extracting individual plot details from combined plot in `cowplot` for unit tests

I am trying to write unit tests for functions where I use cowplot::plot_grid() to combine ggplot2 plots. For example,


# setup
set.seed(123)
library(ggplot2)

# creating basic plots
p1 <- ggplot(aes(x = as.factor(am), y = wt), data = mtcars) + 
  geom_point() + 
  labs(title = "Dataset: mtcars", subtitle = "Source: `base` package")
p2 <- ggplot(aes(x = vore, y = brainwt), data = msleep) + 
  geom_point() + 
  labs(title = "Dataset: msleep", subtitle = "Source: `ggplot2` package")

# combined plot
(p <- cowplot::plot_grid(p1, p2, labels = c("(i)", "(ii)")))
#> Warning: Removed 27 rows containing missing values (geom_point).

For ggplot2 plots, I can build the plot and extract these details.


# extracting title and subtitle (example with p1)
pb1 <- ggplot2::ggplot_build(p1)
pb1$plot$labels$title
#> [1] "Dataset: mtcars"
pb1$plot$labels$subtitle
#> [1] "Source: `base` package"

But how can I extract such details about the individual plots from the combined plot-

# building combined plot
pb <- ggplot2::ggplot_build(p)

So, for example, how can I extract subtitle for p1 from pb?

Created on 2018-12-22 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.