简体   繁体   中英

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. However, in ggsave, this doesn't work, the number always stays at the lowest number (Rplots001.png") and this file is always overwritten.

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

Is there already an implementation of this file naming functionality in R such that it is accessible outside of the grDevices functions?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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