Skip to contents

Plot models and effects

Visualise fitted models with draw() and customise individual plots with assemble(); see Customizing plots.

draw()
Generic plotting via ggplot2
draw(<gam>) draw(<scam>) draw(<scasm>)
Plot smooth and parametric terms from a fitted GAM
draw(<gamlss>)
Plot smooths of a GAMLSS model estimated by GJRM::gamlss
qq_plot(<glmmTMB>) worm_plot(<glmmTMB>) appraise(<glmmTMB>) parametric_terms(<glmmTMB>) parametric_effects(<glmmTMB>) smooths(<glmmTMB>) get_smooths_by_id(<glmmTMB>) smooth_estimates(<glmmTMB>) smooth_coefs(<glmmTMB>) draw(<glmmTMB>)
Effects and diagnostics for glmmTMB models
smooths(<sdmTMB>) get_smooths_by_id(<sdmTMB>) smooth_coefs(<sdmTMB>) smooth_estimates(<sdmTMB>) parametric_terms(<sdmTMB>) parametric_effects(<sdmTMB>) assemble(<sdmTMB>) draw(<sdmTMB>)
Formula effects for sdmTMB models
assemble()
Prepare plots via ggplot2 and assembles them as a list
assemble(<gam>) assemble(<scam>)
Plot smooth and parametric terms from a fitted GAM
scale_fill_partial_effect()
Default diverging red-blue colour palette for partial effects
gratia_theme_get() gratia_theme_set() gratia_theme_update()
Native themes for gratia plots
gratia_palette()
Discrete palettes for gratia plots

Estimate smooths and parametric effects

Estimate individual model terms, add confidence intervals and partial residuals, and transform effects for interpretation.

smooth_estimates()
Evaluate smooths at covariate values
draw(<smooth_estimates>)
Plot the result of a call to smooth_estimates()
parametric_effects()
Estimated values for parametric model terms
draw(<parametric_effects>)
Plot estimated effects for model parametric terms
ale()
Accumulated local effects of a model covariate
draw(<ale>)
Plot accumulated local effects
add_confint()
Add a confidence interval to an existing object
confint(<gam>) confint(<gamm>) confint(<gamm4>) confint(<scam>)
Point-wise and simultaneous confidence intervals for smooths
simultaneous_bands
Simultaneous bands on an evaluation grid or a continuous interval
shape_intervals()
Enforce named shapes on estimates and interval endpoints
shape_confidence_set() in_shape_set()
Intersect a band with linear restrictions on coefficients
add_constant()
Add a constant to estimated values
transform_fun()
Transform estimated values and confidence intervals by applying a function
partial_residuals()
Partial residuals
add_partial_residuals()
Add partial residuals

Predict responses

Predict from the whole model at observed or chosen covariate values, combining model terms rather than estimating individual term effects.

fitted_values()
Generate fitted values from a estimated GAM
fitted_moments()
Estimate moments of the conditional response distribution
conditional_values()
Conditional predictions from a GAM
conditional_moments()
Conditional moments of a GAM response distribution
draw(<conditional_moments>)
Draw conditional response moments
draw(<conditional_values>)
Plot conditional predictions
add_fitted()
Add fitted values from a model to a data frame
add_fitted(<gam>)
Add fitted values from a GAM to a data frame

Compare smooths and predictions

Use difference_smooths() for differences between factor-by smooths, conditional_differences() for contrasts of whole-model predictions, and compare_smooths() to compare smooth estimates across models.

difference_smooths()
Differences of factor smooth interactions
draw(<difference_smooth>)
Plot differences of smooths
conditional_differences()
Conditional differences of fitted values from a GAM
draw(<conditional_differences>)
Plot conditional differences
compare_smooths()
Compare smooths across models
draw(<compare_smooths>)
Plot comparisons of smooths

Estimate derivatives and identify change

Estimate rates of change in smooths or response predictions and identify regions of change; use derivative_samples() for posterior draws of derivatives.

derivatives()
Derivatives of estimated smooths via finite differences
partial_derivatives()
Partial derivatives of estimated multivariate smooths via finite differences
draw(<derivatives>) draw(<partial_derivatives>)
Plot derivatives of smooths
response_derivatives()
Derivatives on the response scale from an estimated GAM
add_sizer()
Add indicators of significant change after SiZeR

Check model fit

Assess model adequacy with appraise(), individual diagnostic plots, residuals, and measures of concurvity.

