Brandon Bertelsen
Brandon Bertelsen

Reputation: 44708

Saving a list of plots by their names()

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

Upvotes: 8

Views: 7977

Answers (2)

datasci-iopsy
datasci-iopsy

Reputation: 345

@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]]
        )
    })

Upvotes: 1

kohske
kohske

Reputation: 66902

probably you need to pass the names of list:

lapply(names(plots), 
  function(x)ggsave(filename=paste(x,".jpeg",sep=""), plot=plots[[x]]))

Upvotes: 22

Related Questions