# Plotting partial pooling in mixed-effects models

In this post, I demonstrate a few techniques for plotting information from a relatively simple mixed-effects model fit in R. These plots can help us develop intuitions about what these models are doing and what “partial pooling” means.

## The sleepstudy dataset

For these examples, I’m going to use the sleepstudy dataset from the lme4 package. The outcome measure is reaction time, the predictor measure is days of sleep deprivation, and these measurements are nested within participants—we have 10 observations per participant. I am also going to add two fake participants with incomplete data to illustrate partial pooling.

library(lme4)
library(dplyr)
library(tibble)

# Convert to tibble for better printing. Convert factors to strings
sleepstudy <- sleepstudy %>%
as_tibble() %>%
mutate(Subject = as.character(Subject))

df_sleep <- bind_rows(
sleepstudy,
tibble(Reaction = c(286, 288), Days = 0:1, Subject = "374"),
tibble(Reaction = 245, Days = 0, Subject = "373"))

df_sleep
#> # A tibble: 183 × 3
#>    Reaction  Days Subject
#>       <dbl> <dbl> <chr>
#>  1     250.     0 308
#>  2     259.     1 308
#>  3     251.     2 308
#>  4     321.     3 308
#>  5     357.     4 308
#>  6     415.     5 308
#>  7     382.     6 308
#>  8     290.     7 308
#>  9     431.     8 308
#> 10     466.     9 308
#> # … with 173 more rows


We can visualize all the data in ggplot2 by using facet_wrap() to create subplots for each participant and stat_smooth() to create a regression line in each subplot.

library(ggplot2)

xlab <- "Days of sleep deprivation"
ylab <- "Average reaction time (ms)"

ggplot(df_sleep) +
aes(x = Days, y = Reaction) +
stat_smooth(method = "lm", se = FALSE) +
# Put the points on top of lines
geom_point() +
facet_wrap("Subject") +
labs(x = xlab, y = ylab) +
# We also need to help the x-axis, so it doesn't
# create gridlines/ticks on 2.5 days
scale_x_continuous(breaks = 0:4 * 2)
#> geom_smooth() using formula 'y ~ x'


By the way, ggplot2 doesn’t draw the regression lines outside of the range of the data unless we set fullrange = TRUE. That’s a helpful feature for 374!

Update: Douglas Bates did it first. Someone sent me a link to a slide deck by Douglas Bates, lead author of the lme4 package, where he has some plots just like the ones I demo in this post. He uses the sleepstudy dataset too—it’s his R package and his teaching dataset, after all—so the similarities are uncanny but accidental. Origin of this post: I was asked on twitter how to make a facet plot of a mixed effects model, wrote up a quick demo using the convenient sleepstudy dataset, and then fleshed that demo into a tutorial. By using his teaching dataset to illustrate some partial pooling concepts, I ended up recreating some of his work on accident. 😬 [Sept. 14, 2017]

## Complete pooling and no pooling models

Each one of these panels plotted above shows an independently estimated regression line. This approach to fitting a separate line for each participant is sometimes called the no pooling model because none of the information from different participants is combined or pooled together.

We fit a separate line for each cluster of data, unaware that any of the other participants exist. The lmList() function in lme4 automates this process.

df_no_pooling <- lmList(Reaction ~ Days | Subject, df_sleep) %>%
coef() %>%
# Subject IDs are stored as row-names. Make them an explicit column
rownames_to_column("Subject") %>%
rename(Intercept = (Intercept), Slope_Days = Days) %>%
# Remove the participant who only had one data-point
filter(Subject != "373")

#>   Subject Intercept Slope_Days      Model
#> 1     308  244.1927  21.764702 No pooling
#> 2     309  205.0549   2.261785 No pooling
#> 3     310  203.4842   6.114899 No pooling
#> 4     330  289.6851   3.008073 No pooling
#> 5     331  285.7390   5.266019 No pooling
#> 6     332  264.2516   9.566768 No pooling


In contrast, we might consider a complete pooling model where all the information from the participants is combined together. We fit a single line for the combined data set, unaware that the data came from different participants.

# Fit a model on all the data pooled together
m_pooled <- lm(Reaction ~ Days, df_sleep)