diagnostic_support
Model diagnostic support and conventions
family_diagnostics
Extend diagnostics for an mgcv-compatible family
appraise()
Model diagnostic plots
qq_plot()
Quantile-quantile plot of model residuals
worm_plot()
Worm plot of model residuals
rootogram()
Rootograms to assess goodness of model fit
draw(<rootogram>)
Draw a rootogram
observed_fitted_plot()
Plot of fitted against observed response values
posterior_predictive_plot()
Posterior predictive check of the response distribution
pp_check.gam() pp_check.bam() pp_check.gamm() pp_check.gamm4() pp_check.scam()
Posterior checks with bayesplot
log_lik()
Posterior draws of pointwise log likelihoods
loo.gam() loo.bam() waic.gam() waic.bam() loo.scam() waic.scam()
Leave-one-out validation and WAIC for GAMs
scalable_qq_plot() scalable_worm_plot() scalable_residuals_linpred_plot() scalable_observed_fitted_plot() scalable_residuals_hist_plot()
Scalable model diagnostic plots
residuals_hist_plot()
Histogram of model residuals
residuals_linpred_plot()
Plot of residuals versus linear predictor values
residuals_covariate_plot() scalable_residuals_covariate_plot()
Plot residuals against covariates
quantile_residuals()
PIT and randomised quantile residuals
surrogate_residuals()
Surrogate residuals for categorical GAMs
dharma_residuals()
Simulation-based PIT residuals
residual_correlation() residual_correlation_plot()
Ordered residual correlation diagnostics
add_residuals()
Add residuals from a model to a data frame
add_residuals(<gam>)
Add residuals from a GAM to a data frame
model_concurvity() concrvity()
Concurvity of an estimated GAM
draw(<pairwise_concurvity>) draw(<overall_concurvity>)
Plot concurvity measures

Prepare data for prediction and evaluation

Choose covariate values at which to evaluate a model and restrict evaluation to regions supported by the data; see Data slices.

data_slice()
Prepare a data slice through model covariates
data_combos()
All combinations of factor levels plus typical values of continuous variables
factor_combos()
All combinations of factor levels
smooth_data()
Generate regular data over the covariates of a smooth
evenly() all_levels() seq_min_max()
Create a sequence of evenly-spaced values
typical_values()
Typical values of model covariates
ref_level() level()
Return the reference or specific level of a factor
too_far()
Exclude values that lie too far from the support of data
too_far_to_na()
Set rows of data to NA if the lie too far from a reference set of values

Sample from fitted models

Draw individual smooths with smooth_samples() or expected responses with fitted_samples(); posterior_samples() generates new responses including coefficient uncertainty, while predicted_samples() simulates responses conditional on the fitted coefficients. Examine chains with as_mcmc_draws() and sampling_diagnostics(). For coefficient draws, use post_draws() in the advanced helpers. See Posterior Simulation and the sampling migration guide.

posterior_samples()
Draw samples from the posterior distribution of an estimated model
smooth_samples()
Posterior draws for individual smooths
draw(<smooth_samples>)
Plot posterior smooths
fitted_samples()
Draw fitted values from the posterior distribution
predicted_samples()
Draw new response values from the conditional distribution of the response
derivative_samples()
Posterior expectations of derivatives from an estimated model
as_mcmc_draws()
Convert posterior samples for MCMC diagnostics
sampling_diagnostics() print(<sampling_diagnostics>)
Extract coefficient-sampler diagnostics
draw(<sampling_diagnostics>)
Plot coefficient-chain diagnostics
simulate(<gamm4>) simulate(<gamlss>) simulate(<gam>) simulate(<gamm>) simulate(<scam>)
Simulate responses from a fitted model
add_fitted_samples() add_predicted_samples() add_posterior_samples() add_smooth_samples()
Add posterior draws from a model to a data object

Inspect models and smooths

Discover a fitted model’s structure and extract its parameters, terms, smooth properties, families, and links.

Model summaries and parameters

Summarise model complexity and extract coefficients and other parameters.

overview()
Provides an overview of a model and the terms in that model
gamm4_support
Support for models fitted by gamm4
edf() model_edf()
Effective degrees of freedom for smooths and GAMs
variance_comp()
Variance components of smooths from smoothness estimates
fixed_effects()
Extract fixed effects estimates from a fitted model
coef(<scam>)
Extract coefficients from a fitted scam model.
get_vcov()
Extract the covariance matrix of the model parameters or a subset of these for a particular model term
model_constant() experimental
Extract the model constant term
dispersion() experimental
Dispersion parameter for fitted model
theta()
General extractor for additional parameters in mgcv models
nb_theta()
Negative binomial parameter theta
null_deviance()
Extract the null deviance of a fitted model

Terms and variables

Identify the terms and covariates used in a fitted model.

