Save a list of plots from environment in R

Advertisements

I want to save all my plots from my R environment with ggsave(). How can I save list of plots from environment in R and then use the list as input to ggsave() ?

I got some plots with cars from here to illustrate:

PlotA <- ggplot(mtcars, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
  geom_point(size=3)

PlotB <- ggplot(mtcars, aes(x=hp, y=mpg, color=cyl, shape=cyl)) +
  geom_point(size=3) +
  geom_smooth(method="lm", aes(fill=cyl)) 

PlotC <- ggplot(mtcars, aes(x=hp, y=mpg)) +
  geom_point(size=3, aes(color=cyl, shape=cyl)) +
  geom_smooth(method="loess", color="black", se=FALSE) +
  geom_smooth(method="lm", aes(color=cyl, fill=cyl)) 
  • My attempt:
saveplots <- list()
saveplots <- ls(pattern = 'Plot')

### Save pngs ###

for(i in 1:length(saveplots)){
  ggsave(saveplots[[i]],
         file=paste0("Total", saveplots,".png"),
         width = 22, height = 11.5, units = "cm",
         path = "plots/")
}

  • Some posts helped a bit, but not quite yet (ex1 ex2). Any ideas? Thanks in adv.

>Solution :

You can use the function get to get the object from the environment.

for(i in 1:length(saveplots)){
  ggsave(plot = get(saveplots[[i]]),
         filename=paste0("Total", saveplots[[i]],".png"),
         width = 22, height = 11.5, units = "cm",
         path = "plots/")
}

Leave a Reply Cancel reply