Generalised Additive Mixed Model with brms: How to get the factor smooth spaghettis of participants across trials?

With traditional gam() model using the mgcv package, one can easily get the so-called participants’ spaghetti to represent the factor smooths. For example, this would be the basic model:

gam1 <-gam(DV ~
    ExpTrialOrder +
    FactorA +
    s(CovariateM) +
    s(ExpTrialOrder, Participant, bs='fs', m=1),

plot.gam(gam1, select=2)

This would be the typical plot, representing participants as separate lines smoothed over experimental trials:

How can one make the same plot using brms to run the same model?

brms_gam1 <-brm(DV ~
    ExpTrialOrder +
    FactorA +
    s(CovariateM) +
    s(ExpTrialOrder, Participant, bs='fs', m=1),
  • Operating System: macOS
  • brms Version: 2.17.0


Meanwhile… I have figured all out… So, in case anyone needs the solution, here it goes:

First, notice that the model above has two smooth terms (s()), the second of which is the so-called factor smooth (or factorial smooth: s(ExpTrialOrder, Participant, bs='fs', m=1), where 'fs' stands for factor smooth, and m is a penalty term).

For the spaghetti graph of Participants over Experimental Trials, we need to extract the appropriate conditional_smooths():

  1. get the conditional_smooths() from the model
  2. the function will return a list with two respective tables of Estimates, SEs, lower and upper CIs etc.; the tables are, given the example above, for: s(CovariateM), and s(ExpTrialOrder, Participant, bs='fs', m=1); we need the second element from the list and particular columns
  3. assign some nice names to columns
newdsmooth2 <- conditional_smooths(brms_gam1, ask=FALSE, plot=FALSE)
newdsmooth2 =[[2]][c(1,2,6,8,9)])
colnames(newdsmooth2) = c('ExpTrialOrder', 'Participant', 'Estimate', 'lo95CI', 'hi95CI')

The rest is just plotting. Since you will end up needing a lot of colours (per Participant), let’s take care of that too the best we can:

require(RColorBrewer) # for palette

colourCount = length(unique(newdsmooth2$Participant))
p3 <- ggplot(newdsmooth2, aes(x=ExpTrialOrder, y=Estimate, group=Participant)) +
    geom_smooth(method='gam', formula=y~s(x,bs='cs'), aes(colour=Participant)) +
    scale_colour_manual(values=colorRampPalette(brewer.pal(12, 'Paired'))(colourCount)) +
    scale_x_continuous('Per Participant smooths over Trials\n[s(ExpTrialOrder, Participant, bs=\'fs\', m=1)]') +
    scale_y_continuous('DV') +

This is the result:

Enjoy & Good Luck!