Skip to contents

ggsprings is a ggplot2 extension that draws springs, instead of straight lines, between pairs of points. Aside from possible artistic use, the main impetus for this is to illustrate statistical ideas by their physical analogs: least squares problems such as the sample mean, the multivariate centroid, linear and non-linear regression and principal components analysis are all “solved” by a system of springs coming to rest.

Animation of a rod pulled by springs attached to data points; it swings and settles on the least squares regression line.

The goal of the package is to make this idea into something concrete you can play with, use for your own examples and perhaps extend. The initial idea and code came from the springs case study in ggplot2: Elegant Graphics for Data Analysis (3e), Ch. 21. But actually making that work took many iterations:

  • the physics had to work: How to characterize a spring, with it’s properties of length, stiffness, and the forces it exerts, in a graphic analog of a physical system.

  • the ggplot implementation had to work: What appeared in the ggplot case study was just a basic sketch, suggesting stat_spring(), geom_spring() and some infrastructure to show how something like this could be done in ggplot2. But, the devil is always in the details, and the most work in this release was how to make that work with grouping and faceting by factors, and their legends.

  • Animate This!: A further challenge was how to use this to make animated graphics, which was the thought I had that motivated making this into a package. The vignette, Least squares by springs, now has two animations. Both are small simulations of the physics, drawn with geom_spring() and animated with gganimate. In the first (shown at the top), a rod is released from the wrong position and settles where the forces and torques of the springs balance: the least squares regression line. In the second, the springs are perpendicular to the rod, which then settles on the first principal component. The only difference between the two is the direction of the springs. The Inspiration section below describes the plots and animation that got this started.

Installation

ggsprings is not yet on CRAN. Install the development version from R-universe with:

install.packages("ggsprings",
                 repos = c("https://friendly.r-universe.dev", "https://cloud.r-project.org"))

or from GitHub with:

remotes::install_github("friendly/ggsprings")

Least squares by springs

A leading example is to illustrate how least squares regression is “solved” by connecting data points to a rod, where the springs are constrained to be vertical. The mathematics behind this are well-described in this Math Stackexchange post, where the least squares estimates of intercept and slope are shown to be the equilibrium position that minimizes the sum of forces and torques exerted by the springs.

By Hooke’s law, a spring stretched a distance xx exerts a force proportional to xx and stores potential energy proportional to x2x^2. The system comes to rest where the total potential energy, the sum of squared residuals, is a minimum.

Potential energy of a spring as a quadratic function of its extension, with the force given by the negative slope of the tangent line.

If the springs are allowed to be free, rather than vertical, the physical solution is the major axis of a principal components analysis.

Examples

The mean

The sample mean is the point where springs attached to each observation come to rest. Each spring has the same number of coils, so a spring is drawn more stretched the further its observation is from the mean: the picture shows the tension in each spring directly.

set.seed(1234)
N <- 10
df <- data.frame(x = runif(N, 1, 10), y = 1:N)
xbar <- mean(df$x)

ggplot(df, aes(x, y)) +
  geom_vline(xintercept = xbar, linewidth = 2) +
  geom_spring(aes(xend = xbar, yend = y), colour = "blue", diameter = 4) +
  geom_point(size = 4, colour = "red") +
  scale_y_continuous(breaks = 1:N) +
  labs(x = "Value (x)", y = "Observation")

Ten points connected by horizontal springs to a vertical rod at their mean.

The bivariate centroid

For points in two dimensions, the centroid (x‾,y‾)(\bar{x}, \bar{y}) is where a free point attached by springs to all the observations comes to rest.

