在页面上布置多个 ggplot 图

Lay out multiple ggplot graphs on a page

我在循环内生成一个 ggplot 对象列表,如下所示:

myPlots = list()
for(i in 1:length(maturities)){
  myPlots[[i]] <- ggplot(deltaIR.df, aes(sample = deltaIR.df[,i])) + 
                  stat_qq() + stat_qq_line() + 
                  labs(title=maturities[i],
                  x = "Theoretical (Normal)", 
                  y = "Empirical Distribution")
}

根据数据集,myPlots 中可能有 4 到 10 个绘图。我现在想把它们打印在一页上,分两行,试过各种方法,都取得了不同程度的成功。最有前途的方法是

library(ggpubr)
grid.arrange(myPlots[[1]], myPlots[[2]], myPlots[[3]], myPlots[[4]], 
             myPlots[[5]], myPlots[[6]], myPlots[[7]], myPlots[[8]], nrow = 2)

这显然有效,但需要我枚举所有对象,而且我不知道会有多少对象。我试图通过写

来简化这个
ggarrange(myPlots, nrow = 2)

但收到一条警告消息:

Warning message:
In as_grob.default(plot) : Cannot convert object of class list into a grob.

我做错了什么,我该如何解决?理想情况下,一行简单的单行代码会将存储在 myPlots 中的所有图表分两行打印出来。

提前致谢

托马斯·飞利浦

您可以使用 cowplot::plot_grid 来获得它。

这是一个假数据的例子:

##List with ten datasets
set.seed(3)
l <- lapply(1:10, function(i)tibble(
  letter = letters,
  values = rnorm(26)
))

##List of ten different plots
plot_list_1 <- lapply(l, function(i)i %>% ggplot(aes(x = values)) + geom_density())

##Display ten plots
cowplot::plot_grid(plotlist = plot_list_1,nrow = 2)

##Display four plots
cowplot::plot_grid(plotlist = plot_list_1[1:4],nrow = 2)

ggpubr::ggarrange 只是 cowplot::plot_grid().

的包装

但如果您想继续使用 ggpubr,则可以继续使用 ggarrange。您需要将所有地块保存在列表中,并使用 plotlist 参数。

library(ggpubr)
library(ggplot2)
library(purrr)

myplot <- function(color){
    ggplot(iris,aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(color = color)
}
plot_list <- map(c("red","green","blue","black","orange"),myplot)


ggarrange(plotlist = plot_list,nrow = 2,ncol = ceiling(length(plot_list)/2))

这对我有用,它与您已经使用的代码相似。

library(gridExtra)    
grid.arrange(grobs=myPlots, nrow=2)

只需在 'myPlots' 之前添加“plotlist”即可声明 myPlots 是一个列表,如文档所述

ggarrange(plotlist = myPlots, nrow = 2)