I have written a function in which a lot of plots are being generated. I would like to store all these plot in separate png files, but I do not understand how to do this if I don't want to do them one by one by png().
Essentially my code looks similar to that below, although the variables and other features of the plots are not so regular (then I would have written a for-loop):
make_graphs <-function(MyData){
a <- ggplot(data = MyData, aes(y = Y1, x = X)) + geom_point()
b <- ggplot(data = MyData, aes(y = Y2, x = X)) + geom_point()
c <- ggplot(data = MyData, aes(y = Y3, x = X)) + geom_point()
d <- ggplot(data = MyData, aes(y = Y4, x = X)) + geom_point()
#...etc...
x <- ggplot(data = MyData, aes(y = Y24, x = X)) + geom_point()
y <- ggplot(data = MyData, aes(y = Y25, x = X)) + geom_point()
Z <- ggplot(data = MyData, aes(y = Y26, x = X)) + geom_point()
# Here I need some way to collect all the plots a-z and write them to files.
}
make_graphs(MyData)
In short, I am looking for a way to generate a list of the plots I have assigned to a-z, so that I can use that list to save as a png. Making a list by hand doesn't do the job for me: my plot names are more complex than a-z, and more plots will be added to the function - I don't want to manually have to add them to the list.
Do you have any ideas how to do this?
After having a list, I plan to do something like this:
plotlist = mget(plots)
pdf("all.pdf")
invisible(lapply(plotlist, print))
dev.off()
Or this:
lapply(names(plots),
function(x)ggsave(filename=paste(x,".jpeg",sep=""), plot=plots[[x]]))