Search code examples
rggplot2r-grid

How to get ggplot grobs after using a function that's using an lapply?


I'm trying to arrange the grobs generated from a function using an lapply but there's more data trying to pass into the gList than can be used by the grid function, here's some reproducible code:

library(dplyr)
library(gridExtra)

split_ex <- mtcars %>% split(cyl)
list_ex <- unique(mtcars$cyl)

test_plot <- function(dat){
subtest_plot <- function(type) {
  ggplot(data=dat %>% filter(cyl==type)) +
    geom_col(aes(y=mpg,x=disp)) +
    labs(title=type)
}
lapply(list_ex, function(type) subtest_plot(type))
}

grid.arrange(test_plot(mtcars),ncols=2)

Solution

  • library(dplyr)
    library(grid)
    library(ggplot2)
    library(gridExtra)
    
    split_ex <- mtcars %>% split(cyl)
    list_ex <- unique(mtcars$cyl)
    
    test_plot <- function(dat){
      subtest_plot <- function(type) {
        ggplot(data=dat %>% filter(cyl==type)) +
          geom_col(aes(y=mpg,x=disp)) +
          labs(title=type)
      }
      lapply(list_ex, function(type) subtest_plot(type))
    }
    
    grid.newpage()
    grid.draw(
      arrangeGrob(grobs=test_plot(mtcars), ncol=2)
    )
    

    enter image description here