首页 > 解决方案 > 网格从评估的文本中排列多个 ggplots

问题描述

我正在尝试grid.arrange()从一串文本中调用/评估几个 ggplots。但是,我失败得很惨——只绘制了最后一个图(p4在下面的示例中)。

library(ggplot2)
library(gridExtra)
p <- ggplot(data = mtcars, aes(x = mpg, y = wt, color = cyl))

p1 <- p + geom_point()
p2 <- p + geom_histogram()
p3 <- p + geom_dotplot()
p4 <- p + geom_smooth(method='lm')

tx <- paste0("p", 1:4)

grid.arrange(grobs = list(eval(parse(text = tx))), nrow = 2)

我怎样才能解决这个问题?

标签: rggplot2eval

解决方案


可以lapply这样实现:

注意:为了制作geom_histogramgeom_dotplot工作,我y = wt为两者制作了本地 aes,geom_point否则geom_smooth您的代码会导致错误。

library(ggplot2)
library(gridExtra)
p <- ggplot(data = mtcars, aes(x = mpg, color = cyl))

p1 <- p + geom_point(aes(y = wt))
p2 <- p + geom_histogram()
p3 <- p + geom_dotplot()
p4 <- p + geom_smooth(aes(y = wt), method='lm')

tx <- paste0("p", 1:4)

grid.arrange(grobs = lapply(tx, function(x) eval(parse(text = x))), nrow = 2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bindot()` using `bins = 30`. Pick better value with `binwidth`.
#> `geom_smooth()` using formula 'y ~ x'


推荐阅读