R 代码不保存绘图图像 [英] R code doesn't save plot 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()
}
推荐答案
好吧,我会写下我在评论中写的内容作为答案.
Well, I'll just write what I wrote in the comments as an answer.
在您自己的循环或函数中绘制 lattice
或 ggplot2
图时,您必须明确地print
lattice
>/ggplot2
绘图
When plotting lattice
or ggplot2
plots inside your own loops or functions, you have to explicitly print
the lattice
/ggplot2
plots
试试这个:
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()
我相信 R 常见问题的这一部分在这里是相关的:7.22 为什么格子/格子图形不起作用?
I believe this part of the R FAQs is relevant here: 7.22 Why do lattice/trellis graphics not work?
我将 png
代码更改为位于循环之前,并将 dev.off()
置于循环之外.
I changed the png
code to come before the loop and placed dev.off()
outside of the loop.
png(filename="plot_%02d.png")
将第一个图保存为 plot_01.png
,第二个图保存为 plot_02.png
等
png(filename="plot_%02d.png")
will save the first plot as plot_01.png
, the second plot as plot_02.png
, etc.
这篇关于R 代码不保存绘图图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!