Search code examples
rstringggplot2concatenation

Save several ggplots to files


I want to save a changing set of ggplot is different files. To do this I use a for-loop looking something like this:

save = c("plot1","plot2")
for (i in 1:length(save)){
  ggsave(cat(save[i],"\n"), file="i.pdf")
}

"plot1" and "plot2" are working ggplots (=names of the plot objects). Because I got the following error:

Error in ggsave(cat(save[i], "\n"), file = "i.pdf") : 
  plot should be a ggplot2 plot

I tried the cat-function. It returns the same error with or without the function. If I enter the "plot" directly it works...

What am I doing wrong?

(Edited the example so there is more than one plot)


Solution

  • 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.