我想在for循环中生成几个格子图,但它确实创建了空图像!
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")
}
Run Code Online (Sandbox Code Playgroud)
当我"手动"运行for循环的内部时,它可以工作,但是在循环中它停止工作.为什么?
以下是生成数据的代码:
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)
Run Code Online (Sandbox Code Playgroud)
第一部分是FAQ(在R docs中,在SO上):你必须打印(mylatticeplot),而不是交互式.
此外,例如,您的方法在RStudio中不起作用.
Error in savePlot(paste0("file_", f), "png") :
can only copy from 'windows' devices
Run Code Online (Sandbox Code Playgroud)
推荐的方式效果更好,工作量更少:
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()
Run Code Online (Sandbox Code Playgroud)