将 ls 中的多个 ggplots 保存到 R 中的一个单独文件中

编程入门 行业动态 更新时间:2024-10-28 09:15:42
本文介绍了将 ls 中的多个 ggplots 保存到 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 中的一个单独文件中

本文发布于:2023-08-05 11:25:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1305220.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   文件   ls   ggplots

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!