Save several ggplots to files

帅比萌擦擦* 提交于 2019-12-07 08:09:28

You need to specify the argument plot in ggsave :

ggsave(plot = plot, file = "save.pdf")

If you have several ggplot you need to save them in a list first.

plotlist = list()
plotlist[[1]] = plot1
plotlist[[2]] = plot2

etc. Or any other way. Once you end up with the list you can loop on it :

for(i in 1:2){
  ggsave(plot = plot[[i]], file = paste("file",i,".pdf",sep=""))
}

That will save you the plots in file1 file2 etc.

You can use get to get the object based on the name:

library(ggplot2)

plot_1 <- qplot(mpg, wt, data = mtcars)
plot_2 <- qplot(mpg, wt, data = mtcars, geom="path")
plot_3 <- qplot(mpg, data = mtcars, geom = "dotplot")

plot_names <- c("plot_1", "plot_2", "plot_3")

for (i in 1:length(plot_names)) {
  ggsave(filename=sprintf("%s.pdf", plot_names[i]), 
         plot=get(plot_names[i]))
}

But, you are really better off storing your plots in a list and iterating over the list elements:

plots <- list(length=3)
plots[[1]] <- qplot(mpg, wt, data = mtcars)
plots[[2]] <- qplot(mpg, wt, data = mtcars, geom="path")
plots[[3]] <- qplot(mpg, data = mtcars, geom = "dotplot")

for (i in 1:length(plots)) {
  ggsave(filename=sprintf("plot%d.pdf", i), 
         plot=plots[[i]])
}

You can store them named if you want to use the plot name as the output or add a list element for the name.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!