R code doesn't save plot image
levelplot, plot, png, r
Solution
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.
Problem
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() } ```