Purrr - Import to the Environment list of plots

Hi,
I've read in the forum about creating a function in order to "map" plots.
For example, I wrote a basic code for plotting many graphs using a list of variables:

library(gapminder)
data_plots<-gapminder %>% 
  group_by(continent,year) %>% 
  summarise(vidas=mean(lifeExp)) 

variables<-list("year", "vidas")


gloop_simple<-map(
  .x = variables,
  .f = ~ggplot(data = data_plots) +
    geom_col(aes(continent, y = .data[[.x]])) 
)

gloop_simple[[1]]
gloop_simple[[2]]

Here I'm plotting the list of variables containing year and vidas, using always as axis x "continent".
The issue is I don't know how to send the list gloop_simple, containing the graphs, to the Environment.
I find info about a package named ggarrange, but It seems dead.
I hope you can guide me.

As always, thanks for your time and interest.

There are a couple of options. I think the simplest makes use of the patchwork package.

patchwork::wrap_plots(gloop_simple)                # for side by side
patchwork::wrap_plots(gloop_simple, ncol = 1)      # for one above the other
1 Like

Thanks for your code, mrjoh3.
Patchwork's wrap plots collapses the plots in one element.
But how can I import each element in the environment?
Should I write a loop?

Is this what you mean?

library(gapminder)
library(dplyr)
library(ggplot2)
library(purrr)

data_plots<-gapminder %>% 
    group_by(continent,year) %>% 
    summarise(vidas=mean(lifeExp)) 
#> `summarise()` has grouped output by 'continent'. You can override using the
#> `.groups` argument.

variables <- list("year", "vidas")


gloop_simple <- map(
    .x = variables,
    .f = ~ggplot(data = data_plots) +
        geom_col(aes(continent, y = .data[[.x]]))) %>% 
    set_names(nm = variables)

list2env(gloop_simple, envir = globalenv())
#> <environment: R_GlobalEnv>

vidas

year

Created on 2022-07-27 by the reprex package (v2.0.1)

1 Like

Thanks, andresrcs
Your code performed what I needed It.
Thanks.

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.