R code doesn't save plot image [duplicate]
Asked Answered
C

1

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()
}
Cr answered 21/11, 2013 at 19:4 Comment(2)
For lattice plots, I believe that you have to explicitly print them to save them in a loop. e.g. latPlot <- levelplot(...); print(latPlot)Streetcar
Also, see this link from the R FAQS: 7.22 Why do lattice/trellis graphics not work?Streetcar
S
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.

Streetcar answered 21/11, 2013 at 19:21 Comment(2)
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 paneTessi
@Tessi best to ask your question as a new question. As far as I know, plot() shouldn't need the print workaroundStreetcar

© 2022 - 2024 — McMap. All rights reserved.