Package 'ggsprings'

Title: Draw Springs in 'ggplot2' to Illustrate Least Squares
Description: Implements an extension of 'ggplot2' which draws springs instead of straight lines between pairs of points. Aside from possible artistic use, the main impetus for this is to illustrate least squares problems by their physical analog: each observation is attached by a spring to a fitted point or line, and the stretch of each spring shows the size of its residual. Examples include the sample mean, the multivariate centroid, linear and non-linear regression, and principal components analysis.
Authors: Michael Friendly [aut, cre] (ORCID: <https://orcid.org/0000-0002-3237-0941>)
Maintainer: Michael Friendly <[email protected]>
License: GPL (>= 3)
Version: 0.5.0
Built: 2026-11-29 03:08:59 UTC
Source: https://github.com/friendly/ggsprings

Help Index


Create the path of a spring

Description

Computes the coordinates of a spring from (x, y) to (xend, yend), in the same units as the coordinates. This is the geometry used by geom_spring(), which however computes it in mm on the screen. Use create_spring() to draw a spring in data coordinates, e.g. with ggplot2::geom_path() and ggplot2::coord_equal().

Usage

create_spring(
  x,
  y,
  xend,
  yend,
  diameter = 1,
  coils = 10,
  n = 50,
  shape = c("zigzag", "wave", "coil")
)

Arguments

x, y

Starting coordinates.

xend, yend

Ending coordinates.

diameter

Diameter of the coils, in the units of x and y.

coils

Number of coils (turns) in the spring.

n

Number of points used to draw each coil.

shape

How the spring is drawn: "zigzag", "wave" or "coil". See geom_spring().

Value

A data frame with columns x and y. It has zero rows when the spring has zero length.

Examples

spring <- create_spring(x = 4, y = 2, xend = 10, yend = 6,
                        diameter = 1, coils = 8)

library(ggplot2)
ggplot(spring, aes(x, y)) +
  geom_path() +
  coord_equal()

Legend key for springs

Description

Draws a short horizontal spring as the legend key for geom_spring().

Usage

draw_key_spring(data, params, size)

Arguments

data, params, size

See ggplot2::draw_key_path().

Value

A grob.

Examples

library(ggplot2)
df <- data.frame(x = 1:3, y = 1, xend = 1:3, yend = 2:4, g = c("a", "b", "c"))
ggplot(df, aes(x, y, xend = xend, yend = yend, colour = g)) +
  geom_spring(key_glyph = draw_key_spring)

Connect observations with springs

Description

geom_spring() is similar to ggplot2::geom_segment() in that it connects a start point (x, y) to an end point (xend, yend), but it draws a spring instead of a straight line.

Usage

geom_spring(
  mapping = NULL,
  data = NULL,
  stat = "identity",
  position = "identity",
  ...,
  shape = c("zigzag", "wave", "coil"),
  n = 50,
  arrow = NULL,
  lineend = "butt",
  linejoin = "round",
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE
)

Arguments

mapping

Set of aesthetic mappings created by aes(). If specified and inherit.aes = TRUE (the default), it is combined with the default mapping at the top level of the plot. You must supply mapping if there is no plot mapping.

data

The data to be displayed in this layer. There are three options:

If NULL, the default, the data is inherited from the plot data as specified in the call to ggplot().

A data.frame, or other object, will override the plot data. All objects will be fortified to produce a data frame. See fortify() for which variables will be created.

A function will be called with a single argument, the plot data. The return value must be a data.frame, and will be used as the layer data. A function can be created from a formula (e.g. ~ head(.x, 10)).

stat

The statistical transformation to use on the data for this layer. When using a ⁠geom_*()⁠ function to construct a layer, the stat argument can be used to override the default coupling between geoms and stats. The stat argument accepts the following:

  • A Stat ggproto subclass, for example StatCount.

  • A string naming the stat. To give the stat as a string, strip the function name of the stat_ prefix. For example, to use stat_count(), give the stat as "count".

  • For more information and other ways to specify the stat, see the layer stat documentation.

position

A position adjustment to use on the data for this layer. This can be used in various ways, including to prevent overplotting and improving the display. The position argument accepts the following:

  • The result of calling a position function, such as position_jitter(). This method allows for passing extra arguments to the position.

  • A string naming the position adjustment. To give the position as a string, strip the function name of the position_ prefix. For example, to use position_jitter(), give the position as "jitter".

  • For more information and other ways to specify the position, see the layer position documentation.

...

Other arguments passed on to layer()'s params argument. These arguments broadly fall into one of 4 categories below. Notably, further arguments to the position argument, or aesthetics that are required can not be passed through .... Unknown arguments that are not part of the 4 categories below are ignored.

  • Static aesthetics that are not mapped to a scale, but are at a fixed value and apply to the layer as a whole. For example, colour = "red" or linewidth = 3. The geom's documentation has an Aesthetics section that lists the available options. The 'required' aesthetics cannot be passed on to the params. Please note that while passing unmapped aesthetics as vectors is technically possible, the order and required length is not guaranteed to be parallel to the input data.

  • When constructing a layer using a ⁠stat_*()⁠ function, the ... argument can be used to pass on parameters to the geom part of the layer. An example of this is stat_density(geom = "area", outline.type = "both"). The geom's documentation lists which parameters it can accept.

  • Inversely, when constructing a layer using a ⁠geom_*()⁠ function, the ... argument can be used to pass on parameters to the stat part of the layer. An example of this is geom_area(stat = "density", adjust = 0.5). The stat's documentation lists which parameters it can accept.

  • The key_glyph argument of layer() may also be passed on through .... This can be one of the functions described as key glyphs, to change the display of the layer in the legend.

shape

How each spring is drawn:

  • "zigzag" (the default): the classic textbook spring.

  • "wave": a smooth wave, a coil seen exactly from the side.

  • "coil": round coils when compressed, opening into a wave when stretched.

With "zigzag" and "wave" every spring has the same form, so only the spacing of its coils shows how far it is stretched. This makes springs of different lengths easy to compare.

n

Number of points used to draw each coil of a spring (ignored for "zigzag", which needs only its turning points).

arrow

specification for arrow heads, as created by grid::arrow().

lineend

Line end style (round, butt, square).

linejoin

Line join style (round, mitre, bevel).

na.rm

If FALSE, the default, missing values are removed with a warning. If TRUE, missing values are silently removed.

show.legend

logical. Should this layer be included in the legends? NA, the default, includes if any aesthetics are mapped. FALSE never includes, and TRUE always includes. It can also be a named logical vector to finely select the aesthetics to display. To include legend keys for all levels, even when no data exists, use TRUE. If NA, all levels are shown in legend, but unobserved levels are omitted.

inherit.aes

If FALSE, overrides the default aesthetics, rather than combining with them. This is most useful for helper functions that define both data and aesthetics and shouldn't inherit behaviour from the default plot specification, e.g. annotation_borders().

Details

Each spring has a fixed number of coils, so a longer spring is drawn more stretched out than a shorter one. This is the visual analog of Hooke's law: the force exerted by a spring is proportional to how far it is stretched. Springs connecting data points to a fitted line or point therefore show, directly, the forces whose balance gives the least squares solution.

The coils are computed when the plot is drawn, in physical units (mm), so they are always round and look the same in every facet panel and group, whatever the scales of x and y. Only the endpoints are transformed by the coordinate system; in non-linear coordinate systems such as ggplot2::coord_polar() the axis of each spring is a straight line on the screen.

Value

A ggplot2 layer

Aesthetics

geom_spring() understands the following aesthetics (required aesthetics are in bold):

  • x

  • y

  • xend

  • yend

  • colour

  • linewidth

  • linetype

  • alpha

  • diameter

  • coils

  • weight

The spring-specific aesthetics are:

  • diameter: Diameter of the spring coils, in mm (default 3).

  • coils: Number of coils (turns) in each spring (default 10). Need not be a whole number.

  • weight: The stiffness (spring constant) of each spring (default 1). As with a real spring, whose stiffness is inversely proportional to its number of coils, a stiffer spring is drawn with fewer coils (coils / weight, but at least 1), and thicker (linewidth * sqrt(weight)). Used with a weighted fit, this shows weighted least squares: the heavily weighted observations have short residuals, drawn as short, stiff springs.

See Also

geom_residual_springs() to draw springs from the observations to a fitted smooth.

Examples

library(ggplot2)

# springs connecting points to their mean
set.seed(1234)
df <- data.frame(x = runif(10, 0, 10), y = runif(10, 0, 10))
xbar <- mean(df$x)
ybar <- mean(df$y)

ggplot(df, aes(x, y)) +
  geom_spring(aes(xend = xbar, yend = ybar), colour = "blue") +
  geom_point(size = 3, colour = "red") +
  annotate("point", x = xbar, y = ybar, size = 5, shape = 15)

# spring aesthetics, with groups and facets
df <- data.frame(
  x = runif(6, max = 10), y = runif(6, max = 10),
  xend = runif(6, max = 10), yend = runif(6, max = 10),
  class = rep(c("a", "b"), 3),
  coils = c(5, 10, 15, 5, 10, 15)
)

ggplot(df, aes(x, y, xend = xend, yend = yend, colour = class)) +
  geom_spring(aes(coils = coils), diameter = 4) +
  facet_wrap(~class)

# spring shapes
df <- data.frame(x = 0, xend = c(2, 5, 10), y = 1:3)
p <- ggplot(df, aes(x, y, xend = xend, yend = y))
p + geom_spring(diameter = 5)
p + geom_spring(diameter = 5, shape = "wave")
p + geom_spring(diameter = 5, shape = "coil")

ggSprings extensions to ggplot2

Description

GeomSpring is the ggproto class behind geom_spring(). It is used for extending ggplot2 and is not intended to be used directly.


Fitted values, residuals and residual springs from a smoother

Description

These layers use the same fitting machinery as ggplot2::geom_smooth(), but return the fitted values at the observed x values (or at xseq), keeping the observed y as yend. This makes it easy to draw the residuals from any smoothing method and formula as points, segments or springs.

Usage

layer_smooth_fit(
  mapping = NULL,
  data = NULL,
  stat = StatSmoothFit,
  geom = GeomPointAccent,
  position = "identity",
  ...,
  show.legend = NA,
  inherit.aes = TRUE
)

stat_smooth_fit(..., geom = GeomPointAccent)

geom_smooth_fit(...)

geom_residuals(...)

geom_residual_springs(...)

Arguments

mapping, data, position, show.legend, inherit.aes

See ggplot2::layer().

stat

The stat; defaults to StatSmoothFit.

geom

The geom used to draw the result.

...

Other arguments passed to the layer, e.g. method, formula, method.args, span, xseq, and fixed aesthetics.

Details

  • geom_smooth_fit() draws the fitted values as points.

  • geom_residuals() draws the residuals as line segments.

  • geom_residual_springs() draws the residuals as springs.

  • stat_smooth_fit() and layer_smooth_fit() are the general constructors.

A weight aesthetic is used as case weights in the fit (as in ggplot2::geom_smooth()) and, in geom_residual_springs(), as the stiffness of each spring (fewer, thicker coils; see geom_spring()), so that a weighted least squares fit can be shown.

Value

A ggplot2 layer

Examples

library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  geom_smooth(method = lm, formula = y ~ x, se = FALSE)

p + geom_residual_springs(method = lm, formula = y ~ x)
p + geom_residuals(method = lm, formula = y ~ x)

# by group
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_point() +
  geom_smooth(method = lm, formula = y ~ x, se = FALSE) +
  geom_residual_springs(method = lm, formula = y ~ x)