Interactively, this example works fine:
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + facet_grid(. ~ vs)
Now, make a function with a formula interface and use aes_string
to do this same thing, and it doesn't work (error is: Error in layout_base(data, cols, drop = drop) : At least one layer must contain all variables used for facetting
):
tf <- function(formula, data) {
res <- as.character(formula[[2]])
fac2 <- as.character(formula[[3]][3])
fac1 <- as.character(formula[[3]][2])
# p <- ggplot(aes_string(x = fac1, y = res), data = data)
# p <- p + geom_point() # original attempt
p <- ggplot() # This is Joran's trick, but it doesn't work here
p <- p + geom_point(aes_string(x = fac1, y = res), data = data)
p <- p + facet_grid(.~fac2) # comment this out, and it works but
# of course is not faceted
}
p <- tf(formula = wt ~ am*vs, data = mtcars)
By Joran's trick I refer to here, which is a similar question I posted recently. In this case ggplot2
doesn't see my faceting request. Making it facet_grid(".~fac2")
had no effect. Suggestions? I'm continually out-witted by these things. Thanks!