Skip to contents

[Experimental]

Usage

gf_sd_ruler(
  p,
  y = NULL,
  data = NULL,
  x = NULL,
  where = c("middle", "mean", "median"),
  color = "red",
  size = 0.8,
  ...
)

Arguments

p

A ggplot object (typically from gf_point(), gf_jitter(), or gf_histogram()).

y

The y-variable (bare name or string). Defaults to the plot's mapped y aesthetic if omitted.

data

Dataset. Defaults to p$data.

x

The x-variable (bare name or string). On scatter and jitter plots this controls the ruler's placement; on histograms it is the outcome variable. Defaults to the plot's mapped x.

where

For vertical rulers, where on the x-axis to place the ruler: "middle" (midpoint of x range), "mean", or "median". Ignored for histograms, where the ruler always starts at the mean.

color

Segment color. Default "red".

size

Segment linewidth. Default 0.8.

...

Additional arguments passed to ggplot2::geom_segment().

Value

A ggplot object with the SD ruler segment added.

Details

Adds a segment showing one standard deviation of a variable, anchored at the mean. The orientation depends on where the outcome variable lives: on a scatter or jitter plot (outcome on the y-axis) the ruler is a vertical segment placed at a chosen x position; on a histogram (outcome on the x-axis, no y aesthetic) it is a horizontal segment running from the mean to mean + SD along the baseline. The orientation is detected automatically from the plot's axis mappings.

See also

The model visualization guide shows the ruler alongside residuals and compares groups with different spread: https://coursekata.github.io/coursekata-r/articles/model-visualization.html

Examples

# the ruler runs from the mean (the empty model) up by one standard
# deviation -- it looks like a residual because SD is a typical residual
gf_point(Thumb ~ Height, data = Fingers, alpha = .4) %>%
  gf_model(lm(Thumb ~ NULL, data = Fingers)) %>%
  gf_sd_ruler()


# `where` controls placement along the x-axis
gf_point(Thumb ~ Height, data = Fingers, alpha = .4) %>%
  gf_sd_ruler(where = "mean")


# categorical x works the same way
gf_jitter(Thumb ~ Sex, data = Fingers, width = .1, alpha = .4) %>%
  gf_sd_ruler(where = "median")


# on a histogram the outcome is on the x-axis, so the ruler is horizontal
# and runs along the baseline from the mean to one SD above it
gf_histogram(~Thumb, data = Fingers, binwidth = 5) %>%
  gf_sd_ruler(color = "red", size = 2)


# name the variable explicitly when the plot does not make it obvious
gf_point(Thumb ~ Height, data = Fingers, alpha = .4) %>%
  gf_sd_ruler(y = Thumb)