Home > database >  Print out plots for each group in list column
Print out plots for each group in list column

Time:09-28

A list column with some plots:

mydiamonds <- diamonds %>% 
  group_by(cut, color) %>% 
  nest %>% 
  mutate(plots = map(data, ~ ggplot(.x, aes(x = x, y = price))   geom_point()))

mydiamonds
# A tibble: 35 × 4
# Groups:   cut, color [35]
   cut       color data                 plots 
   <ord>     <ord> <list>               <list>
 1 Ideal     E     <tibble [3,903 × 8]> <gg>  
 2 Premium   E     <tibble [2,337 × 8]> <gg>  
 3 Good      E     <tibble [933 × 8]>   <gg>  
 4 Premium   I     <tibble [1,428 × 8]> <gg>  
 5 Good      J     <tibble [307 × 8]>   <gg>  
 6 Very Good J     <tibble [678 × 8]>   <gg>  
 7 Very Good I     <tibble [1,204 × 8]> <gg>  
 8 Very Good H     <tibble [1,824 × 8]> <gg>  
 9 Fair      E     <tibble [224 × 8]>   <gg>  
10 Ideal     J     <tibble [896 × 8]>   <gg>  
# … with 25 more rows

I would like to print out each plot using facet_wrap() so they all appear together in a single chart. But I cannot even print them out one by one yet. Tried:

mydiamonds %>% map(plots, ~print(.x))
Error in as_mapper(.f, ...) : object 'plots' not found

I hope it's clear what I'm trying to do from that snippet - just print out each plot (This is within a Rmd code chunk so will print out nicely)

Bonus - assuming I figure out how to just print them out, is it possible to get them onto a single chart using facet_wrap() where the title would be paste0(cut, "|", color)?

CodePudding user response:

The plots column is not visible outside the data

library(ggplot2)
library(dplyr)
library(purrr)
mydiamonds %>%
   ungroup %>%
   # either pull the column
   # or use `.$plots`
   pull(plots) %>%
   map(print)

Or use walk

mydiamonds %>%
   ungroup %>%
   pull(plots) %>%
   walk(print)

We could use ggarrange to get all the plot into a single page, but it would be too small

library(ggpubr)
mydiamonds %>%
    ungroup %>%
    pull(plots) %>%
    ggarrange(plotlist = ., nrow = 5, ncol = 7)

Or it may be better to export to pdf

mydiamonds %>%
    ungroup %>%
    pull(plots) %>%
    ggarrange(plotlist = ., nrow = 1, ncol = 1) %>%
    ggexport(., filename="plots.pdf")

check the output pdf

enter image description here

  • Related