rggplot2gridextraggsave

Is it possible to pipe a list into ggsave


This works, requires however to create a variable (p):

library(tidyverse)
library(gridExtra)

p <- mtcars %>% 
  split(.$cyl) %>% 
    map(~.x %>% ggplot(aes(x=hp,y=qsec)) + geom_point()) 
  
ggsave(filename = "myPlot.pdf", 
       device = "pdf",
       plot = marrangeGrob(p, nrow=1, ncol=1), 
       width = 15, height = 9) 

What I woudl like to do is something like this (code below gives an error):

mtcars %>% 
  split(.$cyl) %>% 
  map(~.x %>% ggplot(aes(x=hp,y=qsec)) + geom_point()) %>% 
    ggsave(filename = "myPlot.pdf", 
           device = "pdf",
           plot = marrangeGrob(., nrow=1, ncol=1), 
           width = 15, height = 9)

Thanks!

Solution

  • You can add {..} around the last code block -

    library(tidyverse)
    library(gridExtra)
    
    mtcars %>% 
      split(.$cyl) %>% 
      map(~.x %>% ggplot(aes(x=hp,y=qsec)) + geom_point()) %>% 
      {  ggsave(filename = "myPlot.pdf", 
             device = "pdf",
             plot = marrangeGrob(., nrow=1, ncol=1), 
             width = 15, height = 9)
      }