Visualization

Visualization helpers for Aurora-GLM models.

This module provides a centralized interface to all plotting functions for GLM, GAM, and GAMM models.

GAM Smooth Effects

  • plot_smooth: Plot individual smooth term with confidence bands

  • plot_all_smooths: Grid of all smooth terms

GAMM Random Effects

  • plot_caterpillar: Random effects with CIs (caterpillar plot)

  • plot_random_effects_qq: Q-Q plot for normality check

  • plot_random_effects_density: Density plots of random effects

  • plot_random_effects_summary: Summary panel of random effects

Model Diagnostics

  • plot_diagnostics: Residual diagnostics panel (like R’s plot.lm)

  • plot_diagnostics_panel: 2x2 diagnostic panel

  • plot_smooth_effect: Single smooth term with confidence bands

  • plot_all_smooth_effects: Grid of all smooth terms

aurora.visualization.plot_smooth(result, term=None, confidence_level=0.95, n_points=100, partial_residuals=True, ax=None, figsize=(8, 6), title=None, xlabel=None, ylabel=None)[source]

Plot a smooth term with confidence bands.

Parameters:
  • result (GAMResult or AdditiveGAMResult) – Fitted GAM result object.

  • term (int, str, or None) – For AdditiveGAMResult: term name like “s(0)” or variable index. For GAMResult: should be None (univariate GAM).

  • confidence_level (float, default=0.95) – Confidence level for bands (e.g., 0.95 for 95% CI).

  • n_points (int, default=100) – Number of evaluation points for smooth curve.

  • partial_residuals (bool, default=True) – Whether to show partial residuals.

  • ax (matplotlib Axes, optional) – Axes to plot on. If None, creates new figure.

  • figsize (tuple, default=(8, 6)) – Figure size if creating new figure.

  • title (str, optional) – Plot title. Auto-generated if None.

  • xlabel (str, optional) – X-axis label. Auto-generated if None.

  • ylabel (str, optional) – Y-axis label. Auto-generated if None.

Returns:

fig – The figure containing the plot.

Return type:

matplotlib Figure

Raises:

Examples

>>> import numpy as np
>>> from aurora.models.gam import fit_gam, plot_smooth
>>> x = np.linspace(0, 10, 100)
>>> y = np.sin(x) + 0.1 * np.random.randn(100)
>>> result = fit_gam(x, y, n_basis=15)
>>> fig = plot_smooth(result)
>>> # For additive GAM
>>> from aurora.models.gam import fit_additive_gam, SmoothTerm
>>> X = np.random.randn(200, 2)
>>> y = np.sin(X[:, 0]) + np.cos(X[:, 1]) + 0.1 * np.random.randn(200)
>>> result = fit_additive_gam(
...     X, y,
...     smooth_terms=[SmoothTerm(variable=0), SmoothTerm(variable=1)]
... )
>>> fig = plot_smooth(result, term="s(0)")

Notes

Confidence bands use the Bayesian posterior covariance of the penalized smooth, Vp (Wood 2017, §6.10):

Var(f(x)) = σ̂² · B(x) (X’X + λS)⁻¹ B(x)’

where B(x) is the basis matrix and σ̂² = RSS / (n - edf) is the scale estimate corrected for the effective degrees of freedom. This is the Bayesian covariance (the frequentist Ve would insert an extra X’WX factor between the inverses); Bayesian bands for penalized splines have good across-the-function frequentist coverage (Marra & Wood 2012).

Partial residuals for term j are:

r_j = y - f_{-j}(x)

where f_{-j} excludes term j.

aurora.visualization.plot_all_smooths(result, ncols=2, confidence_level=0.95, figsize_per_plot=(6, 4), partial_residuals=True)[source]

Plot all smooth terms in a grid layout.

Parameters:
  • result (AdditiveGAMResult) – Fitted additive GAM result.

  • ncols (int, default=2) – Number of columns in grid.

  • confidence_level (float, default=0.95) – Confidence level for bands.

  • figsize_per_plot (tuple, default=(6, 4)) – Size of each subplot.

  • partial_residuals (bool, default=True) – Whether to show partial residuals.

