将 ls 中的多个 ggplots 保存到 R 中的一个单独文件中 [英] Saving multiple ggplots from ls into one and separate files in R
问题描述
我的 ls 上有几个 ggplots 作为对象.我想将它们保存为单独的文件(尽管我也想知道如何将它们全部保存在 1 个大文件中).我已阅读此内容:问题和question 但我似乎无法调整代码.我还尝试按照建议将它们全部绘制在一个大文件中 here 但确实会出现此错误:do.call("grid.arrange", plots2[[i]]) 中的错误:第二个参数必须是列表
.在将所有 ggplots 放在一个列表中时,我缺少一些东西.
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()
推荐答案
最好把你的地块放在一个列表中
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")
或将它们 2x2 排列在多个页面中,
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")
等等
(未经测试)
这篇关于将 ls 中的多个 ggplots 保存到 R 中的一个单独文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!