【问题标题】:Grid Arrange mutliple ggplots from evaluated text网格从评估的文本中排列多个 ggplots
【发布时间】:2021-03-11 21:53:55
【问题描述】:

我正在尝试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)

我该如何解决这个问题?

【问题讨论】:

    标签: r ggplot2 eval


    【解决方案1】:

    使用lapply 可以这样实现:

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

    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'
    

    【讨论】:

      猜你喜欢
      • 2015-05-29
      • 1970-01-01
      • 2021-09-03
      • 2021-09-25
      • 1970-01-01
      • 2018-01-26
      • 2014-10-11
      • 2013-04-25
      • 1970-01-01
      相关资源
      最近更新 更多