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

GodinA picture GodinA · Dec 10, 2013 · Viewed 32.3k times · Source

I have several ggplots as objects on my ls. I want to save them as separate files (although I would also be interested to know how to save them all under 1 big file). I have read this: question and question but I can't seem to adapt the code. I also tried to plot them all in one big file as suggested here but do get this error: Error in do.call("grid.arrange", plots2[[i]]) : second argument must be a list. There's something that I am missing in getting all the ggplots in one list.

This is what I've tried so far:

> ls() #List of objects on my ls. All the p* are my ggplots that I want to save.
[1] "all"     "dat"     "dat2"    "dat3"    "data"    "dlook"   "dlook2"  "dlook3"  "i"       "look2"   "mdfx"   
[12] "objects" "order"   "p"       "p1"      "p10"     "p11"     "p12"     "p13"     "p14"     "p15"     "p16"    
[23] "p17"     "p18"     "p19"     "p2"      "p3"      "p4"      "p5"      "p6"      "p7"      "p8"      "p9"    

> objects<-ls()
> plot<-objects[14:30]
> plots
 [1] "p1"  "p10" "p11" "p12" "p13" "p14" "p15" "p16" "p17" "p18" "p19" "p2"  "p3"  "p4"  "p5"  "p6"  "p7"  "p8"  "p9" 

> class(plots)
[1] "character"

plots2<-as.list(plots)#Transform into a list. 

library(gridExtra) #Code suggested to create one pdf file.
pdf("test.pdf", onefile = TRUE)
for (i in seq(length(plots2))) {
  do.call("grid.arrange", plots2[[i]])  
}
dev.off()

Answer

baptiste picture baptiste · Dec 10, 2013

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,

ggsave("arrange.pdf", arrangeGrob(grobs = l))

or arrange them 2x2 in multiple pages,

ggsave("arrange2x2.pdf", marrangeGrob(grobs = l, nrow=2, ncol=2))

etc.

(untested)