Adding title, axis labels and facet wrap to brms marginal_effects

It looks like conditional_effects() returns a list containing several plots (four plots in the example below). These can be laid out together using wrap_plots from the patchwork package:

library(brms)
library(tidyverse)
library(grid)
library(patchwork)

fit <- brm(count ~ zAge + zBase * Trt + (1 | patient),
           data = epilepsy, family = poisson()) 

# Get the plots generated by conditional_effects()
#  p1 is a list containing four elements. Each element is a plot.
p1 = plot(conditional_effects(fit), plot=FALSE)

# Lay out all four plots and add a title
wrap_plots(p1) + 
  plot_annotation(title="My Title", 
                  theme=theme(plot.title=element_text(hjust=0.5)))

Rplot08

wrap_plots(p1) is equivalent to “adding” the individual plots like this: p1[[1]] + p1[[2]] + p1[[3]] + p1[[4]]. However, wrap_plots is easier if you already have your plots in a list, as we do here.

Note that all of the plots have the same y-axis title. It would be nice to have a single title instead. Unfortunately, patchwork’s plot_annotation function doesn’t seem to have a way to add a general y-axis title. Here’s a more complicated approach where we create a separate object for the y-axis title and combine it with the four plots:

# Create a graphical object (grob) for the y-axis title
ytitle = textGrob("Count", rot=90)

# Remove y-axis title from individual plots
p2 = map(p1, ~.x + labs(y=NULL)) 

# Combine the four plots (inner wrap_plots) and then 
#  add the y-axis title (outer wrap_plots)
wrap_plots(list(ytitle, wrap_plots(p2))) + 
  plot_layout(ncol=2, widths=c(1,100)) +
  plot_annotation(title="My Title", 
                  theme=theme(plot.title=element_text(hjust=0.5)))

Rplot09

4 Likes