Store all ggplot2 plots from environment in a list

Viewed 153

I need to change all the labels (titles/subtitles) from a script that creates close to 100 hundred plots -- all different. Instead of changing the script code I'd like to loop through all plots and add a new labs function. This way nothing is altered from the original. To do this I need to get all ggplot2 objects into list.

My question is: How can one store all ggplot2 objects in the environment into a list?

The code below should create eleven ggplot2 plots and store them in the environment (want to do the reverse .. get them into a list from the environment).

library(tidyverse)

# Make a lot of ggplots using mtcars

all_plots <- list()

all_plots <- map(names(mtcars), 
    possibly(function(x){
  mtcars %>% 
    ggplot(aes(mpg, x))+
    geom_point()
}, NULL)) %>% 
  set_names(names(mtcars))

# function to add all ggplots to the environemnt
list_environment <- function(x) {
  if(is.list(x)) { 
    list2env(x, envir = .GlobalEnv)
    lapply(x, test)
  }
}

list_environment(all_plots)

ls()
2 Answers

First collect the names of all your ggplot objects in the environment. You can loop through ls() and check if each object has 'ggplot' in its class (this works for your example):

my_ggplot_names=ls()[which(sapply(ls(),function(x) class(get(x))[2]=="ggplot"))]

Then it's easy to use mget to collect all the objects with those names into a list:

my_listed_ggplots=mget(my_ggplot_names)

Probably the plots in the list have no names.

library(ggplot2)
all_plots <- replicate(10, 
                       ggplot(mtcars[sample(1:nrow(mtcars), 10),], aes(y=mpg, x=hp)) +
                         geom_point(),
                       simplify=F)

This list has no names,

names(all_plots)
# NULL

and list2env won't work.

list2env(all_plots, envir=.GlobalEnv)
# Error in list2env(all_plots, envir = .GlobalEnv) : 
#   names(x) must be a character vector of the same length as x

Works when we name the list objects using setNames.

all_plots <- setNames(all_plots, sprintf("p%s", seq(all_plots)))
list2env(all_plots, envir=.GlobalEnv)
ls()
# [1] "all_plots" "p1"        "p10"       "p2"        "p3"       
# [6] "p4"        "p5"        "p6"        "p7"        "p8"       
# [11] "p9" 
Related