# generate artificial data
set.seed(4321)
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x, y)
# plot residuals from linear model
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = y ~ x)
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = y ~ x, weighted = TRUE)
# plot residuals from linear model with y as explanatory variable
ggplot(my.data, aes(x, y)) +
geom_vline(xintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = x ~ y) +
coord_flip()
# give a name to a formula
my.formula <- y ~ poly(x, 3, raw = TRUE)
# plot residuals from linear model
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = my.formula) +
coord_flip()
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = my.formula, resid.type = "response")
# plot residuals from robust regression
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = my.formula, method = "rlm")
# plot residuals with weights indicated by colour
my.data.outlier <- my.data
my.data.outlier[6, "y"] <- my.data.outlier[6, "y"] * 10
ggplot(my.data.outlier, aes(x, y)) +
stat_fit_residuals(formula = my.formula, method = "rlm",
mapping = aes(colour = after_stat(weights)),
show.legend = TRUE) +
scale_color_gradient(low = "red", high = "blue", limits = c(0, 1),
guide = "colourbar")
# plot weighted residuals with weights indicated by colour
ggplot(my.data.outlier) +
stat_fit_residuals(formula = my.formula, method = "rlm",
mapping = aes(x = x,
y = stage(start = y, after_stat = y * weights),
colour = after_stat(weights)),
show.legend = TRUE) +
scale_color_gradient(low = "red", high = "blue", limits = c(0, 1),
guide = "colourbar")
# plot residuals from quantile regression (median)
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = my.formula, method = "rq")
# plot residuals from quantile regression (upper quartile)
ggplot(my.data, aes(x, y)) +
geom_hline(yintercept = 0, linetype = "dashed") +
stat_fit_residuals(formula = my.formula, method = "rq",
method.args = list(tau = 0.75))
# inspecting the returned data
gginnards.installed <- requireNamespace("gginnards", quietly = TRUE)
if (gginnards.installed)
library(gginnards)
if (gginnards.installed)
ggplot(my.data, aes(x, y)) +
stat_fit_residuals(formula = my.formula, resid.type = "working",
geom = "debug")
if (gginnards.installed)
ggplot(my.data, aes(x, y)) +
stat_fit_residuals(formula = my.formula, method = "rlm",
geom = "debug")
Run the code above in your browser using DataLab