0
votes

I have the following problem using R and not found a solution so far:

I have a script where I run several operation and generate some plots. At the end, I would like to have a nice piece of code that automatically saves all the plots generated into the current working directory. So far, I am using:

trellis.device(device="png", filename="Plot_A.png") print(Plot_A) dev.off()

Which is working fine for just one specific plot. Now I am looking for some kind of for loop that takes all the plots and saves them with the name of the plot as a png file

2

2 Answers

0
votes

In grid based plotting packages (lattice and ggplot), you can store the plot in an object and call print on them to trigger actual rendering of the plot. What you could do is not render the image on the spot, but append any plots to a list. Then, at the end, you can loop over the plots and output them.

plot_list = list()
lattice_plot = xyplot()
plot_list = append(plot_list, lattice_plot)

for(plot in plot_list) {
    png('name.png')
    print(plot)
    dev.off()
}
0
votes

Not exactly an answer but an alternative workflow.

If you are saving your plots in order to use it somewhere else, for example to include them in a Word document or in a presentation, you could just put your code in an RMarkdown document and knitr it to generate an html or doc document with all the output generated by the code, including plots. With RStudio all that could be done with a few clicks.

It may even be easier to take all plots from the Word document than from a folder of png files.