Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Last active August 16, 2024 04:55
Show Gist options
  • Save andrewheiss/9093632da250e8bc04ae757a98a1b517 to your computer and use it in GitHub Desktop.
Save andrewheiss/9093632da250e8bc04ae757a98a1b517 to your computer and use it in GitHub Desktop.
library(tidyverse)
library(lme4)
library(marginaleffects)

model <- lmer(weight ~ Time + I(Time^2) + Diet*Time + (1 | Chick), data = ChickWeight)

# This is a shortcut for plotting predictions automatically
plot_predictions(model, condition = "Time")

# ↑ that's really just a wrapper for creating a data frame of predictions and
# then plotting it with normal ggplot() code
#
# You can do it yourself with `predictions()`, which then lets you use it in other plots
model_predictions <- predictions(model, newdata = datagrid(Time = seq(0, 21, by = 1)))

ggplot(model_predictions, aes(x = Time, y = estimate)) +
  geom_ribbon(aes(ymin = conf.low, ymax = conf.high), alpha = 0.15) +
  geom_line()

# Those two plots are the same.


# In your case, you have a second plot of individual lines, like this:
ggplot(ChickWeight, aes(x = Time, y = weight)) +
  geom_line(aes(group = Chick), linewidth = 0.1)

# To show the predictions on that plot, include geom_ribbon() and geom_line() with data = model_predictions
ggplot(ChickWeight, aes(x = Time, y = weight)) +
  geom_line(aes(group = Chick), linewidth = 0.05) +
  geom_ribbon(data = model_predictions, aes(y = estimate, ymin = conf.low, ymax = conf.high), alpha = 0.45) +
  geom_line(data = model_predictions, aes(y = estimate))

Created on 2024-08-16 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment