God*_*inA 21 r image save ggplot2
我有几个ggplots作为我的ls上的对象.我想将它们保存为单独的文件(虽然我也有兴趣知道如何将它们全部保存在1个大文件中).我读过这个:问题和问题,但我似乎无法适应代码.我也尝试将它们全部放在一个大文件中,如此处所示,但确实得到了这个错误:Error in do.call("grid.arrange", plots2[[i]]) : second argument must be a list.在一个列表中获取所有ggplots时,我遗漏了一些东西.
这是我到目前为止所尝试的:
> 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()
Run Code Online (Sandbox Code Playgroud)
bap*_*ste 49
最好把你的情节列在清单中
l = mget(plots)
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地逐页打印,
pdf("all.pdf")
invisible(lapply(l, print))
dev.off()
Run Code Online (Sandbox Code Playgroud)
或者每个文件保存一个图,
invisible(mapply(ggsave, file=paste0("plot-", names(l), ".pdf"), plot=l))
Run Code Online (Sandbox Code Playgroud)
或者将它们整理在一页中,
ggsave("arrange.pdf", arrangeGrob(grobs = l))
Run Code Online (Sandbox Code Playgroud)
或者将它们排列成多页2x2,
ggsave("arrange2x2.pdf", marrangeGrob(grobs = l, nrow=2, ncol=2))
Run Code Online (Sandbox Code Playgroud)
等等
(另)
作为充实 Joran 评论的示例以及 Baptiste 答案的补充,这就是初始化列表并将绘图预先存储在列表中的方法:
plots <- list()
plots[[1]] <- ggplot(...) # code for p1
plots[[2]] <- ggplot(...) # code for p2
## Depending on if your plots are scriptable, you could use a loop
for (i in 3:10) {
plots[[i]] <- ggplot(...) # code for plot i
}
Run Code Online (Sandbox Code Playgroud)
那么这个列表,plots,对应于l巴蒂斯特的答案。
使用列表时,单括号 ,[用于子列表,必须使用双括号[[来获取列表的元素。例如,plots[[1]]将为您提供ggplot的第一个元素的对象plots,但plots[1]将为您提供一个长度为 1 的列表,其中包含第一个图作为元素。一开始这可能看起来令人困惑,但它是有道理的,特别是如果您只想绘制前三个图,那么您可以在巴蒂斯特的任何示例中使用myplots[1:3]而不是。l(请参阅?"["获取更多详细信息。)
每当您发现自己用数字按顺序命名变量时,例如,x1, x2, x3,就很好地表明您应该使用列表。
请注意,您不必使用lapply。假设您有一个包含所有图解的列表:
MyPlots = list(plot1, plot2, plot3)
Run Code Online (Sandbox Code Playgroud)
只需使用:
pdf("all.pdf")
MyPlots
dev.off()
Run Code Online (Sandbox Code Playgroud)
如果情节p1,p10等已经存在,并且你希望他们保存p1.pdf,等等,那么我认为这应该这样做:
lapply(plots,function(x){ggsave(file=paste(x,"pdf",sep="."),get(x))})
Run Code Online (Sandbox Code Playgroud)
ggsave(...) 有许多参数用于指定输出文件的维度和格式.