【问题标题】:How do I save or plot from within lists如何从列表中保存或绘图
【发布时间】:2017-06-15 13:30:50
【问题描述】:

我已经命名了来自 qplot 或 ggplot 的实体列表(对象、列表、grobs?),它们可以自行渲染或保存,但我不知道如何将它们作为列表或向量传递给安排。我相信我的问题是一般提取列表对象而不是 ggplot2。

library(ggplot2)
library(grid)
library(gridExtra)

# Generate a named list of ggplots
plotlist <- list()
for(a in c(1:4)) {
    for(b in c(1:4)) {
        plotlist[[paste0("Z",a,b)]] <-
            qplot(rnorm(40,a,b),
                  geom="histogram",
                  xlab=paste0("Z",a,b))
    }
}

# Arrange and display them
# The following two lines work fine, so the plots are in there:
plotlist[["Z12"]]
ggsave(plot=plotlist[["Z12"]], filename="deletable.png")

# The following two lines complain about not being 'grobs'
grid.arrange(plotlist, widths=c(1,1), ncol=2)
grid.arrange(unlist(plotlist), widths=c(1,1), ncol=2)

我可以在不明确命名的情况下以某种方式将它们转换为 grobs,或者找到一个替代 unlist 的方法来让 grob 退出?

【问题讨论】:

  • 你能加入reproducible example吗?
  • @RobertMc 我的原始帖子已经包含一个可重复的示例,该示例遵循 Joris 的指导方针,并通过复制并粘贴到控制台中工作,除了 library() 语句。我会添加它们。

标签: r list ggplot2 r-grid


【解决方案1】:

使用lapply(plotlist, ggplot2::ggplotGrob) 生成 ggplot2 grobs 列表。然后可以将此 grobs 列表传递给 gridExtra::grid.arrange

例如:

library(ggplot2)
library(gridExtra)

plotlist <- list()

for(a in c(1:4)) {
    for(b in c(1:4)) {
        plotlist[[paste0("Z",a,b)]] <-
            qplot(rnorm(40,a,b),
                  geom="histogram",
                  xlab=paste0("Z",a,b))
    }
}

grid.arrange(grobs = lapply(plotlist, ggplotGrob), widths = c(1, 1), ncol = 2)

【讨论】:

  • 在测试这个建议时,我发现只要明确使用“grobs = plotlist”而不是“plotlist”就可以清除错误。 "grobs =lapply(plotlist, ggplotGrob)" 更加明确,也可以完美运行。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2018-02-14
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
相关资源
最近更新 更多