Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

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

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...