for循环中的晶格图-创建空图像 [英] Lattice plots in for loop - empty images created

查看:76
本文介绍了for循环中的晶格图-创建空图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在for循环中生成几个晶格图,但它确实会创建空图像!

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")
}

当我手动"运行for循环的内部时,它可以工作,但是在循环中,它会停止工作.为什么?

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)

推荐答案

第一部分是FAQ(在

The first part is an FAQ (in R docs, and on SO): you must print(mylatticeplot), when not interactive.

此外,例如,您的方法在RStudio中不起作用.

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

这篇关于for循环中的晶格图-创建空图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