问题
I know, similar questions were asked before, but the answer was not fully explained and / or the the solution didn't work for my case, so:
How do you arrange several ggplots that created with a loop on one page?
Searching for the answer, I found some that might have worked if each plot had its own name. For example, grid_arrange_shared_legend might be just what I need, but with the loop I created each plot is written over the previous. So maybe the question is: is there a way to give each ggplots unique name?
To give a better feel for my specific situation, here is a code that about replicates it on the mtcars database; histogram of average mpg for different gears, one histogram for each cylinders:
library(dplyr)
library(ggplot2)
cylinder<-unique(mtcars$cyl)
for (value in cylinder) {
m<-mtcars%>%
filter(cyl==value)%>%
group_by (gear)%>%
summarise(number=n(), average=mean(mpg), se=sd(mpg))
print(m) # reporting the numbers
a<-m%>%
mutate(gear=factor(gear, levels=unique(gear)))%>%
ggplot()+
geom_bar(aes(x=gear, y=average), stat = 'identity', fill ='red') +
geom_errorbar( aes(x= gear, ymin=average-se, ymax=average+se), width=0.2, colour="black", alpha=1, size=1) +
xlab("gears") + ylab("average mpg") +
ggtitle (paste( "cyliner:", value ))+
theme(axis.ticks.x=element_blank())
print(a) }
回答1:
Try this using patchwork
. Your loop is well defined. You only need to create a list to store the plots and then use wrap_plots()
from patchwork
to arrange the plots in one page. Here the code:
library(dplyr)
library(ggplot2)
library(patchwork)
#Create list
List <- list()
cylinder<-unique(mtcars$cyl)
#Loop
for (value in seq_along(cylinder)) {
m<-mtcars%>%
filter(cyl==cylinder[value])%>%
group_by (gear)%>%
summarise(number=n(), average=mean(mpg), se=sd(mpg))
print(m) # reporting the numbers
a<-m%>%
mutate(gear=factor(gear, levels=unique(gear)))%>%
ggplot()+
geom_bar(aes(x=gear, y=average), stat = 'identity', fill ='red') +
geom_errorbar( aes(x= gear, ymin=average-se, ymax=average+se), width=0.2, colour="black", alpha=1, size=1) +
xlab("gears") + ylab("average mpg") +
ggtitle (paste( "cyliner:", value ))+
theme(axis.ticks.x=element_blank())
print(a)
List[[value]]<-a}
#Wrap plots
wrap_plots(List,nrow = 1)
Output:
来源:https://stackoverflow.com/questions/65278770/r-ggpot-arranging-on-one-page-several-ggplots-created-with-a-loop-name-each-p