nested dataframe, ggplot and patchwork

Has anyone used any of the packages that deal with multiple ggplots together with the purr - nested dataframe workflow? Here I post a reprex of a #ggplot for each species in the iris dataset. And the desired output hardcoded with the patchwork package. The goal is to add a %>% that filters the species that I want the plots from and use them in a multiple plot

#> Warning: package 'tibble' was built under R version 3.5.2
library (patchwork)
iris %>% 
  rowid_to_column(var = "specimen") %>% 
#  gather(contains("."), key = "Measurement", value = "cm") %>% 
  group_by(Species) %>% 
  nest %>% 
  mutate(plot = map2(Species, data,  function (.x,.y){
    ggplot(data = .y, aes(x =  Sepal.Length, y = Sepal.Width)) +
      geom_smooth() +
      ggtitle(label = .x)
  })) -> iris.with.plots

iris.with.plots$plot[[1]] + iris.with.plots$plot[[2]]
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
#> `geom_smooth()` using method = 'loess' and formula 'y ~ x'

Created on 2019-01-22 by the reprex package (v0.2.1)

Below is a function that uses reduce to apply %+% (the ggplot2 addition operator) to whatever plots are in a nested data frame. I haven't done this before and I'd be surprised if there weren't a more natural or elegant approach.

my_patchwork = function(data, plot_col="plot") {
  reduce(data[[plot_col]], `%+%`)

iris.with.plots %>% 
  filter(Species %in% c("setosa", "versicolor")) %>% 

You could also do this directly without defining a function:

iris.with.plots %>% 
  filter(Species %in% c("setosa", "versicolor")) %>% 
  .[["plot"]] %>% reduce(`%+%`)


iris.with.plots %>% 
  filter(Species %in% c("setosa", "versicolor")) %>% 
  pluck("plot") %>% reduce(`%+%`)  # pull(plot) %>% reduce(`%+%`) also works

This topic was automatically closed 21 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.