将多个ggplot图表排列在一页上

6
我在循环中生成一组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中的所有图表,并分为两行显示。
谢谢提前帮助。
Thomas Philips
4个回答

7

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))

enter image description here


3

你可以使用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)

enter image description here

enter image description here


哈利路亚 - 真是太棒了!我没有想到我必须明确设置plotlist = myPlots并声明nrow和ncol。当我写下ggarrange(plotlist = myPlots, nrow = 2, ncol = ceiling(length(myPlots)/2))时,我得到了我想要的结果。非常感谢您的快速回复!!! - Thomas Philips
没问题。您能否批准并点赞这个答案?谢谢。 - Henry Cyranka
完成!最后一个问题。当我在RStudio的控制台中键入ggarrange(plotlist = myPlots, nrow = 2, ncol = ceiling(length(myPlots)/2))时,我得到了我期望的8个图形。然而,如果我源代码整个脚本,就不会出现任何图像。更令人困惑的是,如果我把光标放在该行上并单击运行,我就能得到这些图形。是否需要执行其他命令才能在源代码时显示它? - Thomas Philips
这可能是设备问题(绘图窗口)。请确保使用dev.off()关闭所有设备。 - Henry Cyranka
我用dev.off()开始运行脚本rm(list = ls(all = TRUE)) #清除工作区中的所有对象 if(!is.null(dev.list()["RStudioGD"])) dev.off() #清除所有图形但它无法显示garrange的结果。当我单独运行这一行时,第一次会收到警告:Warning message: In doTryCatch(return(expr), name, parentenv, handler) : display list redraw incomplete这个警告让你想起了什么吗? - Thomas Philips

0

只需在'myPlots'之前添加"plotlist"来声明myPlots是一个列表,就像文档中所说的那样

ggarrange(plotlist = myPlots, nrow = 2)


0

这对我很有效,而且它与你已经使用的代码类似。

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

1
你可能想要使用 nrow = 2,而不是 ncol,以适应问题。 - camille

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接