2017-08-16 69 views
0

我必须在我的数据上运行许多ggplots,所以我试图通过变量循环。我想用grid_extra将这些图放置在网格布局中。我设法为循环编写代码,以便为我的列表创建图,但我不确定如何将其扩展到网格外。这里是我的代码:在使用ggplot2循环后使用grid_extra

data("mtcars") 
mtcars$gear=as.factor(mtcars$gear) 

lflist=list("mpg", "hp", "drat", "wt") 
lfplot=list() 
for(i in seq_along(lflist)) { 
    lfplot=ggplot(data=subset(mtcars, !is.na(gear)), aes(x=gear, 
    y=lflist[i]))+geom_boxplot()+ 
    stat_summary(fun.y=median, geom="line", aes(group=1), colour="red")+ 
    stat_summary(fun.y=median, geom="point", colour="red")+ 
    theme(axis.text.x=element_text(size=8),axis.title.x = element_blank()) 

} 
+1

当试图绘制其中一个时出现错误:'错误:stat_boxplot需要以下缺失美学:y'您在哪里定义'y'?在制作剧情列表之前,你确定你可以绘制每个剧情吗? – Masoud

+0

谢谢你的回复。我在'lflist'中定义了我的y - 这些是我正在循环的变量。我重新运行代码并没有收到错误。 –

+0

我认为@Masoud是正确的。我必须使用'aes_string'修改你的代码,如下所示。 – Lyngbakr

回答

1

在这里你去。我们还在内嵌评论中添加了一些提示。让我们知道是否有什么不清楚的。

library(ggplot2) 

data("mtcars") 
mtcars$gear=as.factor(mtcars$gear) 

# In such simple cases, it is advisable to use vectors rather than list 
# lflist = list("mpg", "hp", "drat", "wt") 
lflist = c("mpg", "hp", "drat", "wt") 
lfplots = list() 

for(i in seq_along(lflist)) { # Hint, you can loop directry over the entries (for element in lflist) 
    # Create your plot 
    lfplot = ggplot(data=subset(mtcars, !is.na(gear)), aes(x=gear, y=lflist[i])) + 
    geom_boxplot()+ 
    stat_summary(fun.y=median, geom="line", aes(group=1), colour="red") + 
    stat_summary(fun.y=median, geom="point", colour="red") + 
    theme(axis.text.x=element_text(size=8), 
      axis.title.x = element_blank()) 

    # Add your plot to the list 
    lfplots[[length(lfplots) + 1]] = lfplot 
} 


library(gridExtra) 
grid.arrange(grobs = lfplots, nrow = 2, ncol = 2) 
+0

非常感谢!完美工作。 –

1

我会用cowplot

data("mtcars") 
mtcars$gear=as.factor(mtcars$gear) 

lflist=list("mpg", "hp", "drat", "wt") 
lfplot=list() 
for(i in seq_along(lflist)) { 
    lfplot[[i]] <- ggplot(data=subset(mtcars, !is.na(gear)), aes_string(x="gear",y=lflist[[i]])) + geom_boxplot() + 
    stat_summary(fun.y=median, geom="line", aes(group=1), colour="red")+ 
    stat_summary(fun.y=median, geom="point", colour="red")+ 
    theme(axis.text.x=element_text(size=8),axis.title.x = element_blank()) 
} 

library(cowplot) 

plot_grid(plotlist = lfplot) 

enter image description here

+0

很多很多谢谢 - 使用我的数据。 –