Home > Software design >  Combine multiple plots from a list-column onto a page by group for multi-page PDF
Combine multiple plots from a list-column onto a page by group for multi-page PDF

Time:02-17

I've created two dataframes as a result of running two different models on the same data. Each dataframe contains a list-column with one plot per row. I would eventually like to print all plots to a PDF, but pair the plots with the same grouping variable on a single page of a multi-page PDF. For example, in the simplified example below, I would like the plot from model_figs1 where cyl == "6" to be on the same page to the left of the plot from model_figs2' where cyl == "6"`.

Here is some example data:

library(tidyverse)    
    
# I am sure you could combine model_figs1 & model_figs2 into one process/code chunk,
# but this is an overly simplified example and should be kept separate:

model_figs1 <-
  mtcars %>% 
  group_by(cyl) %>% 
  nest() %>% 
  mutate(plot = map(data, ~ggplot(data = .x, 
                                   aes(x = hp, y = mpg))  
                       geom_point()  
                       geom_smooth(method = "lm")  
                       labs(subtitle = cyl)))

model_figs2 <-
  mtcars %>% 
  group_by(cyl) %>% 
  nest() %>% 
  mutate(plot = map(data, ~ggplot(data = .x, 
                                   aes(x = hp, y = mpg))  
                       geom_point()  
                       geom_smooth(method = "loess")  
                       labs(subtitle = cyl)))

# Bind the dfs together
model_figs <-
  bind_rows(model_figs1, model_figs2, .id = "id")

How do I pair plots with the same grouping variable value onto a single PDF page while printing all plots to a multi-page PDF at once?

CodePudding user response:

If there are only two plots per group, then we can use ggsave with marrangeGrob after arrangeing by the group column

library(gridExtra)
library(dplyr)
model_figs <- model_figs %>%
              arrange(cyl)
ggsave(filename = file.path(getwd(), "Downloads/newplots.pdf"), 
    plot = marrangeGrob(model_figs$plot, ncol = 2, nrow = 1))
  • Related