# Repeat the intercept and slope terms for each participant
df_pooled <- tibble(
Model = "Complete pooling",
ylim = range(df_pulled$Slope_Days), expand = TRUE )  To go all out 😎, let’s also label the contours with the confidence levels. I see that the lower left area is relatively free of points, so I can place the labels there. I filter down to just the ellipse points in the bottom 25% of x and y values. That will keep points in that lower left quadrant. Then I find the (x, y) point with the farthest distance from the center as the location for my label. I make it sound so easy but it took a lot of trial and error (including an an attempt to use cosines). # Euclidean distance contour_dist <- function(xs, ys, center_x, center_y) { x_diff <- (center_x - xs) ^ 2 y_diff <- (center_y - ys) ^ 2 sqrt(x_diff + y_diff) } # Find the point to label in each ellipse. df_label_locations <- df_ellipse %>% group_by(level) %>% filter( Intercept < quantile(Intercept, .25), Slope_Days < quantile(Slope_Days, .25) ) %>% # Compute distance from center. mutate( dist = contour_dist(Intercept, Slope_Days, fixef(m)[1], fixef(m)[2]) ) %>% # Keep smallest values. top_n(-1, wt = dist) %>% ungroup() # Tweak the last plot one more time! last_plot() + geom_text( aes(label = level, color = NULL, shape = NULL), data = df_label_locations, nudge_x = .5, nudge_y = .8, size = 3.5, color = "grey40" )  Are you feeling satisfied? I feel satisfied. ## Bonus: Plotting lines from a Bayesian mixed effects model This last part is more of a code demo than a walkthrough. I call myself a Bayesian. Visualizing uncertainty is one of my things here, so I would be remiss if I didn’t also demo how to do some plots using posterior samples. Conceptually, the classical model above estimated a single set of partially pooled regression lines. With the Bayesian model, we can sample from a posterior distribution of partially pooled regression lines. Instead of one line for each participant, there’s an entire distribution of them for each participant. This distribution lets us quantify our uncertainty about each part of our model. First, we fit the model in RStanARM with weakly informative priors. library(rstanarm) #> Loading required package: Rcpp #> This is rstanarm version 2.21.1 #> - See https://mc-stan.org/rstanarm/articles/priors for changes to default priors! #> - Default priors may change, so it's safest to specify priors, even if equivalent to the defaults. #> - For execution on a local, multicore CPU with excess RAM we recommend calling #> options(mc.cores = parallel::detectCores())  # Update 2021-02: Prior to mid-2020 priors were autoscaled (so autoscale = # TRUE) was implicity set. But now they are no longer autoscaled. The code has # been updated to use the autoscaling. b <- stan_glmer( Reaction ~ Days + (Days | Subject), family = gaussian(), data = df_sleep, prior = normal(0, 2, autoscale = TRUE), prior_intercept = normal(0, 5, autoscale = TRUE), prior_covariance = decov(regularization = 2), prior_aux = cauchy(0, 1, autoscale = TRUE), # reproducible blogging seed = 20211116 )  We get a similar overview as arm::display() when we print the model. b #> stan_glmer #> family: gaussian [identity] #> formula: Reaction ~ Days + (Days | Subject) #> observations: 183 #> ------ #> Median MAD_SD #> (Intercept) 252.3 6.2 #> Days 10.4 1.7 #> #> Auxiliary parameter(s): #> Median MAD_SD #> sigma 25.7 1.6 #> #> Error terms: #> Groups Name Std.Dev. Corr #> Subject (Intercept) 24 #> Days 7 0.06 #> Residual 26 #> Num. levels: Subject 20 #> #> ------ #> * For help interpreting the printed output see ?print.stanreg #> * For info on the priors used see ?prior_summary.stanreg  We have posterior distribution of values now! That means instead of one “center of gravity” point, we have 4,000 plausible points for our central value. The center of our former contour plot has its own contour plot. That’s Bayes for you. We can plot that easily with stat_density_2d(). We set the coordinate limits to be the same as the last plot, just so that we don’t exaggerate the uncertainty around the central point by drawing a gigantic contour surface. # Get a dataframe: One row per posterior sample df_posterior <- b %>% as.data.frame() %>% as_tibble() ggplot(df_posterior) + aes(x = (Intercept), y = Days) + # Calculate the density stat_density_2d(aes(fill = stat(level)), geom = "polygon") + ggtitle("Where's the average intercept and slope?") + xlab("Estimate for average intercept") + ylab("Estimate for average slope") + # Use the same coordinate limits as last plot coord_cartesian( xlim = range(df_pulled$Intercept),
ylim = range(df_pulled\$Slope_Days),
expand = TRUE
) +
guides(fill = "none")


