I'm trying to write a function in which a grouping variable gets handed over to a ggplot2 expression.
# 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)
This works
g <- ggplot(df, aes(x, y, color = grp1)) +
geom_line()
print(g)
This doesn't work
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
This doesn't work either (inspired by 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