【问题标题】:Saving plots with different filenames using R使用 R 保存具有不同文件名的绘图
【发布时间】:2015-02-02 06:52:59
【问题描述】:

在为绘图微调参数时,我想将所有测试运行保存在不同的文件中,这样它们就不会丢失。到目前为止,我设法使用下面的代码来做到这一点:

# Save the plot as WMF file - using random numbers to avoid overwriting
  number <- sample(1:20,1)
  filename <- paste("dummy", number, sep="-")
  fullname <- paste(filename, ".wmf", sep="")
  # Next line actually creates the file
  dev.copy(win.metafile, fullname)
  dev.off() # Turn off the device

这段代码有效,生成名称为“dummy-XX.wmf”的文件,其中 XX 是 1 到 20 之间的随机数,但看起来很麻烦,一点也不优雅。

有没有更优雅的方法来完成同样的事情?甚至,要计算代码运行了多少次并为文件生成漂亮的渐进式数字?

【问题讨论】:

    标签: r plot filenames


    【解决方案1】:

    如果你真的想增加(以避免覆盖已经存在的文件),你可以创建一个像这样的小函数:

    createNewFileName = function(path  = getwd(), pattern = "plot_of_something", extension=".png") {
      myExistingFiles = list.files(path = path, pattern = pattern)
      print(myExistingFiles)
      completePattern = paste0("^(",pattern,")([0-9]*)(",extension,")$")
      existingNumbers  = gsub(pattern = completePattern, replacement = "\\2", x = myExistingFiles)
    
      if (identical(existingNumbers, character(0)))
        existingNumbers = 0
    
      return(paste0(pattern,max(as.numeric(existingNumbers))+1,extension))
    }
    
    # will create the file myplot1.png
    png(filename = createNewFileName(pattern="myplot"))
    hist(rnorm(100))
    dev.off()
    
    # will create the file myplot2.png
    png(filename = createNewFileName(pattern="myplot"))
    hist(rnorm(100))
    dev.off()
    

    【讨论】:

    • 谢谢,对于我的情况,这是一个非常完整的功能。毕竟我可以看到我设计的方法还不错。
    【解决方案2】:

    如果你要打印很多图,你可以这样做

    png("plot-%02d.png")
    plot(1)
    plot(1)
    plot(1)
    dev.off()
    

    这将创建三个文件“plot-01.png”、“plot-02.png”、“plot-03.png”

    您指定的文件名可以采用sprintf-like 格式,其中传入的绘图索引。请注意,当您打开新图形设备时会重置计数,因此需要完成对 plot() 的所有调用在致电dev.off()之前。

    但请注意,使用此方法时,它不会查看已存在的文件。它总是将计数重置为 1。此外,没有办法将第一个索引更改为 1 以外的任何值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多