How do I arrange a variable list of plots using grid.arrange?

library(ggplot2)
df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)
# In my real example,a plot function will fit a ggplot to a list of datasets
#and return a list of ggplots like the example above.

I'd like to arrange the plots using grid.arrange() in gridExtra.

How would I do this if the number of plots in plist is variable?

This works: grid.arrange(plist[[1]],plist[[2]],plist[[3]],plist[[4]],plist[[5]])

but I need a more general solution. thoughts?

65733 次浏览

这样吧:

library(gridExtra)
n <- length(plist)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(plist, ncol=nCol))

enter image description here

只要在每个函数中使用 grobs =参数指定列表,就可以对列表使用 grid.arrange()arrangeGrob()。例如,在你给出的例子中:

library(ggplot2)
library(gridExtra)
df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)


grid.arrange(grobs = plist, ncol = 2) ## display plot
ggsave(file = OutFileName, arrangeGrob(grobs = plist, ncol = 2))  ## save plot

为了完整起见(作为这个老的,已经回答过的问题 has been revived, recently) ,我想添加一个使用 cowplot包的解决方案:

cowplot::plot_grid(plotlist = plist, ncol = 2)

enter image description here

我知道这个问题特别指出使用 网格号包,但是 拼凑起来包中的 wrap_plots函数是处理可变长度列表的一个很好的方法:

library(ggplot2)
# devtools::install_github("thomasp85/patchwork")
library(patchwork)


df <- data.frame(x=1:10, y=rnorm(10))
p1 <- ggplot(df, aes(x,y)) + geom_point()
plist <- list(p1,p1,p1,p1,p1)


wrap_plots(plist)

enter image description here

A useful thing about it is that you don't need to specify how many columns are required, and will aim to keep the numbers of columns and rows equal. For example:

plist <- list(p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1,p1)
wrap_plots(plist) # produces a 4 col x 4 row plot

了解更多关于 拼凑起来软件包 给你的信息

要将所有的图放在一个页面上,你可以像下面这样计算列和行的数量:

x = length(plots)


cols = round(sqrt(x),0)
rows = ceiling(x/cols)

As most multiple plotting functions have ncol and nrow as arguments you can just put these in there. I like ggarrange from ggpubr.

ggarrange(plotlist = plots, ncol=cols, nrow = rows)

这样更有利于行而不是列,所以如果您想要相反的结果,请反过来。也就是说,对于6个地块,它将给出3行和2列,而不是反过来。