在 for 循环中制作的多个 ggplot2 图的网格 [英] Grid of multiple ggplot2 plots which have been made in a for loop
问题描述
作为一个新的 ggplot2 用户,我对各种可能性感到有点迷茫,并且很难在网上找到一个简单的答案来解决我认为是一个简单的问题.
as a new ggplot2 user, I am a bit lost with the amount of possibilities, and struggle to find on the net a simple answer to what I consider a simple problem.
我想在同一张纸上显示来自 ggplot2 的多个图,但知道这些图来自 for 循环.
I would like to display multiple plots from ggplot2 on a same sheet, BUT knowing that these plots come from a for loop.
以下例子无法编译,仅作说明:
Following example does not compile, it is only to illustrate :
for(i in c(1:n)){
for(j in c(1:m)){
.......... # some data production
p <- ggplot(df.all) + geom_bar(aes_string(x=class.names[i],fill=var.names[j])
}}
在这里,p 被覆盖,但我想要一个矩阵或一个列表,我可以在其中放置所有生成的 p,然后是一个像
Here, p is overwritten, but I would like to have instead a matrix or a list in which I can put all the p as they are produced, then a simple function like
display_in_a_grid(list_of_ggplot_plots)
但据我尝试,我无法列出绘图矩阵,也无法找到仅接受一个输入参数的函数.
But as far as I tried, I was not able to make a list of matrix of plot, neither to find a function that takes only one argument for input.
关于我看过的东西:
"arrangeGrob" 不起作用,因为它需要每个图的显式名称(例如:p1,p2,p3,...),就像 http://code.google.com/p/gridextra/wiki/arrangeGrob
"arrangeGrob" from package gridExtra doesn't work because it requires an explicit name for each plot (e.g.: p1,p2,p3,...) like in http://code.google.com/p/gridextra/wiki/arrangeGrob
ggplot2 的facet"方法不适用于我的数据集的组织(或相反:p)
"facet" method of ggplot2 is not adapted to the organization of my data set (or the contrary :p )
你有一个简单的方法来管理这个吗?
Would you have a simple way to manage this ?
谢谢,
弗朗索瓦
推荐答案
我倾向于同意 Richie,但如果你想自己安排:
I would be inclined to agree with Richie, but if you want to arrange them yourself:
library(gridExtra)
library(ggplot2)
p <- list()
for(i in 1:4){
p[[i]] <- qplot(1:10,10:1,main=i)
}
do.call(grid.arrange,p)
查看 ?arrangeGrob
末尾的示例,了解完全消除 for 循环的方法:
take a look at the examples at the end of ?arrangeGrob
for ways to eliminate the for loop altogether:
plots = lapply(1:5, function(.x) qplot(1:10,rnorm(10),main=paste("plot",.x)))
require(gridExtra)
do.call(grid.arrange, plots)
这篇关于在 for 循环中制作的多个 ggplot2 图的网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!