Home > Back-end >  Saving (and opening up) a list of png plots
Saving (and opening up) a list of png plots

Time:10-29

I am trying to save a list of plots with a .png extentions. I can save them individually as a loop.

a <- data.frame(x=sample(10))
b <- data.frame(x=sample(10))
c <- data.frame(x=sample(10))

data<-list()
data[[1]] <- a
data[[2]] <- b
data[[3]] <- c


for(i in 1:3)
{
  temp_plot <- ggplot(data[[i]])   
    theme_bw()  
    geom_histogram(aes(x=x))
  
  ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm") 
}

I have 2 questions:

  1. Can I save them as a list instead?
  2. How do I open them up as a list?

Thank you.

CodePudding user response:

You can save them in a list, yes — for example, using lapply:

plots = lapply(data, \(x) ggplot(x)   theme_bw()   geom_histogram(aes(x = x)))

(pre R 4.1.0, you need to replace \(x) with function (x).)

By “open” I assume you mean how to plot them? Well, using plot:

plot(plots[[2L]])

… or implicitly:

plots[[2L]]
  • Related