A function for visualizing regression models quickly and easily. Default plots contain a
confidence band, prediction line, and partial residuals. Factors, transformations, conditioning,
interactions, and a variety of other options are supported. The visreg function performs the
calculations and, if plot=TRUE (the default), these calculations are passed to plot.visreg
for plotting.
Arguments
- fit
The fitted model object you wish to visualize. Any object with 'predict' and 'model.frame' methods are supported, including lm, glm, gam, rlm, coxph, and many more.
- xvar
Character string specifying the variable to be put on the x-axis of your plot. Both continuous variables and factors are supported.
- by
(Optional) A variable allowing you to divide your plot into cross-sections based on levels of the
byvariable; particularly useful for visualizing models with interactions. Supplied as a character string. Cross-sections are displayed as facets of a ggplot2 plot. Both continuous variables and factors are supported.- breaks
If a continuous variable is used for the
byoption, thebreaksargument controls the values at which the cross-sections are taken. By default, cross-sections are taken at the 10th, 50th, and 90th quantiles. Ifbreaksis a single number, it specifies the number of breaks. Ifbreaksis a vector of numbers, it specifies the values at which the cross-sections are to be taken. Each partial residuals appears exactly once in the plot, in the panel it is closest to.- type
The type of plot to be produced. The following options are supported:
If
"conditional"is selected, the plot returned shows the value of the variable on the x-axis and the change in response on the y-axis, holding all other variables constant (by default, median for numeric variables and most common category for factors).If
"contrast"is selected, the plot returned shows the effect on the expected value of the response by moving the x variable away from a reference point on the x-axis (for numeric variables, this is taken to be the mean). For more details, see references.
- data
The data frame used to fit the model. Typically, visreg() can figure out where the data is, so it is not necessary to provide this. In some cases, however, the data set cannot be located and must be supplied explicitly.
- trans
(Optional) A function specifying a transformation for the vertical axis.
- scale
By default, the model is plotted on the scale of the linear predictor. If
scale='response'for a glm, the inverse link function will be applied so that the model is plotted on the scale of the original response.- alpha
Alpha level (1-coverage) for the confidence band displayed in the plot (default: 0.05).
- nn
Controls the smoothness of the line and confidence band. Increasing this number will add to the computational burden, but produce a smoother plot (default: 101).
- cond
Named list specifying conditional values of other explanatory variables. By default, conditional plots in visreg are constructed by filling in other explanatory variables with the median (for numeric variables) or most common category (for factors), but this can be overridden by specifying their values using
cond(see examples).- collapse
If the
predictmethod forfitreturns a matrix, should this be returns as multiple visreg objects bound together as a list (collapse=FALSE) or collapsed down to a singlevisregobject (collapse=TRUE).- plot
Send the calculations to
plot.visreg()? Default is TRUE.- predict
Named list of additional arguments to pass to
predict()(e.g.,list(re.form = NA)for a mixed model). Most models never need this; it exists as an escape hatch sincepredict()methods vary by model class and aren't otherwise accessible fromvisreg().- ...
Graphical parameters (e.g.,
partial) to pass toplot.visreg()(see examples below).
Value
A visreg or visreg_list object (which is simply a list of visreg objects). A visreg` object
has three components:
- fit
A data frame with
nnrows containing the fit of the model asxvarvaries, along with lower and upper confidence bounds (namedvisreg_fit,visreg_lwr, andvisreg_upr, respectively). The fitted matrix of coefficients.- res
A data frame with
nrows, wherenis the number of observations in the original data set used to model. This frame contains information about the residuals, namedvisregRegandvisreg_pos; the latter records whether the residual was positive or negative.- meta
Contains meta-information needed to construct plots, such as the name of the x and y variables, whether there were any
byvariables, etc.
Note that if plot = TRUE (the default), then the visreg object is passed to plot.visreg()
and a ggplot object is returned instead.
Details
See plot.visreg() for plotting options, such as changing the appearance of points, lines,
confidence bands, etc.
References
Breheny P and Burchett W. (2017) Visualization of regression models using visreg. R Journal, 9: 56–71. doi:10.32614/RJ-2017-046
See also
plot.visreg() for plotting options, visreg2d() for creating two-dimensional visreg objects,
and the package website for detailed explanations and
examples.
Examples
library(ggplot2)
# --- Linear models ----------------------------------------
## Basic
fit <- lm(Ozone ~ Solar.R + Wind + Temp, data = airquality)
visreg(fit, "Wind", type = "contrast")
visreg(fit, "Wind", type = "conditional")
## Factors
airquality$Heat <- cut(airquality$Temp, 3, labels = c("Cool", "Mild", "Hot"))
fit.heat <- lm(Ozone ~ Solar.R + Wind + Heat, data = airquality)
visreg(fit.heat, "Heat", type = "contrast")
visreg(fit.heat, "Heat", type = "conditional")
## Transformations
fit1 <- lm(Ozone ~ Solar.R + Wind + Temp + I(Wind^2), data = airquality)
fit2 <- lm(log(Ozone) ~ Solar.R + Wind + Temp, data = airquality)
fit3 <- lm(log(Ozone) ~ Solar.R + Wind + Temp + I(Wind^2), data = airquality)
visreg(fit1, "Wind")
visreg(fit2, "Wind", trans = exp) + ylab("Ozone")
visreg(fit3, "Wind", trans = exp) + ylab("Ozone")
## Conditioning
visreg(fit, "Wind", cond = list(Temp = 50))
visreg(fit, "Wind", print_cond = TRUE)
#> Conditions used in construction of plot
#> Solar.R: 207
#> Temp: 79
visreg(fit, "Wind", cond = list(Temp = 100))
## Interactions
fit_int <- lm(Ozone ~ Solar.R + Wind * Heat, data = airquality)
visreg(fit_int, "Wind", by = "Heat")
visreg(fit_int, "Heat", by = "Wind")
visreg(fit_int, "Wind", by = "Heat", type = "contrast")
visreg(fit_int, "Heat", by = "Wind", breaks = 6)
visreg(fit_int, "Heat", by = "Wind", breaks = c(0, 10, 20))
## Overlay
visreg(fit_int, "Wind", by = "Heat", overlay = TRUE)
# --- Nonlinear models -------------------------------------
## Logistic regression
data("birthwt", package = "MASS")
birthwt$race <- factor(birthwt$race, labels = c("White", "Black", "Other"))
birthwt$smoke <- factor(birthwt$smoke, labels = c("Nonsmoker", "Smoker"))
fit <- glm(low ~ age + race + smoke + lwt, data = birthwt, family = "binomial")
visreg(fit, "lwt") +
xlab("Mother's Weight") +
ylab("Log odds (low birthweight)")
visreg(fit, "lwt", scale = "response", partial = FALSE) +
xlab("Mother's Weight") +
ylab("P(low birthweight)")
## Proportional hazards
data(cancer, package="survival")
ovarian$rx <- factor(ovarian$rx)
fit <- survival::coxph(
survival::Surv(futime, fustat) ~ age + rx,
data = ovarian
)
visreg(fit, "age") + ylab("log(Hazard ratio)")
## Robust regression
fit <- MASS::rlm(Ozone ~ Solar.R + Wind * Heat, data = airquality)
visreg(fit, "Wind", cond = list(Heat = "Mild"))
## And more...; anything with a 'predict' method should work
## Return raw components of plot
v <- visreg(fit, "Wind", cond = list(Heat = "Mild"))