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 2×2 in multiple pages,

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

etc.

(untested)

Leave a Comment