Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

r - Lattice plots in for loop - empty images created

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...