set.seed(1234)
df <- data.frame(x = runif(N, 1, 10), y = runif(N, 1, 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 = 4, colour = "red") +
  annotate("point", x = xbar, y = ybar, size = 6, shape = 15) +
  coord_equal()

Ten points connected by springs to their centroid, shown as a black square.

Regression: residual springs

geom_residual_springs() fits the same model as geom_smooth() and draws a spring from each observation to its fitted value. Any method and formula that geom_smooth() accepts can be used.

ggplot(mtcars, aes(wt, mpg)) +
  geom_smooth(method = lm, formula = y ~ x, se = FALSE) +
  geom_residual_springs(method = lm, formula = y ~ x) +
  geom_point(size = 2)

Scatterplot of mpg against weight with a regression line; each point is connected to the line by a vertical spring.

Fits are computed separately for each group (or facet panel), as with geom_smooth(), and the springs look the same whatever the scales of x and y:

ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
  geom_smooth(method = lm, formula = y ~ x, se = FALSE) +
  geom_residual_springs(method = lm, formula = y ~ x) +
  geom_point(size = 2) +
  labs(colour = "Cylinders")

Separate regression lines and residual springs for cars with 4, 6 and 8 cylinders.

A weight aesthetic is used as case weights in the fit and as the stiffness of each spring, so weighted least squares can be shown too. As with a real spring, a stiffer spring has fewer coils, and it is drawn thicker. Here two observations (red) have weight 5. They pull the weighted fit (solid) toward them, away from the unweighted fit (dashed), so their residuals are small: short, stiff springs.

set.seed(3)
d <- data.frame(x = 1:10, w = c(1, 1, 1, 5, 1, 1, 5, 1, 1, 1))
d$y <- 2 + 0.8 * d$x + rnorm(10, sd = 1.2) + ifelse(d$w == 5, 2.2, 0)

ggplot(d, aes(x, y, weight = w)) +
  geom_smooth(aes(weight = NULL, linetype = "unweighted"),
              method = lm, formula = y ~ x, se = FALSE, colour = "grey50") +
  geom_smooth(aes(linetype = "weighted"), method = lm, formula = y ~ x, se = FALSE) +
  geom_residual_springs(aes(colour = after_stat(factor(weight))),
                        method = lm, formula = y ~ x, coils = 6, diameter = 3.5) +
  geom_point(aes(colour = factor(w)), size = 3) +
  scale_colour_manual(values = c("1" = "#4A90D9", "5" = "#D9534F"), name = "weight") +
  scale_linetype_manual(values = c(unweighted = "dashed", weighted = "solid"), name = "fit")

Weighted and unweighted regression lines; two heavily weighted points, in red, are attached by short, thick springs with few coils and pull the weighted line toward them.

Spring aesthetics

Besides the usual colour, linewidth, linetype and alpha, geom_spring() understands:

  • diameter: the diameter of the coils, in mm (default 3);
  • coils: the number of coils in each spring (default 10);
  • weight: the stiffness of each spring (default 1); the line width is scaled by sqrt(weight).

Every spring has the same number of coils, so a short spring is drawn with its coils close together and a long one is stretched out:

df <- data.frame(x = 0, y = 1:5, xend = c(1, 2.5, 4, 6.5, 10))

ggplot(df, aes(x, y, xend = xend, yend = y)) +
  geom_spring(diameter = 5) +
  labs(x = "length", y = NULL)

Five horizontal zigzag springs with 10 coils each and lengths from 1 to 10; the coils of the short springs are close together, those of the long springs spread out.

The shape argument changes how springs are drawn: "zigzag" (the default), "wave", or "coil", with round coils that open into a wave as the spring is stretched. Here are a short and a long spring in each shape:

shapes <- c("zigzag", "wave", "coil")
df <- data.frame(shape = rep(shapes, each = 2),
                 y = rep(3:1, each = 2) + c(0.15, -0.15),
                 x = 0, xend = c(3, 9))

p <- ggplot(df, aes(x, y, xend = xend, yend = y)) +
  scale_y_continuous(breaks = 3:1, labels = shapes, limits = c(0.6, 3.4)) +
  labs(x = "length", y = "shape")
for (s in shapes) {
  p <- p + geom_spring(data = df[df$shape == s, ], shape = s, diameter = 4)
}
p

A short and a long spring drawn in each of the three shapes: zigzag, wave and coil.

Learn more

  • The vignette, Least squares by springs, describes the physics of springs, the history of mechanical least squares machines, and the relation to the geometry and algebra of least squares.
  • The package website has the full documentation.

Inspiration

A blog post by Joshua Loftus, Least squares by springs, illustrates this, citing code from Thomas Lin Pedersen. Here is his plot of lifeExp against gdpPercap from the gapminder data, with springs from each observation to the regression line:

Gapminder life expectancy versus GDP per capita, with springs connecting each country to the regression line.

In PCA, the first principal component minimizes the sum of squares of perpendicular distances of the points to the line:

Principal components line with perpendicular springs to each point.

This Cross Validated answer shows an animation of fitting PCA by springs. The forces of the springs initially produce large changes in the fitted line, which swings back and forth across its final position until the forces balance out. (It is written in Matlab, using the code in pca_animation.m.)

Animation of a line rotating to its principal component position as springs pull on it.

An interactive demo by Trey Goesh lets you move points and change spring parameters to see the effect.

Acknowledgments

Thanks to the ggplot2 extenders club, particularly Gina Reynolds (@EvaMaeRey), who contributed the functions for fitted values and residual springs (adapted from ggsmoothfit), and Teun van den Brand (@teunbrand), who helped with the documentation.