# package 'broom' needs to be installed to run these examples
broom.installed <- requireNamespace("broom", quietly = TRUE)
gginnards.installed <- requireNamespace("gginnards", quietly = TRUE)
if (broom.installed) {
library(broom)
}
# Regression by panel example
# simpler alternative: stat_poly_eq()
#
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_poly_line() +
geom_point(aes(colour = factor(cyl))) +
stat_fit_glance(method = "lm",
label.y = "bottom",
method.args = list(formula = y ~ x),
mapping =
aes(label =
after_stat(
sprintf('italic(r)^2~"="~%.3f~~italic(P)~"="~%.2g',
r.squared, p.value))),
parse = TRUE)
# Flipped regression by panel example
# simpler alternative: stat_poly_eq()
#
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_poly_line(orientation = "y") +
geom_point(aes(colour = factor(cyl))) +
stat_fit_glance(method = "lm",
orientation = "y",
label.y = "bottom",
method.args = list(formula = y ~ x),
mapping =
aes(label =
after_stat(
sprintf('italic(r)^2~"="~%.3f~~italic(P)~"="~%.2g',
r.squared, p.value))),
parse = TRUE)
# Regression by group example
# simpler alternative: stat_poly_eq()
#
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, colour = factor(cyl))) +
stat_poly_line() +
geom_point() +
stat_fit_glance(method = "lm",
label.y = "bottom",
method.args = list(formula = y ~ x),
mapping = aes(label =
after_stat(
sprintf('r^2~"="~%.3f~~italic(P)~"="~%.2g',
r.squared, p.value))),
parse = TRUE)
# Weighted regression example
# simpler alternative: stat_poly_eq()
#
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg, weight = cyl)) +
stat_poly_line() +
geom_point(aes(colour = factor(cyl))) +
stat_fit_glance(method = "lm",
label.y = "bottom",
method.args = list(formula = y ~ x,
weights = quote(weight)),
mapping = aes(label =
after_stat(
sprintf('r^2~"="~%.3f~~italic(P)~"="~%.2g',
r.squared, p.value))),
parse = TRUE)
# correlation test
# simpler alternative: stat_correlation()
#
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
stat_fit_glance(method = "cor.test",
label.y = "bottom",
method.args = list(formula = ~ x + y),
mapping = aes(label =
after_stat(
sprintf('r[Pearson]~"="~%.3f~~italic(P)~"="~%.2g',
estimate, p.value))),
parse = TRUE)
if (broom.installed)
ggplot(mtcars, aes(x = disp, y = mpg)) +
geom_point() +
stat_fit_glance(method = "cor.test",
label.y = "bottom",
method.args = list(formula = ~ x + y,
method = "spearman",
exact = FALSE),
mapping = aes(label =
after_stat(
sprintf('r[Spearman]~"="~%.3f~~italic(P)~"="~%.2g',
estimate, p.value))),
parse = TRUE)
# Inspecting the returned data using geom_debug_group()
#
if (gginnards.installed) {
library(gginnards)
}
if (broom.installed && gginnards.installed) {
ggplot(mtcars, aes(x = disp, y = mpg)) +
stat_smooth(method = "lm") +
geom_point(aes(colour = factor(cyl))) +
stat_fit_glance(method = "lm",
method.args = list(formula = y ~ x),
geom = "debug_group")
}
Run the code above in your browser using DataLab