Returns:

fig – Figure with all smooth terms plotted.

Return type:

matplotlib Figure

Examples

>>> from aurora.models.gam import fit_additive_gam, SmoothTerm
>>> import numpy as np
>>> X = np.random.randn(200, 3)
>>> y = np.sin(X[:, 0]) + np.cos(X[:, 1]) + X[:, 2]**2 + 0.1 * np.random.randn(200)
>>> result = fit_additive_gam(
...     X, y,
...     smooth_terms=[
...         SmoothTerm(variable=0),
...         SmoothTerm(variable=1),
...         SmoothTerm(variable=2)
...     ]
... )
>>> fig = plot_all_smooths(result, ncols=3)
aurora.visualization.plot_caterpillar(result, grouping=None, effect_index=0, confidence=0.95, sort=True, figsize=None, ax=None)[source]

Create caterpillar plot for random effects.

Caterpillar plots show the estimated random effects (BLUPs) for each group with confidence intervals, sorted by magnitude. They are useful for identifying groups with unusually large or small effects.

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • grouping (str or int, optional) – Which grouping variable to plot. If None, uses the first random effect term. Required if model has multiple grouping variables.

  • effect_index (int, default=0) – Which random effect to plot (0=intercept, 1=first slope, etc.).

  • confidence (float, default=0.95) – Confidence level for intervals (e.g., 0.95 for 95% CI).

  • sort (bool, default=True) – Whether to sort groups by effect magnitude.

  • figsize (tuple, optional) – Figure size (width, height) in inches.

  • ax (Axes, optional) – Matplotlib axes to plot on. If None, creates new figure.

Returns:

  • fig (Figure) – Matplotlib figure.

  • ax (Axes) – Matplotlib axes with plot.

Return type:

tuple[Figure, Axes]

Examples

>>> import numpy as np
>>> from aurora.models.gamm import fit_gamm
>>> from aurora.models.gamm.plotting import plot_caterpillar
>>>
>>> # Fit model
>>> data = pd.DataFrame({
...     'y': np.random.randn(100),
...     'x': np.random.randn(100),
...     'subject': np.repeat(np.arange(10), 10)
... })
>>> result = fit_gamm(formula="y ~ x + (1 | subject)", data=data)
>>>
>>> # Plot random intercepts
>>> fig, ax = plot_caterpillar(result)
>>> plt.show()

Notes

The confidence intervals are approximate and computed using the posterior variance of the random effects:

Var(b | y) ≈ (Z’WZ + Ψ⁻¹)⁻¹

Groups whose confidence intervals do not include zero have effects that are significantly different from the population mean.

aurora.visualization.plot_random_effects_qq(result, grouping=None, effect_index=0, figsize=(6, 6), ax=None)[source]

Create Q-Q plot for random effects normality check.

Q-Q (quantile-quantile) plots compare the distribution of random effects to a theoretical normal distribution. Points falling along the diagonal line indicate normality.

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • grouping (str or int, optional) – Which grouping variable to plot. If None, uses the first random effect term.

  • effect_index (int, default=0) – Which random effect to plot (0=intercept, 1=first slope, etc.).

  • figsize (tuple, default=(6, 6)) – Figure size (width, height) in inches.

  • ax (Axes, optional) – Matplotlib axes to plot on. If None, creates new figure.

Returns:

  • fig (Figure) – Matplotlib figure.

  • ax (Axes) – Matplotlib axes with plot.

Return type:

tuple[Figure, Axes]

Examples

>>> fig, ax = plot_random_effects_qq(result)
>>> plt.show()

Notes

The random effects are assumed to follow a normal distribution:

b ~ N(0, Ψ)

Departures from normality (heavy tails, skewness) can be identified visually from Q-Q plots. Consider: - S-shaped pattern: Heavy tails (outliers) - Systematic curve: Skewness - Points far from line: Individual outliers

