Home > Mobile >  exporting and saving a list of ggplots objects with names based on a column
exporting and saving a list of ggplots objects with names based on a column

Time:06-18

been an R user for around a year now - so still have tons to learn. Anyways my question is:

  • How do I export the ggplots within the list and name them specifically based on their location.

Below is the dummy data I have created with where I am at.

location <- c('obs1', 'obs2', 'obs3', 'obs4', 'obs5', 'obs6')
percentage <- c(40, 30, 20, 40, 20, 30)
mean_percentage <- c(30, 30, 30, 30, 30, 30)

dat1 <- data.frame(location, percentage, mean_percentage)

plot.func <- function(dat) {
  
  dat %>% 
    pivot_longer(cols = 2:3, names_to = 'place', values_to = 'percent') %>%
    ggplot(aes(x = place, y = percent, fill = place))  
    geom_bar(stat = 'identity')
  
}

myplots <- list()

myplots <- lapply(1:nrow(dat1), function(i) plot.func(dat1[i,]))

The above code produces the list called 'myplots' which contains 6 ggplots.

I would like to export these individually with names based on the location variable.

For example: obs1.barchart.pdf, obs2.barchart.pdf, obs3.barchart.pdf and so on.

I've tried various different ways but going round in circles. Any help much appreciated.

Best, TheBoomerang

CodePudding user response:

One option would be to name your lists of plots and use purrr::imap or purrr::iwalk to loop over the list of plots to save them.

For convenience I use split to first split you data by location which will create a named list of dataframe on which I apply your function using lapply before passing it to iwalk to save the plots using ggsave:

library(ggplot2)
library(dplyr)
library(tidyr)

split(dat1, dat1$location) |> 
  lapply(plot.func) |> 
  purrr::iwalk(~ ggsave(paste(.y, "barchart", "pdf", sep = "."), plot = .x))
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
#> Saving 7 x 5 in image
  • Related