Saving multiple ggplots from ls into one and separate files in R

It's best to have your plots in a list

l = mget(plots)

Then you can simply print them page-by-page,

pdf("all.pdf")
invisible(lapply(l, print))
dev.off()

or save one plot per file,

invisible(mapply(ggsave, file=paste0("plot-", names(l), ".pdf"), plot=l))

or arrange them all in one page,

   # On Windows, need to specify device
    ggsave("arrange.pdf", arrangeGrob(grobs = l), device = "pdf")

or arrange them 2x2 in multiple pages,

  # need to specify device on Windows 
    ggsave("arrange2x2.pdf", marrangeGrob(grobs = l, nrow=2, ncol=2),
device = "pdf")

etc.

(untested)


Note that you don't have to work with lapply. Suppose you have a list containing all your plots:

MyPlots = list(plot1, plot2, plot3)

Just use:

pdf("all.pdf")
MyPlots
dev.off()

If the plots p1, p10, etc. already exist, and you want them saved as p1.pdf, etc., then I think this should do it:

lapply(plots,function(x){ggsave(file=paste(x,"pdf",sep="."),get(x))})

ggsave(...) has a number of arguments for specifying the dimensions and format of the output file.


As an example fleshing out Joran's comment, and a supplement to Baptiste's answer, this is how you would initialize a list and store plots in a list up-front:

plots <- list()
plots[[1]] <- ggplot(...) # code for p1
plots[[2]] <- ggplot(...) # code for p2

## Depending on if your plots are scriptable, you could use a loop

for (i in 3:10) {
    plots[[i]] <- ggplot(...) # code for plot i
}

Then this list, plots, corresponds to l in baptiste's answer.

When using lists, single brackets, [, are used for sublists, where you have to use double brackets [[ to get the element of a list. For example, plots[[1]] will give you the ggplot object that is the first element of plots, but plots[1] will give you a length one list containing that first plot as an element. This may seem confusing at first, but it makes sense, especially if you just wanted to plot the first three plots, then you could use myplots[1:3] instead of l in any of baptiste's examples. (See ?"[" for more details.)

Whenever you catch yourself naming variables sequentially with numbers, e.g., x1, x2, x3, it's a good indication that you should be using a list instead.