aurora.visualization.plot_random_effects_density(result, grouping=None, effect_index=0, show_normal=True, figsize=(8, 5), ax=None)[source]

Plot density of random effects with optional normal overlay.

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • grouping (str or int, optional) – Which grouping variable to plot.

  • effect_index (int, default=0) – Which random effect to plot.

  • show_normal (bool, default=True) – Whether to overlay theoretical normal distribution.

  • figsize (tuple, default=(8, 5)) – Figure size.

  • ax (Axes, optional) – Matplotlib axes to plot on.

Returns:

  • fig (Figure) – Matplotlib figure.

  • ax (Axes) – Matplotlib axes with plot.

Return type:

tuple[Figure, Axes]

Examples

>>> fig, ax = plot_random_effects_density(result)
>>> plt.show()

Notes

The histogram shows the empirical distribution of random effects, while the overlaid curve shows the theoretical normal distribution N(0, Ψ) implied by the model.

aurora.visualization.plot_random_effects_summary(result, grouping=None, effect_index=0, figsize=(14, 10))[source]

Create comprehensive summary of random effects diagnostics.

Produces a 2x2 grid with: 1. Caterpillar plot 2. Q-Q plot 3. Density plot 4. Residuals vs fitted

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • grouping (str or int, optional) – Which grouping variable to plot.

  • effect_index (int, default=0) – Which random effect to plot.

  • figsize (tuple, default=(14, 10)) – Figure size.

Returns:

fig – Matplotlib figure with 2x2 subplot grid.

Return type:

Figure

Examples

>>> fig = plot_random_effects_summary(result)
>>> plt.show()

Notes

This is a convenience function that creates a comprehensive diagnostic summary in a single figure.

aurora.visualization.plot_diagnostics(result, plot_type='residuals', figsize=(8, 6), ax=None)[source]

Create diagnostic plots for GAMM models.

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • plot_type ({'residuals', 'fitted', 'qq', 'scale-location'}) – Type of diagnostic plot: - ‘residuals’: Residuals vs fitted values - ‘fitted’: Fitted vs observed values - ‘qq’: Q-Q plot of residuals - ‘scale-location’: Scale-location plot (sqrt(|residuals|) vs fitted)

  • figsize (tuple, default=(8, 6)) – Figure size.

  • ax (Axes, optional) – Matplotlib axes to plot on.

Returns:

  • fig (Figure) – Matplotlib figure.

  • ax (Axes) – Matplotlib axes with plot.

Return type:

tuple[Figure, Axes]

Examples

>>> # Residuals vs fitted
>>> fig, ax = plot_diagnostics(result, plot_type='residuals')
>>> plt.show()
>>>
>>> # Q-Q plot of residuals
>>> fig, ax = plot_diagnostics(result, plot_type='qq')
>>> plt.show()

Notes

Residuals vs Fitted: - Should show no pattern (randomness around zero) - Fan shape indicates heteroscedasticity - Curvature indicates nonlinearity

Q-Q Plot: - Points should fall on diagonal line - Departures indicate non-normality of residuals

Scale-Location: - Check homoscedasticity (constant variance) - Should show horizontal line with random scatter

Fitted vs Observed: - Points should fall near y=x line - Shows overall model fit quality

aurora.visualization.plot_diagnostics_panel(result, figsize=(12, 10))[source]

Create 2x2 diagnostic panel for GAMM model.

Standard diagnostic panel inspired by R’s plot.lm(): 1. Residuals vs Fitted (top-left) 2. Q-Q Plot of residuals (top-right) 3. Scale-Location plot (bottom-left) 4. Residuals vs Leverage with Cook’s distance (bottom-right)

Parameters:
  • result (GAMMResult) – Fitted GAMM model result.

  • figsize (tuple, default=(12, 10)) – Figure size (width, height) in inches.

Returns:

fig – Matplotlib figure with 2x2 diagnostic panel.

Return type:

Figure

Examples

>>> from aurora.models.gamm import fit_gamm
>>> result = fit_gamm("y ~ x + (1|group)", data=df)
>>> fig = plot_diagnostics_panel(result)
>>> plt.show()

Notes

This produces a publication-quality diagnostic panel following the classic R layout:

Residuals vs Fitted (top-left): - Should show random scatter around zero - Patterns indicate model misspecification

Normal Q-Q (top-right): - Points should fall on diagonal - Departures indicate non-normal residuals

Scale-Location (bottom-left): - Should show horizontal trend - Increasing spread indicates heteroscedasticity

Residuals vs Leverage (bottom-right): - Identifies influential observations - Cook’s distance contours show influence

References

aurora.visualization.plot_smooth_effect(result, term_name, data=None, n_points=100, level=0.95, show_data=True, show_residuals=False, figsize=(8, 6), ax=None)[source]

Plot estimated smooth function with confidence band.

Creates a plot of the estimated smooth term f(x) with: - Smooth curve (estimated effect) - Pointwise confidence interval - Rug plot showing data density - Optional partial residuals

Parameters:
  • result (GAMMResult) – Fitted GAMM/GAM model result.

  • term_name (str) – Name of the smooth term to plot (e.g., ‘s(age)’ or ‘age’).

  • data (dict or DataFrame, optional) – Original data used for fitting. If None, attempts to extract from result.

  • n_points (int, default=100) – Number of points for smooth curve evaluation.

  • level (float, default=0.95) – Confidence level for intervals.

  • show_data (bool, default=True) – Whether to show rug plot of data density.

  • show_residuals (bool, default=False) – Whether to show partial residuals.

  • figsize (tuple, default=(8, 6)) – Figure size (width, height) in inches.

  • ax (Axes, optional) – Matplotlib axes to plot on. If None, creates new figure.

Returns:

  • fig (Figure) – Matplotlib figure.

  • ax (Axes) – Matplotlib axes with plot.

Return type:

tuple[Figure, Axes]

Examples

>>> from aurora.models.gamm import fit_gamm
>>> result = fit_gamm("y ~ s(age) + (1|group)", data=df)
>>> fig, ax = plot_smooth_effect(result, term_name='age', data=df)
>>> plt.show()

Notes

The confidence band is a pointwise interval, not a simultaneous band. For simultaneous confidence bands, additional adjustments are needed.

Partial residuals are computed as:

e_i = f̂(x_i) + (y_i - ŷ_i)

This allows visualizing the data on the scale of the smooth effect.

References

aurora.visualization.plot_all_smooth_effects(result, data=None, n_cols=2, figsize_per_plot=(5, 4), **kwargs)[source]

Plot all smooth effects in a grid layout.

Parameters:
  • result (GAMMResult) – Fitted GAMM/GAM model result.

  • data (dict or DataFrame, optional) – Original data used for fitting.

  • n_cols (int, default=2) – Number of columns in the grid.

  • figsize_per_plot (tuple, default=(5, 4)) – Size of each subplot.

  • **kwargs (dict) – Additional arguments passed to plot_smooth_effect.

Returns:

fig – Matplotlib figure with grid of smooth effect plots.

Return type:

Figure

Examples

>>> result = fit_gamm("y ~ s(x1) + s(x2) + s(x3) + (1|group)", data=df)
>>> fig = plot_all_smooth_effects(result, data=df)
>>> plt.show()
aurora.visualization.plot_gamm_diagnostics(result, figsize=(12, 10))

Create a 2x2 panel of diagnostic plots for a fitted GAMM model.

The four panels are:

  1. Residuals vs Fitted – checks for non-linearity and heteroscedasticity. A blue spline smoother is overlaid to reveal systematic patterns.

  2. Normal Q-Q Plot – assesses normality of residuals.

  3. Scale-Location – plots sqrt(|residuals|) against fitted values to detect heteroscedasticity. A red smoother is overlaid.

  4. Histogram of Residuals – visualises the residual distribution with a theoretical normal density curve overlaid.

