以交互方式,此示例运行良好:
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + facet_grid(. ~ vs)
现在,用公式接口制作一个函数并使用aes_string
它来做同样的事情,它不起作用(错误是:)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)
通过 Joran 的技巧,我在这里指的是,这是我最近发布的一个类似问题。在这种情况下ggplot2
,看不到我的分面请求。让它facet_grid(".~fac2")
没有效果。建议?我一直被这些事情弄得不知所措。谢谢!