Using ggsave within a function and changing file name

I have some data that is split by one of my factor variables, and I'm trying to make some plots using ggplot and save them using a function. I've tried doing this:

#loading data and packages
library(tidyverse)
data("iris")

#splitting data according to a factor 
iris_split <- split(iris,iris$Species)
attach(iris_split)

#setting up function to make and save plots
somefunction <- function(x) {
  p <- ggplot(x, aes(x=Petal.Length)) + 
    geom_density()
  
#saving plots
  ggsave(filename = "x_plot.png", device = "png", plot = p)
}

#running function on each dataframe in my list
map(iris_split, somefunction)

In this bit of code, running ggsave with the argument 'filename = "x_plot.png"' causes the plots to be overwritten as the function runs, leaving me with only one plot saved. What I'd like to do instead is to change the name of the file within the function to something based on the dataframe (i.e., setosa_plot.png, versicolor_plot.png, virginica_plot.png).

Does anyone know if there's a way to do this?

One other thing I've tried so far is using deparse(substitute(x)) and paste0() to paste together the dataframe name and "_plot.png", like this:

somefunction <- function(x) {
  p <- ggplot(x, aes(x=Petal.Length)) + 
    geom_density()
 
  deparsed <- deparse(substitute(x))
  saveas <- paste0(deparsed,"_plot.png")
  ggsave(filename = saveas, device = "png", plot = p)
}

map(iris_split, somefunction)

This doesn't work, because instead of saving each plot with a different filename as I'd hoped it would, I instead get one plot (which has presumably overwritten previously saved plots), called ".x[[i]]_plot.png"

Any help would be much appreciated!

You can use the names of the list to construct unique filenames.

#loading data and packages
library(tidyverse)
data("iris")

#splitting data according to a factor 
iris_split <- split(iris,iris$Species)

#setting up function to make and save plots
somefunction <- function(x, fname) {
  p <- ggplot(x, aes(x=Petal.Length)) + 
    geom_density()
  
  #saving plots
  ggsave(filename = str_c(fname, ".png"), device = "png", plot = p)
}

#running function on each dataframe in my list
imap(iris_split, somefunction)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.