如何保存在循环中创建的图表对象

How to save a chart object created in loops

我在几个循环中创建了一个图表,我想在外循环结束时自动将图表写入文件。这是一个玩具示例:

filename <- "mychart"
for(i in 1:5) {
  x <- 1:5
  fun1 <- sample(1:10, 5, replace = TRUE)
  xlim <- c(1, 5)
  ylim <- c(0, 10)
  plot(x, fun1, xlim = xlim, ylim = ylim, type = "l")
  for(j in 1:3)  {
    fun2 <- 2:6 + j
    lines(x, fun2, type = "l", col = "red")
  }
  out.filename <- paste(filename, i, sep = "")
  ## want to save this plot out to disk here!
}

我也想在控制台上创建绘图,这样我就可以看到程序的进度。类似问题的大多数答案似乎都涉及使用单个“plot”语句创建的图,或者不启用控制台图 window。非常感谢任何建议。

我认为这可以满足您的需求:

plotit <- function(i) {
   x = 1:5
   fun1 = sample(1:10, 5, replace=TRUE)
   plot(x, fun1, xlim=c(1,5), ylim=c(0,10), type="l")
   for(j in 1:3)  {
       fun2 = 2:6 + j
       lines(x, fun2, type = "l", col = "red")
   }   
   savePlot(paste0("mychart", i, ".png"), type="png")
}

然后:

for(i in seq(5)) plotit(i)

保存基本图形绘图的典型方法是使用单独的设备函数,例如 pdf()png() 等。您打开具有适当文件名的绘图设备,创建绘图,然后关闭dev.off() 的设备。您的情节是否在 for 循环中创建并不重要。在 ?png.

中查看大量设备(以及底部的示例)

对于您的代码,它应该是这样的:

filename <- "mychart"
for(i in 1:5) {

    out.filename <- paste(filename, i, ".png", sep = "")
    ## Open the device before you start plotting
    png(file = out.filename)
    # you can set the height and width (and other parameters) or use defaults

    x <- 1:5
    fun1 <- sample(1:10, 5, replace = TRUE)
    xlim <- c(1, 5)
    ylim <- c(0, 10)
    plot(x, fun1, xlim = xlim, ylim = ylim, type = "l")
    for(j in 1:3)  {
        fun2 <- 2:6 + j
        lines(x, fun2, type = "l", col = "red")
    }
    ## Close the device when you are done plotting.
    dev.off() 
}