简体   繁体   English

像png中一样在ggsave中自动为文件编号

[英]Automatic file numbering in ggsave as in png

In png() , the first argument is filename = "Rplot%03d.png" which causes files to be generated with ascending numbers. png() ,第一个参数是filename = "Rplot%03d.png" ,这将导致文件以升序生成。 However, in ggsave, this doesn't work, the number always stays at the lowest number (Rplots001.png") and this file is always overwritten. 但是,在ggsave,此操作不起作用,该数字始终保持为最低数字(Rplots001.png“),并且该文件始终被覆盖。

Looking at the code of the grDevices-functions (eg grDevices::png() it appears that the automatic naming happens in functions which are called by .External() 综观的grDevices函数的代码(例如grDevices::png()似乎自动命名发生在其被调用的函数.External()

Is there already an implementation of this file naming functionality in R such that it is accessible outside of the grDevices functions? R中是否已经有此文件命名功能的实现,以便可以在grDevices函数之外访问它?

Edit: asked differently, is there a way to continue automatic numbering after shutting off and restarting a device? 编辑:问不同,在关闭并重新启动设备后,是否可以继续自动编号? For example, in this code, the two later files overwrite the former ones: 例如,在此代码中,后面的两个文件将覆盖前一个文件:

png(width = 100)
plot(1:10)
plot(1:10)
dev.off()
png(width = 1000)
plot(1:10)
plot(1:10)
dev.off()

You can write a function to do this. 您可以编写一个函数来执行此操作。 For example, how about simply adding a time stamp. 例如,简单地添加时间戳如何。 something like: 就像是:

fname = function(basename = 'myfile', fileext = 'png'){
  paste(basename, format(Sys.time(), " %b-%d-%Y %H-%M-%S."), fileext, sep="")
}

ggsave(fname())

Or, if you prefer sequential numbering, then something along the lines of 或者,如果您更喜欢顺序编号,则遵循

next_file = function(basename = 'myfile', fileext = 'png', filepath = '.'){
  old.fnames = grep(paste0(basename,' \\d+\\.', fileext,'$'), 
    list.files(filepath), value = T)
  lastnum = gsub(paste0(basename,' (\\d+)\\.', fileext,'$'), '\\1', old.fnames)
  if (!length(lastnum)) { 
    lastnum = 1 
  } else {
    lastnum = sort(as.integer(lastnum),T)[1] + 1L 
  }
  return(paste0(basename, ' ', sprintf('%03i', lastnum), '.', fileext))
}

ggsave(next_file())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM