moplot_onepred: Plot contrasts for one categorical predictor

View source: R/moplot_onepred.R

moplot_onepredR Documentation

Plot contrasts for one categorical predictor

Description

moplot_onepred() creates a graphical representation of the contrasts associated with one categorical predictor in a fitted model.

The upper panel displays the quantities compared by each contrast, together with their confidence intervals. The optional lower panel displays the corresponding model parameter, its confidence interval, and an approximate Cohen's d.

The horizontal position of each parameter in the lower panel is inherited from the midpoint of the corresponding contrast in the upper panel.

Usage

moplot_onepred(
  model,
  predictor,
  data = NULL,
  sig_level = 0.05,
  conf_level = 0.95,
  estimate_type = c("auto", "observed", "predicted"),
  prediction_scale = c("response", "link"),
  coefficient_scale = c("model", "interpreted"),
  per_difference = FALSE,
  bounds = NULL,
  hypotheses = NULL,
  show_coef = TRUE,
  show_data = FALSE,
  style = c("minimal", "publication"),
  caption = TRUE,
  digits = 2L,
  base_size = 13,
  panel_heights = c(2, 1)
)

Arguments

model

A fitted model supported by the package.

predictor

A single character string identifying the categorical predictor to display.

data

Optional data frame containing the variables used to fit model. If NULL, the data supplied in the model call are recovered; the model frame is used only when they are unavailable. The original variables are needed for model-based estimates when the model contains transformed terms such as log(x). Rows of a supplied data frame that were excluded from the fit, through subset or missing values, are dropped, matching rows by name.

sig_level

A numeric value between 0 and 1 defining the significance threshold used for the contrast labels. The default is 0.05.

conf_level

A numeric value between 0 and 1 specifying the confidence level. The default is 0.95.

estimate_type

Character string specifying how the quantities in the upper panel should be computed. Available options are:

"auto"

Uses observed means when the fixed part of the model contains only the focal predictor, the model has no random effects and no unequal prior weights, and, for generalized models, prediction_scale = "response". Model-based predictions are used otherwise: with other predictors or interactions, with random effects (observed means would ignore the clustering of the observations), with weights (observed means are unweighted), and for estimates on the link scale.

"observed"

Uses observed means computed directly from the model data.

"predicted"

Uses model-based fixed-effect predictions.

prediction_scale

Character string specifying the scale used for model-based predictions. Available options are "response" and "link". The default is "response".

coefficient_scale

Character string specifying the estimate displayed in the lower panel. Available options are:

"model"

Displays the model coefficient on its original model scale.

"interpreted"

Displays the interpreted estimate returned by extract_param(), such as an odds ratio or incidence rate ratio when appropriate.

per_difference

Logical. Should the lower-panel coefficients be divided by their scale factor? The default is FALSE.

For some codings, such as Helmert and reverse Helmert contrasts or custom matrices, each model coefficient equals a scale factor s multiplied by the difference displayed in the upper panel (for example s = 1/3 for the second Helmert contrast). When per_difference = TRUE, the lower panel reports beta / s and its confidence interval, so that both panels refer to the same difference; with coefficient_scale = "interpreted", ratios are computed as exp(beta / s), the ratio for the displayed comparison. Test statistics, p-values, and Cohen's d are unaffected. For generalized models, beta / s is a difference on the link scale. Codings with s = 1 for every contrast (treatment, sum, sliding differences) are unaffected, and the argument is ignored with a warning for polynomial contrasts.

bounds

Optional numeric vector c(lower, upper) giving the natural range of a response analyzed with a Gaussian (identity link) model, such as c(1, 7) for a Likert score or c(0, Inf) for a reaction time, so that confidence intervals remain within it. Ignored, with a warning, for generalized models. See contrasts_onepred().

hypotheses

Optional numeric matrix declaring the comparisons that the coefficients of predictor are intended to estimate, with one row per coefficient and one column per factor level. Each declared hypothesis is checked against the comparison that the coefficient estimates; the result is reported in a message and in the caption. The figure always shows the comparisons that the coefficients estimate. See contrasts_onepred().

show_coef

Logical. Should the lower coefficient panel be displayed? The default is TRUE.

show_data

Logical. Should raw observations be displayed in the upper panel using horizontal jittering? The default is FALSE.

style

Character string specifying the graphical style. Available options are:

"minimal"

Uses a restrained grayscale palette.

"publication"

Uses a colorblind-safe palette and stronger visual emphasis.

caption

Controls whether a descriptive caption is printed in the console. It can be:

  • TRUE, to generate and print an automatic caption;

  • FALSE or NULL, to suppress the caption;

  • a single character string to print a custom caption.

The caption is not added to the graphical object. Each sentence is printed on a separate console line so that the text can be copied and used independently of the plot.

digits

Number of decimal places used in the lower-panel labels. The default is 2.

base_size

Base font size used in both panels. The default is 13.

panel_heights

A numeric vector of length two specifying the relative heights of the upper and lower panels. The default is c(2, 1). This argument is used only when show_coef = TRUE.

Details

The function displays one focal categorical predictor at a time, but the fitted model may contain additional predictors.

Models in which the focal predictor is involved in an interaction are not currently supported.

Treatment and Sum contrasts are displayed as independent pairs to improve readability. Other supported contrast types reuse repeated displayed quantities where appropriate.

Polynomial contrasts, generated by stats::contr.poly() with equally spaced or user-supplied scores, use a dedicated layout, because each component involves every level rather than a comparison between two quantities. The upper panel contains one facet per component (linear, quadratic, and so forth): each shows the level estimates with their confidence intervals and the curve implied by that component alone, drawn around the mean of the estimates on the linear-predictor scale and transformed to the scale of the estimates. Crosses mark the value of the curve at each level, which is Polynomial_fit in the output of contrasts_onepred(). Levels are spaced according to the scores of the coding. The lower panel shows each coefficient beneath the facet of its component. per_difference is ignored, with a warning, because polynomial coefficients have no scale factor.

No model-intercept line is displayed.

Value

When show_coef = FALSE, a ggplot object containing the upper panel.

When show_coef = TRUE, a patchwork object containing the aligned upper and lower panels.

In both cases the object carries recommended export dimensions, used by moplot_export() when width or height is not supplied.

Examples

set.seed(123)

dat <- data.frame(
  group = factor(
    rep(c("A", "B", "C"), each = 40),
    levels = c("A", "B", "C")
  ),
  y = c(
    rnorm(40, 0.0, 0.9),
    rnorm(40, 0.4, 0.9),
    rnorm(40, 0.9, 0.9)
  )
)

contrasts(dat$group) <- contr.helmert(3)

mod <- lm(
  y ~ group,
  data = dat
)

moplot_onepred(
  model = mod,
  predictor = "group"
)

moplot_onepred(
  model = mod,
  predictor = "group",
  show_data = TRUE,
  style = "publication"
)

moplot_onepred(
  model = mod,
  predictor = "group",
  show_coef = FALSE
)


MoPlot documentation built on Nov. 25, 2026, 5:10 p.m.