For each participant, we have 4,000 partially-pooled regression lines too, so we can visualize our uncertainty for each participant’s individual regression line.

Let’s finish by drawing a sample of those lines for a faceted plot. We have to do a bunch of data wrangling to get a dataframe with one row per subject per posterior sample.

# For each sample, add the average intercept and average slope values to each
# participant's deviation from that average. These yields the intercept and
# slope parameters for each participant.
df_effects <- df_posterior %>%
mutate(
# Find all the columns with the pattern "b[(Intercept". Add the column
# (Intercept) to each of those columns.
across(
.cols = matches("b\\[\\(Intercept"),
.fns = ~ . + (Intercept)
),
# Again for slope
across(
.cols = matches("b\\[Day"),
.fns = ~ . + Days
)
)

# Convert to a long format
df_long_effects <- df_effects %>%
select(matches("b\\[")) %>%
rowid_to_column("draw") %>%
tidyr::pivot_longer(
cols = c(-draw),
# when we make new columns with pivot_ functions, the
# they get quotes
names_to = "Parameter",
values_to = "Value"
)

# Extract the effect type and subject number from each parameter name
df_long_effects <- df_long_effects %>%
mutate(
Effect = Parameter %>%
stringr::str_detect("Intercept") %>%
ifelse(., "Intercept", "Slope_Day"),
Subject = Parameter %>%
stringr::str_extract("\\d\\d\\d")
) %>%
select(draw, Subject, Effect, Value)

# Finally!
df_long_effects
#> # A tibble: 160,000 × 4
#>     draw Subject Effect     Value
#>    <int> <chr>   <chr>      <dbl>
#>  1     1 308     Intercept 256.
#>  2     1 308     Slope_Day  19.5
#>  3     1 309     Intercept 208.
#>  4     1 309     Slope_Day   2.49
#>  5     1 310     Intercept 197.
#>  6     1 310     Slope_Day   9.00
#>  7     1 330     Intercept 281.
#>  8     1 330     Slope_Day   5.21
#>  9     1 331     Intercept 307.
#> 10     1 331     Slope_Day   1.16
#> # … with 159,990 more rows


Now that we have the data in the right shape, we are going randomly choose 50 posterior samples and plot those lines alongside the observed data.

# For reproducibility
set.seed(20220330)

df_samples <- df_long_effects %>%
filter(draw %in% sample(1:4000, size = 50)) %>%
tidyr::pivot_wider(names_from = Effect, values_from = Value)
df_samples
#> # A tibble: 1,000 × 4
#>     draw Subject Intercept Slope_Day
#>    <int> <chr>       <dbl>     <dbl>
#>  1    93 308          254.    17.6
#>  2    93 309          217.     2.87
#>  3    93 310          202.     5.61
#>  4    93 330          250.    11.7
#>  5    93 331          262.     8.65
#>  6    93 332          242.    12.0
#>  7    93 333          258.    15.8
#>  8    93 334          232.    12.2
#>  9    93 335          240.     0.869
#> 10    93 337          283.    18.9
#> # … with 990 more rows

ggplot(df_sleep) +
aes(x = Days, y = Reaction) +
geom_abline(
aes(intercept = Intercept, slope = Slope_Day),
data = df_samples,
color = "#3366FF",
alpha = .1
) +
geom_point() +
facet_wrap("Subject") +
scale_x_continuous(breaks = 0:4 * 2) +
labs(x = xlab, y = ylab)


For the participants with complete data, the lines pile up and form a narrow band, indicating a low degree of uncertainty. In the final two panels, however, we only have limited data, and the sample of lines fan out and cover many different plausible trajectories.

The uncertainty is more dramatic if we draw a contour plot for each participant—basically, drawing each participants’ mostly likely locations in the landscape of parameter values.

