Saving 100s of ggplots from RStudio automatically (simultaneously)

At this point, it's very hard to tell why you're getting the error. If it's possible for you to post example data I may be able to help further. Also, please share the code that you used to run the function.

In the mean time, here's another version of the function that can be applied to built in data sets, like iris

plot_histograms <- function(df, key = "key-value", pair = "pair-value", outdir = getwd()) {
  library(ggplot2)
  
  ncol_df <- ncol(df)
  for (index in seq_len(ncol_df)) {
    # do whatever needs to be done here to produce a plot for a column
    # I'm using qplot() just to make things easy
    g <- qplot(x = df[, index], bins = 10) +
      ggtitle(paste(key, pair, index, sep = " - "))
    
    outfile <- sprintf("%s_%s_%03d.pdf", key, pair, index)
    ggsave(filename = file.path(outdir, outfile), g)
  }
}

# Run on iris
plot_histograms(iris, "Key", "Pair")
## Saving 7.12 x 8.33 in image
## Saving 7.12 x 8.33 in image
## Saving 7.12 x 8.33 in image
## Saving 7.12 x 8.33 in image
## Warning: Ignoring unknown parameters: bins
## Saving 7.12 x 8.33 in image

As you can tell from the output, 5 plots were created and then saved to my working directory with names like Key_Pair_001.pdf, looking like this:

1 Like