我正在尝试编写一个函数,其中一个分组变量被移交给一个 ggplot2 表达式。
# sample data
df <- data.frame(x = rep(1:20, 5), y = rnorm(100),
grp1 = c(rep("A", 20), rep("B", 20), rep("C", 20), rep("D", 20), rep("E", 20)),
grp2 = c(rep("X", 50), rep("Y", 50)),
stringsAsFactors = TRUE)
这有效
g <- ggplot(df, aes(x, y, color = grp1)) +
geom_line()
print(g)
这不起作用
plot_this <- function(mydf, mygroup) {
g <- ggplot(mydf, aes(x, y, color = mygroup)) +
geom_line()
}
p <- plot_this(df, grp2)
print(p)
Error in FUN(X[[i]], ...) : object 'grp2' not found
这也不起作用(受 dplyr 启发)
plot_this <- function(mydf, mygroup) {
mygroup <- enquo(mygroup)
g <- ggplot(mydf, aes(x, y, color = (!! mygroup))) +
geom_line()
}
p <- plot_this(df, grp2)
print(p)
Error in FUN(X[[i]], ...) : object 'grp2' not found