R ggpot:在一页上排列几个用循环创建的ggplot,每个图以不同的方式命名 [英] R ggpot: Arranging on one page several ggplots created with a loop / name each plot differenly
问题描述
我知道,之前也曾问过类似的问题,但答案并未得到充分解释和/或解决方案不适用于我的情况,所以:
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:
您如何安排在一个页面上用循环创建的多个ggplots?
How do you arrange several ggplots that created with a loop on one page?
在寻找答案时,我发现如果每个地块都有自己的名称,则可能会起作用.例如,grid_arrange_shared_legend可能正是我所需要的,但是通过我创建的循环,每个图都覆盖了前一个图.所以也许问题是:有没有办法给每个ggplots赋予唯一的名称?
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?
为了更好地了解我的具体情况,以下代码将其复制到mtcars数据库中.不同齿轮的平均mpg直方图,每个气缸一个直方图:
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) }
推荐答案
使用 Patchwork
尝试一下.您的循环定义良好.您只需要创建一个列表来存储图,然后使用 patchwork
中的 wrap_plots()
即可将图布置在一页中.这里的代码:
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)
输出:
这篇关于R ggpot:在一页上排列几个用循环创建的ggplot,每个图以不同的方式命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!