Grid of multiple ggplot2 plots which have been made in a for loop

ぃ、小莉子 提交于 2019-11-27 06:45:39

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)

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)

This is my solution. Tiny change in the ggplot function with the mapping parameter to aes_string.

library(gridExtra)
library(ggplot2)
p <- list()
for(i in 1:4){
p[[i]] <- ggplot(data=df,aes_string(x=df$x,y=df$y) +geom_bar(aes_string(x=class.names[i],fill=var.names[j])
}
do.call(grid.arrange,p)

Hope this helps!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!