To illustrate how to use
plot_smooths(), let’s first
prepare some dummy data with a factor variable and run
gam() on this data.
We need to load the following packages.
gam model includes a reference smooth
s(x2), a by-factor difference smooth
s(x2, by = fac), and a smooth
s(x0). For more
flexibility and for more complex models, using
predict_gam() and then plotting the predicted data yourself
might be helpful (see “predict-gam” vignette).
We can now plot the estimated smooths for the two levels of
fac. The function supports factors with more than 2
With models that transform the response scale (like Poisson and
binomial models), use the
transform argument with the
function to be used for transformation as the value. Let’s first load
some data and fit a Poisson GAM.
We can now plot on the response scale using
transform = exp.
It is also possible to plot a single smooth.
It is possible to plot models with interactions by specifying
faceting with the
split argument allows the user to split the factor
interaction (back) into separate factors, which can be used to facet
split takes a
named list, where each object in the list is a named vector with the
names of the new factors as strings (
c("x1", "x2")) and the
name of the factor interaction to be split as the name of this vector
x1x2 = ...).
You can use the
sep argument to specify the character
used for separating the factor interaction. By default is
"\\.", which is the default character used when creating
To plot just one or some of the facets, you should use the
conditions argument. This argument takes a list of quosures
quos(). The quosures are statements like the ones used
dplyr::filter(), and you can include multiple statements
separated by commas inside
If you need more flexibility (for example, if you’d like to be able
to select variables as aesthetics rather than facets), the most
straightforward solution is to get the predictions of the model with
get_gam_predictions() and use the standard ggplot2
To get confidence intervals,
geom_ribbon() must have a
group aesthetic set to the index column
which is automatically generated by
The difference smooth can be plotted with
plot_difference(). The difference smooth is the difference
between the smooths of two conditions (two levels in a factor). Portions
of the difference smooth confidence interval that do not include 0 are
shaded in red.
The following is a difference smooth comparing the two levels of the
fac term in the Poisson GAM above.
To plot a difference smooth from a model with factor interactions, it
is possible to specify the two levels to compare from the factor
interaction (the argument
split is not supported in