8

Let's say I have a list of plots that I've created.

library(ggplot2)
plots <- list()
plots$a <- ggplot(cars, aes(speed, dist)) + geom_point()
plots$b <- ggplot(cars, aes(speed)) + geom_histogram()
plots$c <- ggplot(cars, aes(dist)) + geom_histogram()

Now, I would like to save all of these, labelling each with their respective names(plots) element.

lapply(plots, 
       function(x) { 
         ggsave(filename=paste(...,".jpeg",sep=""), plot=x)
         dev.off()
         }
       )

What would I replace "..." with such that in my working directory the plots were saved as:

a.jpeg
b.jpeg
c.jpeg
Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255

2 Answers2

22

probably you need to pass the names of list:

lapply(names(plots), 
  function(x)ggsave(filename=paste(x,".jpeg",sep=""), plot=plots[[x]]))
kohske
  • 65,572
  • 8
  • 165
  • 155
1

@kohske's answer is sensational! Below is the purrr 0.3.4 version for those who may prefer working within tidyverse. Also, a temporary directory is created to hold the plots since ggsave defaults to saving to the working directory.

map(names(plots), function(.x) {
    ggsave(
        path = "tmp/",
        filename = paste0(.x, ".png"),
        plot = plots[[.x]]
        )
    })
DataSci-IOPsy
  • 308
  • 2
  • 11