Create ggplot2 visualizations of smooth or spline effects from GAM and GLM models. Supports Linear, Logistic, Poisson, and Cox models with interaction terms. Handles GAM smooth terms (s(), te(), ti()), GLM splines (ns(), bs()), and Cox pspline().
Usage
splineplot(
fit,
data,
xvar = NULL,
by_var = NULL,
refx = NULL,
term_index = 1,
bins = 12,
xlim = NULL,
ylim = NULL,
show_hist = NULL,
log_scale = FALSE,
ci_level = 0.95,
show_ref_point = TRUE,
colors = NULL,
ribbon_ci = FALSE,
xlab = NULL,
ylab = NULL,
ylab_right = "Percent of Population"
)
Arguments
- fit
A fitted model object (gam, glm, lm, coxph)
- data
The data frame used to fit the model
- xvar
Character string specifying the variable name for x-axis (default: first spline term)
- by_var
Character string specifying the interaction variable (default: auto-detect from model)
- refx
Reference value for the x variable (default: median)
- term_index
For GAM with multiple smooth terms, which term to plot (default: 1)
- bins
Number of bins for histogram (default: 12)
- xlim
X-axis limits (default: range of x variable)
- ylim
Y-axis limits (default: auto-determined, e.g., c(0.25, 2.0) for HR/OR/RR)
- show_hist
Logical, whether to show histogram (default: TRUE)
- log_scale
Logical, whether to use log scale for OR/RR/HR (default: FALSE)
- ci_level
Confidence interval level (default: 0.95)
- show_ref_point
Logical, whether to show reference point marker (default: TRUE)
- colors
Named vector of colors for by_var levels
- ribbon_ci
Logical, whether to use ribbon style for CI (default: FALSE, uses dotted lines)
- xlab
Custom x-axis label (default: xvar name)
- ylab
Custom y-axis label (default: auto-determined based on model type)
- ylab_right
Custom right y-axis label for histogram (default: "Percent of Population")
Examples
# Create sample data
set.seed(123)
n <- 200
x <- rnorm(n, mean = 50, sd = 10)
lp <- -0.05*(x - 50) + 0.001*(x - 50)^2
y <- rbinom(n, 1, plogis(lp))
dat <- data.frame(x = x, y = y)
# GLM with natural splines
library(splines)
fit_glm <- glm(y ~ ns(x, df = 4), family = binomial(), data = dat)
p <- splineplot(fit_glm, dat)
#> Using 'x' as x variable
#> Using refx = 49.41 (median of x)
# \donttest{
# GAM example (requires mgcv)
if (requireNamespace("mgcv", quietly = TRUE)) {
fit_gam <- mgcv::gam(y ~ s(x), family = binomial(), data = dat)
p2 <- splineplot(fit_gam, dat)
}
#> Using 'x' as x variable
#> Using refx = 49.41 (median of x)
# Cox model example (requires survival)
if (requireNamespace("survival", quietly = TRUE)) {
time <- rexp(n, rate = exp(lp/2))
status <- rbinom(n, 1, 0.8)
dat$time <- time
dat$status <- status
fit_cox <- survival::coxph(survival::Surv(time, status) ~ ns(x, df = 4),
data = dat)
p3 <- splineplot(fit_cox, dat)
}
#> Using 'x' as x variable
#> Using refx = 49.41 (median of x)
# }