df_effects_all_wide <- df_long_effects %>%
tidyr::pivot_wider(names_from = Effect, values_from = Value)

ggplot(df_effects_all_wide) +
aes(x = Intercept, y = Slope_Day) +
stat_density_2d(
aes(fill = stat(level)),
geom = "polygon",
# normalized density so all colors appear in each plot
contour_var = "ndensity"
) +
facet_wrap("Subject") +
xlab("Intercept estimate") +
ylab("Slope estimate") +
guides(fill = "none")


For 373 and 374, the contour regions/ink-splats are very tall: A lot of slope values are plausible. The region for 374 is more off center and slightly narrow than that of 373: That extra data point matters.

Funnily enough, this post started as a quick write-up of a demo I wrote, but it kind of spiraled out of control. I hope this write-up helps students and users understand mixed-effects models at a more intuitive level.

I had formally learned about these models twice in graduate school. In psychology, we were told to use them if we wanted to make inferences about a larger population of subjects or stimulus items. In educational psychology, we were told to use them to capture the sources of variances in a nested data-set: Kids nested in classrooms nested in schools, etc. It wasn’t until I taught myself Bayesian stats that I learned about third reason to use them: They pool information across different units, providing regularized model estimates. I find this rationale most intuitive. The Gelman and Hill book and Statistical Rethinking both discuss the partial pooling description of these models. (Ooooh, as I added the Rethinking link, I just noticed that I created a ggplot2 version of the plot from the cover of that book. 😆)

Last knitted on 2022-03-30. Source code on GitHub.1

1. sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.2.0 alpha (2022-03-29 r82022 ucrt)
#>  os       Windows 10 x64 (build 22000)
#>  system   x86_64, mingw32
#>  ui       RTerm
#>  language (EN)
#>  collate  English_United States.utf8
#>  ctype    English_United States.utf8
#>  tz       America/Chicago
#>  date     2022-03-30
#>  pandoc   NA
#>
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ! package      * version  date (UTC) lib source
#>    abind          1.4-5    2016-07-21 [1] CRAN (R 4.2.0)
#>    arm            1.12-2   2021-10-15 [1] CRAN (R 4.2.0)
#>    assertthat     0.2.1    2019-03-21 [1] CRAN (R 4.2.0)
#>    base64enc      0.1-3    2015-07-28 [1] CRAN (R 4.2.0)
#>    bayesplot      1.9.0    2022-03-10 [1] CRAN (R 4.2.0)
#>    boot           1.3-28   2021-05-03 [2] CRAN (R 4.2.0)
#>    cachem         1.0.6    2021-08-19 [1] CRAN (R 4.2.0)
#>    callr          3.7.0    2021-04-20 [1] CRAN (R 4.2.0)
#>    cli            3.2.0    2022-02-14 [1] CRAN (R 4.2.0)
#>    coda           0.19-4   2020-09-30 [1] CRAN (R 4.2.0)
#>    codetools      0.2-18   2020-11-04 [2] CRAN (R 4.2.0)
#>    colorspace     2.0-3    2022-02-21 [1] CRAN (R 4.2.0)
#>    colourpicker   1.1.1    2021-10-04 [1] CRAN (R 4.2.0)
#>    crayon         1.5.1    2022-03-26 [1] CRAN (R 4.2.0)
#>    crosstalk      1.2.0    2021-11-04 [1] CRAN (R 4.2.0)
#>    DBI            1.1.2    2021-12-20 [1] CRAN (R 4.2.0)
#>    digest         0.6.29   2021-12-01 [1] CRAN (R 4.2.0)
#>    downlit        0.4.0    2021-10-29 [1] CRAN (R 4.2.0)
#>    dplyr        * 1.0.8    2022-02-08 [1] CRAN (R 4.2.0)
#>    DT             0.22     2022-03-28 [1] CRAN (R 4.2.0)
#>    dygraphs       1.1.1.6  2018-07-11 [1] CRAN (R 4.2.0)
#>    ellipse      * 0.4.2    2020-05-27 [1] CRAN (R 4.2.0)
#>    ellipsis       0.3.2    2021-04-29 [1] CRAN (R 4.2.0)
#>    evaluate       0.15     2022-02-18 [1] CRAN (R 4.2.0)
#>    fansi          1.0.2    2022-01-14 [1] CRAN (R 4.2.0)
#>    farver         2.1.0    2021-02-28 [1] CRAN (R 4.2.0)
#>    fastmap        1.1.0    2021-01-25 [1] CRAN (R 4.2.0)
#>    generics       0.1.2    2022-01-31 [1] CRAN (R 4.2.0)
#>    ggplot2      * 3.3.5    2021-06-25 [1] CRAN (R 4.2.0)
#>    ggrepel        0.9.1    2021-01-15 [1] CRAN (R 4.2.0)
#>    ggridges       0.5.3    2021-01-08 [1] CRAN (R 4.2.0)
#>    git2r          0.30.1   2022-03-16 [1] CRAN (R 4.2.0)
#>    glue           1.6.2    2022-02-24 [1] CRAN (R 4.2.0)
#>    gridExtra      2.3      2017-09-09 [1] CRAN (R 4.2.0)
#>    gtable         0.3.0    2019-03-25 [1] CRAN (R 4.2.0)
#>    gtools         3.9.2    2021-06-06 [1] CRAN (R 4.2.0)
#>    here           1.0.1    2020-12-13 [1] CRAN (R 4.2.0)
#>    highr          0.9      2021-04-16 [1] CRAN (R 4.2.0)
#>    htmltools      0.5.2    2021-08-25 [1] CRAN (R 4.2.0)
#>    htmlwidgets    1.5.4    2021-09-08 [1] CRAN (R 4.2.0)
#>    httpuv         1.6.5    2022-01-05 [1] CRAN (R 4.2.0)
#>    igraph         1.2.11   2022-01-04 [1] CRAN (R 4.2.0)
#>    inline         0.3.19   2021-05-31 [1] CRAN (R 4.2.0)
#>    isoband        0.2.5    2021-07-13 [1] CRAN (R 4.2.0)
#>    knitr        * 1.38     2022-03-25 [1] CRAN (R 4.2.0)
#>    labeling       0.4.2    2020-10-20 [1] CRAN (R 4.2.0)
#>    later          1.3.0    2021-08-18 [1] CRAN (R 4.2.0)
#>    lattice        0.20-45  2021-09-22 [2] CRAN (R 4.2.0)
#>    lifecycle      1.0.1    2021-09-24 [1] CRAN (R 4.2.0)
#>    lme4         * 1.1-28   2022-02-05 [1] CRAN (R 4.2.0)
#>    loo            2.5.1    2022-03-24 [1] CRAN (R 4.2.0)
#>    magrittr       2.0.2    2022-01-26 [1] CRAN (R 4.2.0)
#>    markdown       1.1      2019-08-07 [1] CRAN (R 4.2.0)
#>    MASS           7.3-56   2022-03-23 [2] CRAN (R 4.2.0)
#>    Matrix       * 1.4-1    2022-03-23 [2] CRAN (R 4.2.0)
#>    matrixStats    0.61.0   2021-09-17 [1] CRAN (R 4.2.0)
#>    memoise        2.0.1    2021-11-26 [1] CRAN (R 4.2.0)
#>    mgcv           1.8-39   2022-02-24 [2] CRAN (R 4.2.0)
#>    mime           0.12     2021-09-28 [1] CRAN (R 4.2.0)
#>    miniUI         0.1.1.1  2018-05-18 [1] CRAN (R 4.2.0)
#>    minqa          1.2.4    2014-10-09 [1] CRAN (R 4.2.0)
#>    munsell        0.5.0    2018-06-12 [1] CRAN (R 4.2.0)
#>    nlme           3.1-157  2022-03-25 [2] CRAN (R 4.2.0)
#>    nloptr         2.0.0    2022-01-26 [1] CRAN (R 4.2.0)
#>    pillar         1.7.0    2022-02-01 [1] CRAN (R 4.2.0)
#>    pkgbuild       1.3.1    2021-12-20 [1] CRAN (R 4.2.0)
#>    pkgconfig      2.0.3    2019-09-22 [1] CRAN (R 4.2.0)
#>    plyr           1.8.7    2022-03-24 [1] CRAN (R 4.2.0)
#>    prettyunits    1.1.1    2020-01-24 [1] CRAN (R 4.2.0)
#>    processx       3.5.2    2021-04-30 [1] CRAN (R 4.2.0)
#>    promises       1.2.0.1  2021-02-11 [1] CRAN (R 4.2.0)
#>    ps             1.6.0    2021-02-28 [1] CRAN (R 4.2.0)
#>    purrr          0.3.4    2020-04-17 [1] CRAN (R 4.2.0)
#>    R6             2.5.1    2021-08-19 [1] CRAN (R 4.2.0)
#>    ragg           1.2.2    2022-02-21 [1] CRAN (R 4.2.0)
#>    RColorBrewer   1.1-2    2014-12-07 [1] CRAN (R 4.2.0)
#>    Rcpp         * 1.0.8.3  2022-03-17 [1] CRAN (R 4.2.0)
#>  D RcppParallel   5.1.5    2022-01-05 [1] CRAN (R 4.2.0)
#>    reshape2       1.4.4    2020-04-09 [1] CRAN (R 4.2.0)
#>    rlang          1.0.2    2022-03-04 [1] CRAN (R 4.2.0)
#>    rprojroot      2.0.2    2020-11-15 [1] CRAN (R 4.2.0)
#>    rstan          2.21.3   2021-12-19 [1] CRAN (R 4.2.0)
#>    rstanarm     * 2.21.1   2020-07-20 [1] CRAN (R 4.2.0)
#>    rstantools     2.1.1    2020-07-06 [1] CRAN (R 4.2.0)
#>    rstudioapi     0.13     2020-11-12 [1] CRAN (R 4.2.0)
#>    scales         1.1.1    2020-05-11 [1] CRAN (R 4.2.0)
#>    sessioninfo    1.2.2    2021-12-06 [1] CRAN (R 4.2.0)
#>    shiny          1.7.1    2021-10-02 [1] CRAN (R 4.2.0)
#>    shinyjs        2.1.0    2021-12-23 [1] CRAN (R 4.2.0)
#>    shinystan      2.6.0    2022-03-03 [1] CRAN (R 4.2.0)
#>    shinythemes    1.2.0    2021-01-25 [1] CRAN (R 4.2.0)
#>    StanHeaders    2.21.0-7 2020-12-17 [1] CRAN (R 4.2.0)
#>    stringi        1.7.6    2021-11-29 [1] CRAN (R 4.2.0)
#>    stringr        1.4.0    2019-02-10 [1] CRAN (R 4.2.0)
#>    survival       3.3-1    2022-03-03 [2] CRAN (R 4.2.0)
#>    systemfonts    1.0.4    2022-02-11 [1] CRAN (R 4.2.0)
#>    textshaping    0.3.6    2021-10-13 [1] CRAN (R 4.2.0)
#>    threejs        0.3.3    2020-01-21 [1] CRAN (R 4.2.0)
#>    tibble       * 3.1.6    2021-11-07 [1] CRAN (R 4.2.0)
#>    tidyr          1.2.0    2022-02-01 [1] CRAN (R 4.2.0)
#>    tidyselect     1.1.2    2022-02-21 [1] CRAN (R 4.2.0)
#>    utf8           1.2.2    2021-07-24 [1] CRAN (R 4.2.0)
#>    vctrs          0.3.8    2021-04-29 [1] CRAN (R 4.2.0)
#>    withr          2.5.0    2022-03-03 [1] CRAN (R 4.2.0)
#>    xfun           0.30     2022-03-02 [1] CRAN (R 4.2.0)
#>    xtable         1.8-4    2019-04-21 [1] CRAN (R 4.2.0)
#>    xts            0.12.1   2020-09-09 [1] CRAN (R 4.2.0)
#>    yaml           2.3.5    2022-02-21 [1] CRAN (R 4.2.0)
#>    zoo            1.8-9    2021-03-09 [1] CRAN (R 4.2.0)
#>
#>  [1] C:/Users/Tristan/AppData/Local/R/win-library/4.2
#>  [2] C:/Program Files/R/R-4.2.0alpha/library
#>
#>  D ── DLL MD5 mismatch, broken installation.
#>
#> ──────────────────────────────────────────────────────────────────────────────


Tags:

Posted: