如何从列表中保存或绘图
How do I save or plot from within lists
我已经命名了来自 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 出来?
使用lapply(plotlist, ggplot2::ggplotGrob)
生成ggplot2 grobs列表。然后可以将此 grob 列表传递给 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)
我已经命名了来自 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 出来?
使用lapply(plotlist, ggplot2::ggplotGrob)
生成ggplot2 grobs列表。然后可以将此 grob 列表传递给 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)