Skip to contents

[Experimental]

gf_squaresid() is a fully supported alias of gf_square_resid(). The name honors Tyler Haslam, the Utah high school teacher whose efforts shaped the residual and squared-residual visualizations and who requested this function by that name.

Usage

gf_square_resid(plot, model, aspect = 4/6, alpha = 0.1, ...)

gf_squaresid(plot, model, aspect = 4/6, alpha = 0.1, ...)

Arguments

plot

A ggformula plot object, typically created with gf_point().

model

A fitted linear model object created using lm().

aspect

A numeric value controlling the square's aspect ratio. Default is 4/6.

alpha

A numeric value specifying the transparency of the square's fill. Default is 0.1.

...

Additional aesthetics passed to geom_polygon(), such as color and fill.

Value

A ggplot object with squared residuals added.

Details

This function adds squared residual representations to a ggformula plot, illustrating squared error as a polygon. The function dynamically adjusts the aspect ratio to ensure proper scaling of squares.

Examples

# squared residuals can be drawn on a full data set, but with hundreds of
# points the plot gets hard to read
flipper_model <- lm(body_mass_kg ~ flipper_length_m, data = penguins)
gf_point(body_mass_kg ~ flipper_length_m, data = penguins) %>%
  gf_model(flipper_model) %>%
  gf_square_resid(flipper_model)


# a small sample makes the squared residuals much easier to see
set.seed(1)
penguins_20 <- sample(penguins, 20)

# squared residuals from the empty model (in blue)
empty_model <- lm(body_mass_kg ~ NULL, data = penguins_20)
gf_point(body_mass_kg ~ flipper_length_m, data = penguins_20) %>%
  gf_model(empty_model) %>%
  gf_square_resid(empty_model, color = "blue")


# squared residuals from a two-group model on a jitter plot (in firebrick)
gentoo_model <- lm(body_mass_kg ~ gentoo, data = penguins_20)
gf_jitter(body_mass_kg ~ gentoo, data = penguins_20, width = .1) %>%
  gf_model(gentoo_model) %>%
  gf_square_resid(gentoo_model, color = "firebrick")


# squared residuals from a regression model (in firebrick)
sample_flipper_model <- lm(body_mass_kg ~ flipper_length_m, data = penguins_20)
gf_point(body_mass_kg ~ flipper_length_m, data = penguins_20) %>%
  gf_model(sample_flipper_model) %>%
  gf_square_resid(sample_flipper_model, color = "firebrick")