4

I have the following bit of code and don't understand why the for loop isn't working. I'm new to this, so excuse me if this is obvious, but it's not actually producing a combined set of graphs (as the more brute force method does below), it just prints out each graph individually

library(ggpubr)
graphs <- lapply(names(hemi_split), function(i){ 
  ggplot(data=hemi_split[[i]], aes(x=type, y=shoot.mass))+
    geom_point()+
    facet_wrap(.~host, scales="free")+ 
    theme_minimal()+
    labs(title=i)
         });graphs

for (i in 1:length(graphs)) {
  ggarrange(graphs[[i]])
} ##not working 

## this works, and is the desired output
ggarrange(graphs[[1]], graphs[[2]], graphs[[3]],
          graphs[[4]], graphs[[5]], graphs[[6]],
          graphs[[7]], graphs[[8]], graphs[[9]],
          graphs[[10]], graphs[[11]])

thank you!

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
Skotani1
  • 149
  • 6

2 Answers2

2

You can use do.call to provide all of the list elements of graphs as arguments of ggarrange:

library(ggpubr)
graphs <- lapply(names(mtcars)[2:5],function(x){
                ggplot(mtcars,aes_string(x = x, y = "mpg")) +
                   geom_point()})
do.call(ggarrange,graphs)

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
2

another solution using purrr

library(tidyverse)
ggraphs <- map(names(mtcars)[2:5],
            ~ ggplot(mtcars,aes_string(x = .x, y = "mpg")) +
              geom_point())

ggarrange(plotlist = ggraphs)
Yuriy Saraykin
  • 8,390
  • 1
  • 7
  • 14