包装多个ggplot2函数,并将包装器与运算符“一起使用”+&引用;在R
我从问题开始:有没有一种方法可以创建一个函数,比如说包装多个ggplot2函数,并将包装器与运算符“一起使用”+&引用;在R,r,ggplot2,R,Ggplot2,我从问题开始:有没有一种方法可以创建一个函数,比如说ggColors,它将包ggplot2中的几个其他函数包装起来?该函数应使用运算符+(而不是%%>%%运算符)与ggplot对象相加,如本例所示: p <- ggplot(mtcars, aes(hp,disp, color = as.factor(cyl))) + geom_point() p + ggColors() 问题是scale\u color\u manual和scale\u fill\u manual不相加,因为它们不会导
ggColors
,它将包ggplot2
中的几个其他函数包装起来?该函数应使用运算符+
(而不是%%>%%
运算符)与ggplot
对象相加,如本例所示:
p <- ggplot(mtcars, aes(hp,disp, color = as.factor(cyl))) + geom_point()
p + ggColors()
问题是
scale\u color\u manual
和scale\u fill\u manual
不相加,因为它们不会导致函数内的ggplot
对象ggColors
ggColors
应返回打印元素列表。然后,可以使用+
将返回列表的所有元素添加到绘图中:
ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) {
# Some conditions:
if (is.null(values)){
if (cold.colors) {
values <- c("darkblue","blue", "green")
} else {
values <- c("red","orange", "yellow")
}
}
# Modified default values of `ggplot2` functions:
return(list(scale_color_manual(name = name, values = values),
scale_fill_manual (name = name, values = values)))
}
ggColors <- function(values = NULL, name = NULL, cold.colors = TRUE) {
# Some conditions:
if (is.null(values)){
if (cold.colors) {
values <- c("darkblue","blue", "green")
} else {
values <- c("red","orange", "yellow")
}
}
# Modified default values of `ggplot2` functions:
return(list(scale_color_manual(name = name, values = values),
scale_fill_manual (name = name, values = values)))
}
p + ggColors()