我在循环内生成一个 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")
}
Run Code Online (Sandbox Code Playgroud)
根据数据集的不同,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)
Run Code Online (Sandbox Code Playgroud)
这显然有效,但需要我枚举所有对象,我不知道会有多少对象。我试图通过写作来简化这一点
ggarrange(myPlots, nrow = 2)
Run Code Online (Sandbox Code Playgroud)
但收到警告信息:
Warning message:
In as_grob.default(plot) : Cannot convert object of class list into a grob.
Run Code Online (Sandbox Code Playgroud)
我做错了什么,我该如何解决?理想情况下,一行简单的代码将打印存储在 myPlots 中的所有图分两行。
提前致谢
托马斯·菲利普斯
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))
Run Code Online (Sandbox Code Playgroud)