Lattice plots in for loop - empty images created
lattice, plot, r
Solution
The first part is an FAQ (in R docs, and on SO): you must `print(mylatticeplot)`, when not interactive.
In addition, your approach does not work in RStudio, for example.
Error in savePlot(paste0("file_", f), "png") :
can only copy from 'windows' devices
The recommended way works better, and is less work:
png("file_%03d.png")
for (f in unique(df$month)) {
p = bwplot(x ~ country|type, data = df[df$month == f,], panel=function(...) {
panel.abline(h=0, col="green")
panel.bwplot(...)
})
print(p)
}
dev.off()
Problem
I want to produce several lattice plots in a for loop, but it does create empty images!!! ``` for (f in unique(df$month)) { plot.new() bwplot(x ~ country|type, data = df[df$month == f,], panel=function(...) { panel.abline(h=0, col="green") panel.bwplot(...) }) savePlot(paste0("file_", f), "png") } ``` When I run the inner of the for loop "by hand", it works, but in loop it stops working. Why? Here is the code to generate the data: ``` set.seed(123) n <- 300 country <- sample(c("Europe", "Africa", "Asia", "Australia"), n, replace = TRUE) type <- sample(c("city", "river", "village"), n, replace = TRUE) month <- sample(c("may", "june", "july"), n, replace = TRUE) x <- rnorm(n) df <- data.frame(x, country, type, month) ```