smooths()
Names of smooths in a GAM
n_smooths()
How many smooths in a fitted model
which_smooths()
Identify a smooth term by its label
parametric_terms()
Names of any parametric terms in a GAM
model_terms()
Find the names of model terms
model_vars()
List the variables involved in a model fitted with a formula
term_names()
Extract names of all variables needed to fit a GAM or a smooth
term_variables()
Names of variables involved in a specified model term

Smooth objects and properties

Extract smooth objects and inspect their structure and coefficients.

get_smooth()
Extract an mgcv smooth by name
get_by_smooth()
Extract an factor-by smooth by name
get_smooths_by_id()
Extract an mgcv smooth given its position in the model object
basis_size()
Extract basis dimension of a smooth
smooth_dim()
Dimension of a smooth
smooth_label()
Extract the label for a smooth used by 'mgcv'
smooth_type()
Determine the type of smooth and return it in a human readable form
smooth_terms() experimental
List the variables involved in smooths
smooth_coefs()
Coefficients for a particular smooth
smooth_coef_indices()
Indices of the parametric terms for a particular smooth
is_by_smooth() is_factor_by_smooth() is_continuous_by_smooth() by_variable() by_level()
Tests for by variable smooths

Inspect response distributions, link functions, and linear predictors.

family(<gam>) family(<gamm>) family(<bam>) family(<gamm4>)
Extract family objects from models
family_name()
Name of family used to fit model
family_type()
Extracts the type of family in a consistent way
link() inv_link() extract_link()
Extract link and inverse link functions from models
has_theta()
Are additional parameters available for a GAM?
n_eta() experimental
The Number of linear predictors in model

Explore spline bases and penalties

Inspect and visualise the basis functions and penalties that define smooths.

basis()
Basis expansions for smooths
draw(<basis>)
Plot basis functions
tidy_basis()
A tidy basis representation of a smooth object
draw(<mgcv_smooth>)
Plot basis functions
penalty()
Extract and tidy penalty matrices
draw(<penalty_df>)
Display penalty matrices of smooths using ggplot
boundary() experimental
Extract the boundary of a soap film smooth

Example data and simulation

Generate example data or use bundled data sets to learn and demonstrate GAM workflows.

data_sim()
Simulate example data for fitting GAMs
data_sim_families
Generating responses with mgcv family objects
data_sim_shapes
Reference functions for shape-constrained GAMs
gw_f0() gw_f1() gw_f2() gw_f3()
Gu and Wahba test functions
rtw()
Simulator for tweedie LSS models
bird_move
Simulated bird migration data
gss_vocab
Data from the General Social Survey (GSS) from the National Opinion Research Center of the University of Chicago
ref_sims
Reference simulation data
smallAges
Lead-210 age-depth measurements for Small Water
zooplankton
Madison lakes zooplankton data

Advanced programming helpers

Build custom computations using lower-level evaluation, sampling, and validation tools.

Model evaluation and posterior sampling

lp_matrix() model.matrix(<scam>)
Return the linear prediction matrix of a fitted GAM
eval_smooth()
S3 methods to evaluate individual smooths
spline_values()
Evaluate a spline at provided covariate values
post_draws() generate_draws()
Low-level Functions to generate draws from the posterior distribution of model coefficients
gaussian_draws()
Posterior samples using a Gaussian approximation
mh_draws()
Posterior samples using Metropolis Hastings
user_draws()
Handle user-supplied posterior draws

Validation and data utilities

check_user_select_smooths()
Select smooths based on user's choices
is_factor_term()
Is a model term a factor (categorical)?
is_mgcv_family()
Is an object one of mgcv's family objects?
is_mgcv_smooth() stop_if_not_mgcv_smooth() check_is_mgcv_smooth() is_mrf_smooth()
Check if objects are smooths or are a particular type of smooth
is_multivariate_y()
Is a model multivariate?
is_offset()
Is a model term an offset?
fix_offset()
Fix the names of a data frame containing an offset variable.
seq_min_max_eps()
Create a sequence of evenly-spaced values adjusted to accommodate a small adjustment
shift_values()
Shift numeric values in a data frame by an amount eps
rep_first_factor_value()
Repeat the first level of a factor n times
to_na()
Sets the elements of vector to NA
vars_from_label()
Returns names of variables from a smooth label
load_mgcv()
Load mgcv quietly

Deprecated and legacy interfaces

Reference for older code; use smooth_estimates(), parametric_effects(), and derivatives() for new analyses.

evaluate_smooth() deprecated
Evaluate a smooth
evaluate_parametric_term() deprecated
Evaluate parametric model terms
draw(<evaluated_parametric_term>) deprecated
Plot estimated parametric effects
confint(<fderiv>)
Point-wise and simultaneous confidence intervals for derivatives of smooths