sara_khan sara_khan - 1 year ago 60
R Question

Using grid_extra after looping with ggplot2

I am have to run many ggplots on my data and so am trying to loop through variables. I would like to place the plots in a grid arrangement using grid_extra. I have managed to write code for the loop in order to create the plots for my list but am unsure how to extend that to grid extra. Here is my code:

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())

}

Answer Source

Here you go. We also added some hints in the inline comments. Let us know if anything is unclear for you.

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download