sara_khan sara_khan -3 years ago 88
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:


lflist=list("mpg", "hp", "drat", "wt")
for(i in seq_along(lflist)) {
lfplot=ggplot(data=subset(mtcars, !, aes(x=gear,
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.



# 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, !, aes(x=gear, y=lflist[i])) + 
    stat_summary(fun.y=median, geom="line", aes(group=1), colour="red") +
    stat_summary(fun.y=median, geom="point", colour="red") +
          axis.title.x = element_blank())

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

grid.arrange(grobs = lfplots, nrow = 2, ncol = 2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download