6

The following code produces an image:

library(latticeExtra)
x=runif(40)
y=runif(40)
z=runif(40)
png(filename=paste(i,".png",sep=""))
levelplot(z ~ x + y, panel = panel.levelplot.points, col.regions = rainbow(50))
dev.off()

But the following code does not. Why?

library(latticeExtra)
for(i in seq(1,5)) {
    x=runif(40)
    y=runif(40)
    z=runif(40)
    png(filename=paste(i,".png",sep=""))
    levelplot(z ~ x + y, panel = panel.levelplot.points, col.regions = rainbow(50))
    dev.off()
}
StanLe
  • 5,037
  • 9
  • 38
  • 41
  • For `lattice` plots, I believe that you have to explicitly `print` them to save them in a loop. e.g. `latPlot <- levelplot(...); print(latPlot)` – ialm Nov 21 '13 at 19:11
  • 1
    Also, see this link from the R FAQS: [7.22 Why do lattice/trellis graphics not work?](http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f) – ialm Nov 21 '13 at 19:13

1 Answers1

8

Well, I'll just write what I wrote in the comments as an answer.

When plotting lattice or ggplot2 plots inside your own loops or functions, you have to explicitly print the lattice/ggplot2 plots

Try this:

library(latticeExtra)
png(filename="plot_%02d.png")
for(i in seq(1,5)) {
    x=runif(40)
    y=runif(40)
    z=runif(40)
    # Assign your lattice plot to myPlot
    myPlot <- levelplot(z ~ x + y, panel = panel.levelplot.points, col.regions = rainbow(50))
    print(myPlot)
}
dev.off()

I believe this part of the R FAQs is relevant here: 7.22 Why do lattice/trellis graphics not work?

EDIT:

I changed the png code to come before the loop and placed dev.off() outside of the loop.

png(filename="plot_%02d.png") will save the first plot as plot_01.png, the second plot as plot_02.png, etc.

ialm
  • 8,510
  • 4
  • 36
  • 48
  • I have the same problem but with `plot(NA, xlim = 0:1, ylim = 0:1, bty = "n", axes = 0 )` inside a loop (i.e. `plot()` instead of a `ggplot`). But this solution doesn't seem to work for that. The code I have works fine, but as soon as I place `png()` before it (and `dev.off() after it`, it fails to write a file or even to display the plot in the RStudio viewer pane – stevec Apr 30 '20 at 10:47
  • 1
    @stevec best to ask your question as a new question. As far as I know, `plot()` shouldn't need the `print` workaround – ialm May 04 '20 at 22:15