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.
我想安排使用地块grid.arrange()
在gridExtra
。
我将如何做到这一点,如果地块的数量plist
变量?
此工作原理: grid.arrange(plist[[1]],plist[[2]],plist[[3]],plist[[4]],plist[[5]])
但我需要一个更通用的解决方案。 想法?
这个怎么样:
library(gridExtra)
n <- length(plist)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(plist, ncol=nCol))
您可以使用grid.arrange()
和arrangeGrob()
为指定使用列表使用列表只要grobs =
在每个函数参数。 例如,在你给的例子:
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
为了完整起见(和这个老,已经回答的问题已经恢复,最近 ),我想补充使用的解决方案cowplot
包:
cowplot::plot_grid(plotlist = plist, ncol = 2)
我知道这个问题明确规定使用gridExtra包,但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)
关于它的有用的事情是,你并不需要指定多少列是必需的,将致力于保持列和行相等的数量。 例如:
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)
由于大多数多种绘图功能,具有NcoI和nrow作为参数,你可以把这些在那里。 我喜欢ggpubr ggarrange。
ggarrange(plotlist = plots, ncol=cols, nrow = rows)
这有利于更多的行,如果你想的相反比列,以便扭转。 即6个地块它将给3行2列不是周围的其他方式。