将列表列中的多个图按组组合到一页上以获取多页 PDF

Combine multiple plots from a list-column onto a page by group for multi-page PDF

由于 运行 同一数据上的两个不同模型,我创建了两个数据框。每个数据框都包含一个列表列,每行一个图。我最终想将所有图打印成 PDF,但将这些图与多页 PDF 的单页上的相同分组变量配对。例如,在下面的简化示例中,我希望 model_figs1cyl == "6" 的绘图位于 model_figs2' where cyl == "6" 绘图左侧的同一页上`.

下面是一些示例数据:

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")

如何将具有相同分组变量值的图配对到单个 PDF 页面上,同时将所有图同时打印到多页 PDF 中?

如果每组只有两个地块,那么我们可以在 arrange 按组列

后使用 ggsavemarrangeGrob
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))