# Package 'broom' needs to be installed to run these examples.
# We check availability before running them to avoid errors.
if (requireNamespace("broom", quietly = TRUE)) {
broom.installed <- TRUE
library(broom)
library(quantreg)
# Inspecting the returned data using geom_debug()
if (requireNamespace("gginnards", quietly = TRUE)) {
library(gginnards)
# This provides a quick way of finding out the names of the variables that
# are available for mapping to aesthetics. This is specially important for
# this stat as these names depend on the specific tidy() method used, which
# depends on the method used, such as lm(), used to fit the model.
# Regression by panel, default column names
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_smooth(method = "lm", formula = y ~ x + I(x^2)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_tidy(method = "lm",
method.args = list(formula = y ~ x + I(x^2)),
geom = "debug")
# Regression by panel, sanitized column names
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_smooth(method = "lm", formula = y ~ x + I(x^2)) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_tidy(method = "lm",
method.args = list(formula = y ~ x + I(x^2)),
geom = "debug", sanitize.names = TRUE)
}
}
# Regression by panel example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_tidy(method = "lm",
label.x = "right",
method.args = list(formula = y ~ x),
mapping = aes(label = sprintf("Slope = %.3g\np-value = %.3g",
after_stat(x_estimate),
after_stat(x_p.value))))
# Regression by group example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, colour = factor(cyl))) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point() +
stat_fit_tidy(method = "lm",
label.x = "right",
method.args = list(formula = y ~ x),
mapping = aes(label = sprintf("Slope = %.3g, p-value = %.3g",
after_stat(x_estimate),
after_stat(x_p.value))))
# Weighted regression example
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, weight = cyl)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point(aes(colour = factor(cyl))) +
stat_fit_tidy(method = "lm",
label.x = "right",
method.args = list(formula = y ~ x, weights = quote(weight)),
mapping = aes(label = sprintf("Slope = %.3g\np-value = %.3g",
after_stat(x_estimate),
after_stat(x_p.value))))
# Quantile regression
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_smooth(method = "lm", formula = y ~ x) +
geom_point() +
stat_fit_tidy(method = "rq",
label.y = "bottom",
method.args = list(formula = y ~ x),
tidy.args = list(se.type = "nid"),
mapping = aes(label = sprintf("Slope = %.3g\np-value = %.3g",
after_stat(x_estimate),
after_stat(x_p.value))))
Run the code above in your browser using DataLab