plot_gam: Plot GAM Model

View source: R/plot_gam.R

plot_gamR Documentation

Plot GAM Model

Description

Plots fitted GAM values for focal predictor, keeping any other predictors in the model at a specified quantile (default: median)

Usage

plot_gam(
  model,
  predictor,
  quantile.others = 50,
  col = "blue4",
  bg = adjustcolor("dodgerblue", 0.2),
  plot2 = "auto",
  col2 = NULL,
  bg2 = "gray90",
  ...
)

Arguments

model

A GAM model object fitted using mgcv::gam().

predictor

Character string specifying the name of the predictor variable to plot on the x-axis.

quantile.others

Number between 1 and 99 for quantile at which all other predictors are held constant. Default is 50 (median).

col

Color for the prediction line. Default is "blue4".

bg

Background color for the confidence band. Default is adjustcolor('dodgerblue', .2).

plot2

How to plot the distribution in the lower plot. Options: 'auto' (default, auto-select based on number of unique values), 'freq' (always plot frequencies), 'density' (always plot the density) or 'none' (neither). When 'auto', plots frequencies with predictor has less than 30 unique values, density otherwise.

col2

Color for the lines/bars in the bottom distribution plot. Default is "dodgerblue"

bg2

Background color for the bottom distribution plot. Default is "gray90".

...

Additional arguments passed to plot() and lines().

Value

Invisibly returns a list containing:

  • predictor_values: The sequence of predictor values used

  • predicted: The predicted values

  • se: The standard errors

  • lower: Lower confidence bound (predicted - 2*se)

  • upper: Upper confidence bound (predicted + 2*se)

Examples


library(mgcv)
# Fit a GAM model
data(mtcars)
mtcars$cyl <- factor(mtcars$cyl)  # Convert to factor before fitting GAM
model <- gam(mpg ~ s(hp) + s(wt) + cyl, data = mtcars)

# Plot effect of hp (with other variables at median)
plot_gam(model, "hp")

# Plot effect of hp (with other variables at 25th percentile)
plot_gam(model, "hp", quantile.others = 25)

# Customize plot
plot_gam(model, "hp", main = "Effect of Horsepower", col = "blue", lwd = 2)



statuser documentation built on April 25, 2026, 5:06 p.m.