r - 网格从评估的文本中排列多个 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)
我怎样才能解决这个问题?
解决方案
可以lapply
这样实现:
注意:为了制作geom_histogram
和geom_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'
推荐阅读
- server-side-rendering - 如何渲染 Svelte 服务器端?
- python-3.x - 如何在不使用 Pandas 的情况下使用 python 截断 CSV 文件中的值
- php - 无法使用 woocommerce cart rest api 将产品添加到购物车
- can-bus - 在 CAPL 中收到 ACK 后发送 CAN 帧(使用 CAPL 中的延迟/定时器)
- css - flex-model中溢出的滚动条
- python - 不使用循环的序列
- spring - 可分页未通过 @ManyToMany 关系给出预期结果
- reactjs - 当用户更改另一个 TextInput 的值时,一个 TextInput 的值会更改
- javascript - 如何使每个创建的详细按钮都可以参考每个数据
- c# - 从屏幕上剪切图像并保存