knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
library("gratia") library("mgcv")
gratia is a package to make working with generalized additive models (GAMs) in R easier, including producing plots of estimated smooths using the ggplot2 📦.
This introduction will cover some of the basic functionality of gratia to get you started. We'll work with some classic simulated data often used to illustrate properties of GAMs
df <- data_sim("eg1", seed = 42) df
and the following GAM
m <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = df, method = "REML") summary(m)
gratia provides the draw()
function to produce plots using the ggplot2
📦. To draw the estimated smooths from the GAM we fitted above, use
draw(m)
This is intended as reasonable overview of the estimated model, but it offers
limited option to modify the resulting plot. If you want full control, you can
obtain the data used to create the plot above with smooth_estimates()
sm <- smooth_estimates(m) sm
which will evaluate all smooths are unevenly spaced values over the range of the
covariate(s). If you want to evaluate only selected smooths, you can specify
which via the smooth
argument. This takes the smooth labels which are the
names of the smooths as they are known to mgcv. To list the labels for the
smooths in use
smooths(m)
To evaluate only $f(x_2)$ use
sm <- smooth_estimates(m, smooth = "s(x2)") sm
Then you can generate your own plot using the ggplot2 package, for example
library("ggplot2") library("dplyr") sm |> add_confint() |> ggplot(aes(y = .estimate, x = x2)) + geom_ribbon(aes(ymin = .lower_ci, ymax = .upper_ci), alpha = 0.2, fill = "forestgreen" ) + geom_line(colour = "forestgreen", linewidth = 1.5) + labs( y = "Partial effect", title = expression("Partial effect of" ~ f(x[2])), x = expression(x[2]) )
The appraise()
function provides standard diagnostic plots for GAMs
appraise(m)
The plots produced are (from left-to-right, top-to-bottom),
Adding partial residuals to the partial effect plots produced by draw()
can also help diagnose problems with the model, such as oversmoothing
draw(m, residuals = TRUE)
gratia is in very active development and an area of development that is currently lacking is documentation. To find out more about the package, look at the help pages for the package and look at the examples for more code to help you get going.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.