在页面上布置多个ggplot图 [英] Lay out multiple ggplot graphs on a page
问题描述
我在循环内生成ggplot对象的列表,如下所示:
I generate a list of ggplot objects inside a loop as follows:
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")
}
取决于数据集,myPlot中可能有4到10个图.我现在想将它们打印在两行的一页上,并尝试了各种方法,但均获得了不同程度的成功.最有前途的方法是
Depending on the dataset, there could be between 4 and 10 plots in myPlots. I now want to print them on one page in two rows, and have tried various methods with varying degrees of success. The most promising approach is
library(ggpubr)
grid.arrange(myPlots[[1]], myPlots[[2]], myPlots[[3]], myPlots[[4]],
myPlots[[5]], myPlots[[6]], myPlots[[7]], myPlots[[8]], nrow = 2)
这显然很有效,但是需要我枚举所有对象,而且我不知道会有多少个对象.我试图通过写来简化
This clearly works, but requires me to enumerate all the objects, and I don't know how many objects there will be. I tried to simplify this by writing
ggarrange(myPlots, nrow = 2)
但收到警告消息:
Warning message:
In as_grob.default(plot) : Cannot convert object of class list into a grob.
我做错了什么,该如何解决?理想情况下,简单的一行代码将打印存储在myPlots中的所有图分成两行.
What am I doing wrong, and how can I fix this? Ideally, a simple, single, line of code will print all the plots stored in myPlots in two rows.
预先感谢
托马斯·飞利浦
推荐答案
ggpubr::ggarrange
只是cowplot::plot_grid()
的包装.
但是,如果您想继续使用ggpubr
,则可以继续使用ggarrange
.并且您需要将所有图解保存在列表中,并使用plotlist
自变量.
But if you want to stay with ggpubr
, then you can keep using ggarrange
. And you need to save all your plots in a list, and use plotlist
argument.
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))
这篇关于在页面上布置多个ggplot图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!