Parameters:
  • result (GAMMResult) – Fitted GAMM result. Must expose fitted_values and residuals attributes.

  • figsize (tuple of float, default=(12, 10)) – Figure size as (width, height) in inches.

Returns:

  • fig (matplotlib.figure.Figure) – The created figure object.

  • axes (numpy.ndarray of matplotlib.axes.Axes) – Array of shape (2, 2) containing the individual Axes.

Raises:

ImportError – If matplotlib or scipy is not installed.

See also

plot_random_effects

Caterpillar and correlation plots for random effects.

Examples

>>> from aurora.models.gamm import fit_gamm
>>> result = fit_gamm(formula='y ~ x + (1|subject)', data=df)
>>> fig, axes = plot_diagnostics(result)
>>> plt.show()
aurora.visualization.plot_gamm_random_effects(result, group_name=None, figsize=(15, 5))

Visualize random effects distribution with caterpillar and correlation plots.

For random-intercept-only models, produces a single sorted caterpillar plot. For random intercept + slope models, produces a 1x3 panel:

  1. Caterpillar plot (intercepts) – random intercepts sorted by value.

  2. Caterpillar plot (slopes) – random slopes sorted by value.

  3. Intercept-slope scatter – scatter plot of intercepts vs slopes with the estimated correlation annotated.

Parameters:
  • result (GAMMResult) – Fitted GAMM result. Must expose random_effects and variance_components attributes.

  • group_name (str, optional) – Name of the grouping variable to plot. If None, the first grouping variable in result.random_effects is used.

  • figsize (tuple of float, default=(15, 5)) – Figure size as (width, height) in inches (only used when there are two random effect components).

Returns:

  • fig (matplotlib.figure.Figure) – The created figure object.

  • axes (matplotlib.axes.Axes or numpy.ndarray of matplotlib.axes.Axes) – A single Axes (1 component) or an array of 3 Axes (2 components).

Raises:

See also

interpret_variance_components

Textual summary of variance components.

plot_diagnostics

Residual diagnostic plots.

Examples

>>> from aurora.models.gamm import fit_gamm
>>> result = fit_gamm(formula='y ~ x + (1 + x | subject)', data=df)
>>> fig, axes = plot_random_effects(result, 'subject')
>>> plt.show()

Model Plots

Model diagnostic and smooth term plots for Aurora-GLM.

This submodule provides visualization functions for inspecting fitted GLM, GAM, and GAMM model results. Plotting is dispatched from the top-level aurora.visualization package.

GAM Smooth Term Visualization

plot_smooth

Plot an individual smooth term with confidence bands.

plot_all_smooths

Grid of all smooth terms in a GAM/GAMM.

GAMM Random Effects Visualization

plot_caterpillar

Random effects with confidence intervals (caterpillar plot).

plot_random_effects_qq

Q-Q plot for normality check of random effects.

plot_random_effects_density

Density plots of random effects.

plot_random_effects_summary

Summary panel of random effects.

Model Diagnostics

plot_diagnostics_panel

2x2 diagnostic panel (residuals vs fitted, Q-Q, scale-location, residuals vs leverage), similar to R’s plot.lm.

plot_smooth_effect

Single smooth term with confidence bands.

plot_all_smooth_effects

Grid of all smooth terms.

GAMM-Specific Panels

plot_gamm_diagnostics

GAMM diagnostics panel.

plot_gamm_random_effects

GAMM random effects plots.

Residual Plots

Residual diagnostic plots for Aurora-GLM models.

This submodule provides visualization tools for inspecting model residuals, including residuals-vs-fitted plots, Q-Q plots, scale-location plots, and residual histograms. These plots help assess model assumptions such as homoscedasticity, normality, and independence of errors.

See also

aurora.visualization

Top-level visualization interface.

Prediction Plots

Prediction visualization utilities for Aurora-GLM models.

This submodule provides functions for visualizing model predictions, including predicted-vs-observed plots, prediction interval plots, and partial dependence displays. These tools aid in interpreting model fit and communicating predictive performance.

See also

aurora.visualization

Top-level visualization interface.