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)
You need to specify the argument plot in ggsave :
If you have several ggplot you need to save them in a list first.
etc. Or any other way. Once you end up with the list you can loop on it :
That will save you the plots in file1 file2 etc.
You can use
get
to get the object based on the name:But, you are really better off storing your plots in a
list
and iterating over the list elements:You can store them named if you want to use the plot name as the output or add a list element for the name.