| plot.mfp2 | R Documentation |
Shows how selected variables contribute to the fitted model, with confidence intervals. Term plots can also include component-plus-residual points to help assess the fitted relationship.
## S3 method for class 'mfp2'
plot(
x,
terms = NULL,
partial_only = FALSE,
type = c("terms", "contrasts"),
ref = NULL,
terms_seq = c("data", "equidistant"),
alpha = 0.05,
show_titles = TRUE,
show_grid = FALSE,
color_points = "#AAAAAA",
color_line = "black",
color_line_spike = "black",
color_fill = "#000000",
shape = 16,
size_points = 1,
size_points_spike = 2,
linetype = "solid",
linewidth = 1,
alpha_fill = 0.1,
...
)
x |
A fitted |
terms |
Names of the variables to plot, for example,
|
partial_only |
Whether to show only the fitted effect and confidence
interval. Defaults to |
type |
Either |
ref |
Named list of reference values for contrast plots, for example,
|
terms_seq |
Either |
alpha |
Significance level for confidence intervals. The default,
|
show_titles |
Whether to show titles describing the fitted
transformation or variable representation. Defaults to |
show_grid |
Whether to show the major and minor panel grid lines of
|
color_points |
Colour of component-plus-residual points, for example,
|
color_line |
Colour of fitted curves and fitted points for binary
predictors and factors, for example, |
color_line_spike |
Colour of the separate zero endpoint for a
|
color_fill |
Fill colour of confidence bands, for example,
|
shape |
Shape of component-plus-residual points. Common ggplot2
shape codes include |
size_points |
Numeric size of component-plus-residual points,
in millimetres, for example, |
size_points_spike |
Numeric size of fitted points for binary
predictors, factors, and zero endpoints.
For example, use |
linetype |
Line style of fitted curves, for example, |
linewidth |
Numeric width of fitted curves, for example, |
alpha_fill |
Confidence-band transparency, from |
... |
Additional arguments are not used. Supplying |
A named list of ggplot2 objects, one per plotted variable.
Individual plots can be printed by name or position and modified using
ggplot2.
Use type to choose what the fitted curve or fitted points represent:
"terms" (default) shows a variable's fitted contribution, using the
relationship selected during fitting.
"contrasts" shows the difference from a reference value. See
Contrasts and reference values.
Fitted contributions use the following model scales:
Gaussian with an identity link: contributions to the mean response, in the same units as the response used for fitting. For example, fitting log-PSA gives contributions to mean log-PSA.
Binomial with a logit link: log-odds.
Poisson and negative-binomial with a log link: log mean.
Negative-binomial with a square-root link: square root of the mean; with an identity link: the mean.
Other GLM and GEE models: the scale defined by the fitted link function.
Cox: log relative hazard.
Fine–Gray: log relative subdistribution hazard.
survreg: the fitted location scale, such as log time for Weibull models.
Term plots include the intercept for GLM, negative-binomial, GEE, and
survreg models. Cox and Fine–Gray terms have no intercept. Offsets are
excluded from fitted term contributions. See Multinomial and ordinal
models for their scales, panels, and intercepts.
Use terms to select variables kept in the final model. Use their original
names: "age" rather than "fp(age)", and "race" rather than individual
contrast-column names such as "raceB" and "raceC".
For example, for a model containing age, cancer volume, and the factor race:
# Plot age only.
age_plots <- plot(fit, terms = "age")
age_plots[["age"]]
# Create separate plots and combine them using patchwork, if installed.
plots <- plot(fit, terms = c("age", "cavol"))
patchwork::wrap_plots(plots, ncol = 2)
# Show all fitted race levels together.
race_plots <- plot(fit, terms = "race")
race_plots[["race"]]
Use terms_seq to choose where a numeric variable's fitted effect is
calculated:
"data" uses the observed predictor values in the data used to fit
the model.
"equidistant" uses equally spaced values between the smallest and
largest observed predictor values.
The default is "data" for term plots and "equidistant" for contrast
plots. Both settings use the same fitted model.
# Evaluate the curve at observed ages. plots <- plot(fit, terms = "age", terms_seq = "data") # Evaluate it at equally spaced ages over the same range. curves <- plot( fit, terms = "age", terms_seq = "equidistant", partial_only = TRUE ) curves[["age"]]
See Binary and categorical predictors for discrete variables.
To obtain estimates at specific new values, use predict.mfp2() with
newdata and terms_seq = "data", then plot its output. An example is
included below.
A contrast is:
contribution at the plotted value - contribution at the reference.
For example, compare each age with age 50:
plots <- plot( fit, terms = "age", type = "contrasts", ref = list(age = 50) ) plots[["age"]]
The contrast is zero at age 50. Above zero, the fitted contribution is larger than at age 50; below zero, it is smaller. Intercepts cancel from the comparison.
The interpretation follows the model scale: a Gaussian identity-link contrast is a difference in mean response; a binomial logit contrast is a log odds ratio; and a log-link count-model contrast is a log ratio of mean counts. Cox and Fine–Gray contrasts are log hazard ratios and log subdistribution hazard ratios, respectively. These comparisons hold the other predictors and any offset fixed and, where applicable, use the same stratum.
Supply references on the original variable scale. The fitted shift,
transformation, and centering are applied automatically. For example, if
age was fitted using log(age + 10), supply ref = list(age = 50), not
list(age = 60) or list(age = log(60)).
For a formula factor, use a category label available during fitting. For example, if race has categories A, B, and C, compare each with race A:
plots <- plot( fit, terms = "race", type = "contrasts", ref = list(race = "A") ) plots[["race"]]
If a reference is omitted, the function uses:
the smaller value for a numeric predictor with two distinct values;
the observed mean in the fitting data for other numeric predictors;
the first fitted level for a formula factor.
See Contrasts and reference values in predict.mfp2() for further
details.
By default, term plots add one component-plus-residual point for each observation used to fit the model. Each point has:
a horizontal position given by the observed predictor value;
a height equal to the fitted contribution at that value plus a residual from the complete model.
These points leave out the fitted contributions of the other predictors, while keeping the plotted predictor's contribution and the residual from the complete model. This helps assess the fitted relationship while accounting for the other predictors. Residuals are calculated from the complete fitted model, including any offsets.
The type of residual added depends on the model:
GLM, negative-binomial, and survreg: deviance residuals.
GEE: deviance residuals based on fitted marginal means and prior weights.
Cox: martingale residuals.
Fine–Gray: martingale residuals from the weighted Cox fit, summed over each subject's expanded rows.
Multinomial: binary deviance residuals comparing each non-reference category with all other categories. This differs from the comparison with the reference category shown by the fitted curve.
Ordinal: deviance residuals for the cutoff shown in each panel.
For non-Gaussian models, these points provide a diagnostic display rather
than an exact adjustment of the observed response for other predictors.
Points always use observed predictor values, even when the fitted curve
uses terms_seq = "equidistant".
Set partial_only = TRUE to hide the component-plus-residual points:
curves <- plot(fit, terms = "age", partial_only = TRUE) curves[["age"]]
Contrast plots always omit component-plus-residual points.
Confidence bands and vertical intervals describe uncertainty in the fitted contribution or contrast, rather than the spread of component-plus-residual points. They use the estimated uncertainty in the final model's coefficients and apply to each plotted value individually. They are not prediction intervals for future outcomes.
The intervals treat the selected model as fixed. They do not account for uncertainty from selecting variables, FP powers, or spike-at-zero components. For GEE models, they use the covariance selected for the fit.
Multinomial models return one plot per variable, with a panel for each
non-reference category. A panel labelled "B vs A" shows the fitted
contribution to the log-odds of category B versus reference category A,
including that comparison's intercept for term plots. The fitted
transformation is shared across panels, but the coefficients differ.
Contrasts are shown separately for each category comparison.
Ordinal term plots have one panel per response cutoff. For ordered categories low, medium, and high, the panels compare medium/high with low, and high with low/medium. Each curve and confidence interval includes its cutoff intercept. The default logistic link uses cumulative log-odds; other ordinal links use their corresponding link scale.
Ordinal contrast plots show the shared predictor effect without cutoff intercepts and therefore use a single panel.
Binary predictors and formula factors are displayed using fitted points and vertical confidence intervals rather than a continuous curve. Numeric binary predictors use their observed values on the horizontal axis; formula factors use their fitted category labels.
For numeric predictors with only two values in multinomial or ordinal
models, use terms_seq = "data" to avoid displaying intermediate values.
For a term fitted with zero = TRUE, the continuous function is defined
for positive values. Its curve and confidence band are drawn only above
zero, with the fitted value at exactly zero shown as a separate point.
Centering can make that contribution nonzero. This point comes from the
continuous term and does not represent a separately estimated zero effect.
A catzero term also includes a separately estimated zero indicator.
A spike-at-zero term follows the representation selected in the final model:
a positive-value function with a zero indicator;
the positive-value function alone;
the zero indicator alone.
When a continuous component is retained, the positive-value curve is not
connected to the zero endpoint. For catzero and spike-at-zero terms,
that endpoint uses color_line_spike; for zero = TRUE alone, it uses
color_line.
A binary-only spike term uses labels such as "exposure = 0" and
"exposure > 0", with fitted points in color_line.
predict.mfp2(), mfp2()
## Gaussian models: terms and contrasts
data("prostate")
fit_gaussian <- mfp2(
lpsa ~ fp(age) + fp(cavol) + fp(weight) + svi,
data = prostate,
keep = c("age", "cavol"),
verbose = FALSE
)
# Plotting requires ggplot2.
if (requireNamespace("ggplot2", quietly = TRUE)) {
# Term contributions with component-plus-residual points.
plots <- plot(fit_gaussian, terms = c("age", "cavol"))
print(plots[["age"]])
# Show only the fitted contribution and its confidence band.
curves <- plot(fit_gaussian, terms = "age", partial_only = TRUE)
print(curves[["age"]])
# Compare each plotted age with age 50, on the original age scale.
contrasts <- plot(
fit_gaussian,
terms = "age",
type = "contrasts",
ref = list(age = 50)
)
print(contrasts[["age"]])
# Each element is a ggplot2 object and can be modified.
print(curves[["age"]] + ggplot2::labs(x = "Age (years)"))
}
## Categorical predictors: use the factor name
fit_factor <- mfp2(
Sepal.Length ~ Species,
data = iris,
keep = "Species",
verbose = FALSE
)
if (requireNamespace("ggplot2", quietly = TRUE)) {
plot(fit_factor, terms = "Species", partial_only = TRUE)[["Species"]]
}
## A predictor with a spike at zero
set.seed(1)
d_spike <- data.frame(exposure = c(rep(0, 35), runif(85, 0.1, 8)))
d_spike$y <- 2 * (d_spike$exposure > 0) + log1p(d_spike$exposure) +
rnorm(120)
fit_spike <- mfp2(
y ~ fp(exposure, spike = TRUE),
data = d_spike,
keep = "exposure",
verbose = FALSE
)
# Zero is shown separately from the curve for positive values.
if (requireNamespace("ggplot2", quietly = TRUE)) {
plot(fit_spike, terms = "exposure", partial_only = TRUE)[["exposure"]]
}
## Cox models: contributions to the log relative hazard
data("gbsg")
fit_cox <- mfp2(
survival::Surv(rectime, censrec) ~ fp(age) + fp(nodes),
data = gbsg,
family = "cox",
verbose = FALSE
)
# Points add martingale residuals to the fitted contribution.
if (requireNamespace("ggplot2", quietly = TRUE)) {
plot(fit_cox, terms = "nodes")[["nodes"]]
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.