Search code examples
rggplot2logistic-regressionfacet-grid

Combine ggplot's facet_grid with bmrs conditional_effects


I have a (toy) dataset where each subject did 10 repetitions of a task, where they had to guess the distance between two points shown. In this dataset I have the ratings given by external judges (not the participants themselves) on the performance of each of those subjects.

library(tidyverse)
library(brms)
data <- data.frame(subject = rep(rep(c(1:10),5), 10),
               judge   = sort(rep(c(1:5), 100)),
               distance = runif(500),
               response = round(runif(500,1,6)))

I want to plot how each judge rated the performance of each subject on each of those repetitions, as a function of distance. I can do that nicely with ggplot's facet_grid

ggplot(data,aes(x=distance, y=jitter(response))) +
geom_point(alpha=0.5) +
geom_smooth(method=lm) +
facet_grid(judge~subject)

enter image description here Now, the judges' responses are ordinal, and I don't want to model them as continuous. So I run a brms ordinal model on a single subject

fit.oneSubj <- brm(data = data %>% filter(subject == 1) %>% filter(judge == 1),
                   response ~ distance,
                   family = cumulative("probit"),
                   chains = 1,
                   save_all_pars = TRUE)

And I plot it

conditional_effects(fit.oneSubj, spaghetti = TRUE, nsamples = 100) %>% #, categorical = TRUE gives you ordinal probability curves
  plot(points = T, point_args = c(alpha = 1/3), line_args = c(size = 0),
       theme = theme(panel.grid = element_blank()))

enter image description here the plot from conditional_effects is also a ggplot, so it should be possible to combine the two. But how? I tried generating one of these latter plots per subject and merging them together with patchwork, but that does not give me the elegant wrapping of facet_grid with a single x and y label for all plots at once.


Solution

  • I ended up doing this by creating all plots separately in a loop, making sure the xlim and ylim are all the same, saving them into a list, then plotting them with ggarrange and annotate_figure (both from ggpubr). It doesn't look as pretty without the facet labels, but it's good enough!