mlm_plot: Publication-ready interaction plot for multilevel models

View source: R/mlm_plot.R

mlm_plotR Documentation

Publication-ready interaction plot for multilevel models

Description

Creates a ggplot2-based interaction plot showing predicted values of the outcome across levels of pred, with separate lines for each selected value of modx. Confidence bands and raw data overlay are optional.

Usage

mlm_plot(
  model,
  pred,
  modx,
  modx.values = c("mean-sd", "quartiles", "tertiles", "custom"),
  at = NULL,
  interval = TRUE,
  conf.level = 0.95,
  points = FALSE,
  point_alpha = 0.3,
  colors = NULL,
  line_size = 1,
  x_label = NULL,
  y_label = NULL,
  legend_title = NULL
)

Arguments

model

An lmerMod object with a two-way interaction between pred and modx in the fixed-effects.

pred

Character scalar. Focal predictor (x-axis).

modx

Character scalar. Moderator (separate lines).

modx.values

Strategy for moderator values. Same options as mlm_probe(): "mean-sd", "quartiles", "tertiles", "custom".

at

Numeric vector of custom moderator values (used when modx.values = "custom").

interval

Logical. Draw confidence bands? Default TRUE.

conf.level

Confidence level for bands. Default 0.95.

points

Logical. Overlay raw data points? Default FALSE.

point_alpha

Transparency for raw data points. Default 0.3.

colors

Character vector of colours for moderator lines. If NULL, uses a accessible default palette.

line_size

Line width for predicted lines. Default 1.

x_label

Label for x-axis. Defaults to pred.

y_label

Label for y-axis. Defaults to response variable name.

legend_title

Label for the legend. Defaults to modx.

Value

A ggplot object.

Examples

set.seed(1)
dat <- data.frame(
  y   = rnorm(200),
  x   = rnorm(200),
  m   = rep(rnorm(20), each = 10),
  grp = factor(rep(1:20, each = 10))
)
dat$y <- dat$y + dat$x * dat$m
mod <- lme4::lmer(y ~ x * m + (1 | grp), data = dat,
                  control = lme4::lmerControl(optimizer = "bobyqa"))
mlm_plot(mod, pred = "x", modx = "m")
mlm_plot(mod, pred = "x", modx = "m", modx.values = "quartiles")


mlmoderator documentation built on April 4, 2026, 1:07 a.m.