stat_fit_augment() fits a model and returns a "tidy"
version of the model's data with prediction added, using augmnent()
methods from packages 'broom', 'broom.mixed', or other sources. The
prediction can be added to the plot as a line.
Arguments
- mapping
The aesthetic mapping, usually constructed with
aes(). Only needs to be set at the layer level if you are overriding the plot defaults.- data
A layer specific dataset - only needed if you want to override the plot defaults.
- geom
The geometric object to use display the data
- position
The position adjustment to use for overlapping points on this layer
- ...
other arguments passed on to
layer. This can include aesthetics whose values you want to set, not map. Seelayerfor more details.- method
character or function.
- method.args, augment.args
list of arguments to pass to
methodand to tobroom::augment.- n.min
integer Minimum number of distinct values in the explanatory variable (on the rhs of formula) for fitting to the attempted.
- fit.seed
RNG seed argument passed to
set.seed(). Defaults toNA, which means thatset.seed()will not be called.- level
numeric Level of confidence interval to use (0.95 by default)
- y.out
character (or numeric) index to column to return as
y.- na.rm
logical indicating whether
NAvalues should be stripped before the computation proceeds.- show.legend
logical. Should this layer be included in the legends?
NA, the default, includes if any aesthetics are mapped.FALSEnever includes, andTRUEalways includes.- inherit.aes
If
FALSE, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification, e.g.borders.
Details
stat_fit_augment() together with
stat_fit_glance() and stat_fit_tidy(), based on
package 'broom' can be used with a broad range of model fitting functions
as supported at any given time by 'broom'. In contrast to
stat_poly_eq() which can generate text or expression labels
automatically, for these functions the mapping of aesthetic label
needs to be explicitly supplied in the call, and labels built on the fly.
A ggplot statistic receives as data a data frame that is not the one passed
as argument by the user, but instead a data frame with the variables mapped
to aesthetics. In other words, it respects the grammar of graphics and
consequently within arguments passed through method.args names of
aesthetics like _x_ and _y_ should be used instead of the original variable
names, while data is automatically passed the data frame. This helps ensure
that the model is fitted to the same data as plotted in other layers.
Note
The statistic stat_fit_augment can be used only with
methods that accept formulas under any formal parameter name and a
data argument. Use ggplot2::stat_smooth() instead of
stat_fit_augment in production code if the additional features are
not needed.
Although arguments passed to parameter augment.args will be
passed to augment() whether they are silently
ignored or obeyed depends on each specialization of augment(), so do
carefully read the documentation for the version of augment()
corresponding to the method used to fit the model. Be aware that
se_fit = FALSE is the default in these methods even when supported.
Warning!
Not all augment() method specializations are
defined in package 'broom'. augment() specializations for mixed
models fits of classes "lme", "nlme", "lme4" and many
others are defined in package 'broom.mixed'.
Handling of grouping
stat_fit_augment() applies the function
given by method separately to each group of observations; in
'ggplot2' factors mapped to aesthetics generate a separate group for each
level. Because of this, stat_fit_augment() is not useful for
annotating plots with results from t.test() or ANOVA or ANCOVA
(e.g., when a factor is mapped to the _x_ or _y_ aesthetics. In such cases
use instead stat_fit_tb() which applies the model fitting per panel.
Computed variables
The output of augment() is
returned as is, except for y which is set based on y.out and
y.observed which preserves the y returned by the
generics::augment methods. This renaming is needed so that the geom
works as expected.
To explore the values returned by this statistic, which vary depending
on the model fitting function and model formula we suggest the use of
geom_debug. An example is shown below.
See also
Package broom for details on how the tidying of
the result of model fits is done.
Other ggplot statistics for model fits:
stat_fit_deviations(),
stat_fit_glance(),
stat_fit_residuals(),
stat_fit_tb(),
stat_fit_tidy()
Aesthetics
stat_fit_augment() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:
| • | x | |
| • | y | |
| • | group | → inferred |
| • | ymax | → after_stat(y + .se.fit * t.value) |
| • | ymin | → after_stat(y - .se.fit * t.value) |
Learn more about setting these aesthetics in vignette("ggplot2-specs").
Examples
# Package 'broom' needs to be installed to run these examples.
# We check availability before running them to avoid errors.
broom.installed <- requireNamespace("broom", quietly = TRUE)
gginnards.installed <- requireNamespace("gginnards", quietly = TRUE)
if (broom.installed) {
library(broom)
}
# Inspecting the returned data using geom_debug_group()
if (gginnards.installed) {
library(gginnards)
}
# Regression by panel, inspecting data
if (broom.installed & gginnards.installed) {
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_augment(method = "lm",
method.args = list(formula = y ~ x),
geom = "debug_group",
dbgfun.data = colnames)
}
#> [1] "PANEL 1; group(s) -1; 'draw_function()' input 'data' (anonymous function):"
#> [1] "y" "x" ".fitted" ".resid"
#> [5] ".hat" ".sigma" ".cooksd" ".std.resid"
#> [9] "y.observed" "t.value" ".se.fit" "fm.class"
#> [13] "fm.method" "fm.formula" "fm.formula.chr" "PANEL"
#> [17] "group" "ymax" "ymin"
# Regression by panel example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_augment(method = "lm",
method.args = list(formula = y ~ x))
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_augment(method = "lm",
augment.args = list(se_fit = TRUE),
method.args = list(formula = y ~ x + I(x^2)))
# Residuals from regression by panel example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_hline(yintercept = 0, linetype = "dotted") +
stat_fit_augment(geom = "point",
method = "lm",
method.args = list(formula = y ~ x),
y.out = ".resid")
# Regression by group example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, colour = factor(cyl))) +
geom_point() +
stat_fit_augment(method = "lm",
augment.args = list(se_fit = TRUE),
method.args = list(formula = y ~ x))
# Residuals from regression by group example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, colour = factor(cyl))) +
geom_hline(yintercept = 0, linetype = "dotted") +
stat_fit_augment(geom = "point",
method.args = list(formula = y ~ x),
y.out = ".resid")
# Weighted regression example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, weight = cyl)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_augment(method = "lm",
method.args = list(formula = y ~ x,
weights = quote(weight)))
# Residuals from weighted regression example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, weight = cyl)) +
geom_hline(yintercept = 0, linetype = "dotted") +
stat_fit_augment(geom = "point",
method.args = list(formula = y ~ x,
weights = quote(weight)),
y.out = ".resid")
