R code doesn't save plot image [duplicate]

本小妞迷上赌 提交于 2021-02-04 13:56:10

问题


The following code produces an 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()
}

回答1:


Well, I'll just write what I wrote in the comments as an answer.

When plotting lattice or ggplot2 plots inside your own loops or functions, you have to explicitly print the lattice/ggplot2 plots

Try this:

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

I believe this part of the R FAQs is relevant here: 7.22 Why do lattice/trellis graphics not work?

EDIT:

I changed the png code to come before the loop and placed dev.off() outside of the loop.

png(filename="plot_%02d.png") will save the first plot as plot_01.png, the second plot as plot_02.png, etc.



来源:https://stackoverflow.com/questions/20129725/r-code-doesnt-save-plot-image

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!