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