
Least Squares By Springs
Michael Friendly
2026-11-28
Source:vignettes/least-squares.Rmd
least-squares.Rmd
Introduction
The method of least squares fitting is remarkable in its versatility. It grew out of practical problems in astronomy (the orbits of planets, librations of the moon) and geodesy (finding the “shape” of the earth), where astronomers and mathematicians sought to find a way to combine a collection of fallible observations (angular separation between stars) into a a single “best” estimate. Some of the best names in mathematics are associated with this discovery: Newton, Laplace, Legendre, Gauss. Stigler (1981) recounts some of this history.
It’s original application was to justify the use of the arithmetic average \(\bar{x}\) as the value that gave the smallest sum of squares of errors \(\text{SSE} =\Sigma (x - \bar{x})^2\), but the same principle gives solutions for linear least squares regression, multiple regression, smoothing splines and non-linear models, all the way to exploratory factor analysis.
As a mathematical method of estimation, least squares is also remarkably versatile in the variety of methods of proof that can justify it’s application. Minimization of the sum of squares of errors can be solved by calculus, linear algebra or by numerical optimization and even by a simple geometric argument.
It is the purpose of this vignette to show how least squares problems can also be solved by the physics of springs and a bit of the history of this idea. No need to invoke a function minimization algorithm, invert a matrix, or solve a system of equations. Just connect your observations to what you want to estimate with springs, and bingo!, let the springs give the answer.
A mechanical solution
Among the earliest physical realizations of solving least squares problems by springs, Gaines and Palfrey (1932) included the following figures to illustrate a remarkable physical device for fitting a linear relation \(y = a + b x\) to observations. In the left figure, seven uniform springs placed at \(x = 0 : 6\) are suspended from the observed values \(y_i = 5\) and from these light bands are connected to a heavy stepped plumb wheel. The dotted horizontal line represented the least squares fit; it goes through the mean \(\bar{y} = 5\) and has the equation \(\hat{y} = 5 + 0 x\). The number gauge at the left allows one to read the intercept, \(a = 5\) and from the scale markings on the wheel one can read the slope, \(b = 0\).

Figure 1: Diagrams to illustrate the use of springs in fitting a linear regression relation. Left: all observed \(y\) values are the same (\(y = 5\)); right: \(y_i = \{9, 6, 8, 4, 4, 1, 3\}\). The equation of the line can be read from the scale at the left for the intercept and the scale on the wheel for the slope.
In the figure at the right the \(y\) values are \(y_i = \{9, 6, 8, 4, 4, 1, 3\}\) which has the same sum, \(\Sigma y = 35\) The dotted fitted line again passes through the mean \(\bar{y} = 5\). The springs connecting the points to the fitted line are stretched or compressed by their deviations, \(e_i = y_i - \hat{y}\), and for equilibrium these deviations must sum to zero, \(\Sigma e_i = 0\). Each spring stores potential energy proportional to \(e_i^2\) and the system is in equilibrium when the sum of energies, \(\Sigma e_i^2\) is at its minimum.
For this problem, lm() gives \(\hat{y} = 8.43 - 1.143 \;x\) and these values can be read approximately from the device.
## (Intercept) x
## 8.429 -1.143
In reaching equilibrium, the weighted wheel is rotated through an angle proportional to the slope, \(b\), whose value is shown on the scale for the wheel. The intercept is the value shown on the scale at the left for the line at \(x=0\).
Thus, the spring diagram illustrates mechanically the properties of the least squares solution:
- The fitted line passes through the central value \(\bar{x}\) at the value of the mean \(\bar{y}\) of the \(y_i\).
- The algebraic sum of the deviations from the line is zero, \(\Sigma e_i = \Sigma (y_i - \bar{y}) = 0\).
- The sum of squares of the deviations \(\Sigma e_i^2\) is minimum.
Early history
The idea of a mechanical analog of least squares by springs actually goes back almost to the initial ideas stated in Gauss’ Theoria Motus (1809), as detailed by Farebrother (1999). Donkin (1844) was the first to suggest that in finding the best measure of location \(\tilde{x}\) in a sample, an observation \(x_0\) of weight \(g\) exerts a force proportional to \(g \cdot (\tilde{x} - x_0)\) and equilibrium requires \(\Sigma g \cdot (\tilde{x} - x_0) = 0\).
Simon Newcomb (Newcomb 1873a, 1873b) shortly extended this to the problem of finding, by least squares, the best position of a line describing changes in some astronomical observation which varies uniformly (linearly) over time. He describes the physical analog as that of a rigid rod “attracted by each of the points with a force proportional to the weight of the corresponding observation multiplied by the distance of the point to the rod” (i.e., residual).
Newcombe’s mechanical model does not refer to springs, but it is remarkable in that: (a) he recognizes weighted least squares, because observations may be more or less reliable, and (b) he recognizes the idea of influence on the rotational forces– observations further from the centroid exert greater influence on the slope of the line.
Hooke’s Law, potential energy and force
The application of springs to problems in statistics depends on understanding the physics of springs and physical systems more generally, using the concepts of potential energy, forces applied by physical objects and how these can balance in a state of equilibrium.
Linear springs
A linear spring is the one whose tension is directly proportional to its length: stretching such a spring to a length \(x\) requires the force \(F(x) = k\;x\). Force acts in a given direction, so compressing a spring requires a force \(- k\;x\). This is illustrated in the figure below, where \(x\) indicates the stretching of a spring.
](figures/Hookes-law-springs.png)
Figure 2: Hooke’s Law for springs. The force required to stretch the spring is proportional to the extension, \(x\), represented by the weights. Source: Wikipedia
Here the multiplier \(k\) is a constant (called the Hooke’s constant) that characterizes a particular spring. A small \(k\) means a lax spring, while a large \(k\) means a stiff spring. By convention, the unstretched length of such a spring is zero.
In the ggSprings package to date, all observations are considered to have the same, arbitrary spring constant. Allowing these
to vary, with a weight aesthetic would be a natural way to implement weighted least squares.
Functions, energy, force
A spring is something that acts elastically, meaning that it stores (potential) energy if you either stretch it or compress it. How much energy it stores is proportional to the square of the distance it is stretched or compressed.
\[ P(x) = \frac12 k \; x^2 \] In this notation, the force exerted by a spring, \(F(x)\) can be seen as the (negative) derivative, or slope at \(x\) of potential energy,
\[ F(x) = -\frac{d}{dx} \left( \frac12 k \; x^2 \right)= -k \; x \] A spring is at equilibrium when the potential energy is minimized, or the force exerted is zero. The general relations between mathematics and physics are shown in the table below (Levi 2009, 27).
| Mathematics | Physics |
|---|---|
| function, $f (x)$ | potential energy, $P(x)$ |
| derivative, $f\prime (x)$ | force, $F(x) = -P\prime(x)$ |
| $\min_x f(x) \implies f\prime (x) = 0$ | equilibrium, $\min_x P(x) \implies F (x) = 0$ |
These relations are illustrated in the figure below, where positive \(x\) means the spring is stretched and negative \(x\) represents compression. When the spring is stretched to \(x = 3\), the potential energy is \(P(x) = \frac12 (3^2) = 4.5\). The line through \((3, 4.5)\) tangent to the curve has slope \(P^\prime (x) = x = 3\) so the force the spring exerts is \(F(x) = -3\), where the negative sign means a force in the direction of \(x=0\).

Figure 3: Potential energy and force of a spring.
The horizontal line through \((0, 0)\), that is, when \(x = 0\) illustrates equilibrium where potential energy is minimized, and the force (slope) is \(F(0) = 0\).
Mean of a sample
The sample mean has several nice physical analogs, which stem from the properties that
the sum of deviations (\(e_i\)) of observations (\(x_i\)) from the mean \(\bar{x}\) equals 0: \(\Sigma_i e_i =\Sigma_i ( x_i - \bar{x} ) = 0\).
the sum of squared deviations is the smallest for any choice of \(\bar{x} = \min_{\bar{x}} ( x_i - \bar{x} )^2\)
Demonstration using springs
Create a set of observations, sampled randomly on [1, 10]
set.seed(1234)
N <- 8
df <- data.frame(
x = runif(N, 1, 10),
y = seq(1, N)
)
means <- colMeans(df)
xbar <- means[1] |> print()## x
## 5.176
Each spring drawn by geom_spring() has the same number of coils, so a spring is drawn more stretched
the further the observation is from the mean. This shows the tension in each spring (Hooke’s law) directly,
without having to calculate it.
Then, visualize this with springs. In the call to geom_spring() for this problem, the spring is specified to go
from the value of x to xend = xbar, while setting y and yend to the value of y. A lot of code is devoted
to making this a pretty figure.
ggplot(df, aes(x=x, y=y)) +
geom_point(size = 5, color = "red") +
geom_segment(x = xbar, xend = xbar,
y = 1/2, yend = N + 1/2,
linewidth = 3) +
geom_spring(aes(x = x, xend = xbar,
y = y, yend = y),
color = "blue",
diameter = 4,
linewidth = 1) +
labs(x = "Value (x)",
y = "Observation number") +
ylim(0, N+2) +
scale_y_continuous(breaks = 1:N) +
annotate("text", x = xbar, y = N + 1,
label = "Movable\nrod", size = 5,
lineheight = 3/4) 
Bivariate centroid
For a bivariate sample, \((x_i, y_i)\), the centroid point, \((\bar{x}, \bar{y})\) is realized physically as the result of attaching springs between the fixed points and a free, movable point. If we make the tension on the spring proportional to it’s length or the distance to the centroid, each point will have potential energy proportional to its squared distance from the movable one, where the forces balance (sum to zero).
Set this up for a sample of 10 points, uniformly distributed on (1, 10).
set.seed(1234)
N <- 10
df <- data.frame(
x = runif(N, 1, 10),
y = runif(N, 1, 10)
)The springs go from each point to the centroid, \((\bar{x}, \bar{y})\), so calculate
these now as xbar, ybar.
means <- colMeans(df)
xbar <- means[1]; ybar <- means[2]Visualize the springs:
ggplot(df, aes(x=x, y=y)) +
geom_point(size = 5, color = "red") +
geom_spring(aes(x = x, xend = xbar,
y = y, yend = ybar),
color = "blue",
diameter = 4,
linewidth = 1) +
geom_point(x = xbar, y = ybar,
size = 7,
shape = 15,
color = "black") +
scale_x_continuous(breaks = 1:10) +
scale_y_continuous(breaks = 1:10) 
Least squares regression
For linear least squares regression, we have a collection of points \((x_i, y_i)\), and it is desired to fit a “best” line \(y = a + b \times x\) that makes the sum of squares of errors, \[ \text{RSS} (a,b) = \sum_i \; \left[y_i - (a + b \times x_i) \right]^2 = \sum_i e_i^2 \] as small as possible. The representation by springs is shown in 4 where the observations are drawn as small ovals, connected to the fitted points on the line \(y = a + b \times x\), realized by a rigid rod in the mechanical analog. The Guides represent vertical channels that force the springs to work only up or down in the vertical direction.
![_Source_: [@Levi2009, p. 33]](figures/levi-least-sq-springs.png)
Figure 4: Source: (Levi 2009, 33)
Minimizing the sum of squares of the spring lengths means minimizing the potential energy of the mechanical system, and consequently the rod is in equilibrium. This implies that the sum of (vertical) forces \(F_i\) is zero, and that the sum of rotational forces, or torques around the intercept, \(A\) in the diagram is also zero.
\[\begin{eqnarray} \sum_i F_i = 0 & \implies & \sum_i e_i = 0 \tag{1} \\ \sum_i x_i F_i = 0 & \implies & \sum_i x_i e_i = 0 \tag{2} \end{eqnarray}\]
The animation in Figure 5 shows this mechanical solution in action.
The rod is released from a wrong position. The net force of the springs moves it up or down,
and their net torque rotates it. With a little friction, it swings back and forth until it comes to rest
where the forces and torques balance: the least squares line (dashed). The code for this is in
examples/animate-regression.R in the package source, using geom_spring() and gganimate.

Figure 5: Least squares by springs, animated. The rod (black) is pulled by springs attached to the data points and settles on the least squares line (dashed).
Substituting \(e_i = y_i - (a + b x_i)\) gives what are recognized as the “normal equations” for the least squares solution,
\[\begin{eqnarray*} \sum y_i - a \sum x_i - n b & = & 0 \\ \sum x_i y_i - a \sum x_i^2 - b \sum x_i & = & 0 \end{eqnarray*}\]
or, rearranging terms,
\[\begin{eqnarray*} a \sum x_i - n b & = & \sum y_i \\ a \sum x_i^2 - b \sum x_i & = & \sum x_i y_i \end{eqnarray*}\]
These equations may be more recognizable in matrix form. Letting \(\mathbf{X} = [\mathbf{1}, \mathbf{x}]\) and \(\mathbf{b} = \begin{pmatrix} a \\ b \\ \end{pmatrix}\), we arrive at
\[\begin{align*} \begin{bmatrix} n & \sum x \\ \sum x & \sum x^2 \\ \end{bmatrix} \begin{pmatrix} a \\ b \\ \end{pmatrix} & =\begin{pmatrix} \sum y \\ \sum x y \\ \end{pmatrix} \\ \mathbf{X}^\top \mathbf{X} \mathbf{b} & =\mathbf{X}^\top \mathbf{y}\end{align*}\]
from which the matrix solution is \[ \widehat{\mathbf{b}} = ( \mathbf{X}^\top \mathbf{X})^{-1} \; \mathbf{X}^\top \mathbf{y} \; , \]
as long as \((\mathbf{X}^\top \mathbf{X})^{-1}\) exists, i.e., \(\text{det}(\mathbf{X}^\top \mathbf{X}) \ne 0\).
Geometric solution
It is of interest to see how the solution using springs is equivalent to a geometric argument. 6 shows the vector space representation of a vector $ of three observations. Any possible regression line corresponds to a vector \(\boldsymbol{\beta} = (a, b)\) in the dashed plane that represents linear combinations of \(\mathbf{X} = [\mathbf{1}, \mathbf{x}]\). The least squares solution is that which minimizes the length of the residual vector \(\mathbf{y} - \widehat{\mathbf{y}} = \mathbf{e}\).

Figure 6: Geometrical interpretation of least squares regression. The vector \(\mathbf{y}\) to point A represents the data for three observations
From this diagram it can be seen that the residual vector must be orthogonal to \(\mathbf{X} = [\mathbf{1}, \mathbf{x}]\), so,
\[\begin{eqnarray*} \mathbf{X} \perp \mathbf{e} & \implies & \mathbf{X}^\top \mathbf{e} = 0 \\ & \implies &\mathbf{X}^\top (\mathbf{y}-\mathbf{X}\;\widehat{\mathbf{b}}) = 0 \\ & \implies &\mathbf{X}^\top \mathbf{y} = \mathbf{X}^\top \mathbf{X}\; \widehat{\mathbf{b}} \\ & \implies &\widehat{\mathbf{b}} = (\mathbf{X}^\top \mathbf{X}) ^\top \mathbf{X}^\top \mathbf{y} \end{eqnarray*}\]
We can also note that the orthogonality condition, \(\mathbf{X} = [\mathbf{1}, \mathbf{x}] \perp \mathbf{e}\) means that
\[\begin{eqnarray*} \mathbf{1}^\top \mathbf{e} &= \Sigma e_i = 0 \\ \mathbf{x}^\top \mathbf{e} &= \Sigma x_i e_i = 0 \;\; , \end{eqnarray*}\]
Example
For a simple example of geom_springs() for a regression problem, we plot the first two variables, x1, y1 in the
anscombe data set, together with the linear regression line.
simple_plot <-
ggplot(anscombe,
aes(x = x1, y = y1)) +
geom_point(size = 4, color = "red") +
geom_smooth(method = lm, formula = y~x,
se = FALSE,
linewidth = 1.4)
simple_plot
The current implementation of geom_springs() requires that we fit the linear model,
add the predicted value of y1 to the dataset and use that value as yend in the call to geom_spring()
model <- lm(y1 ~ x1, data = anscombe)
anscombe$fitted <- predict(model)
simple_plot +
geom_spring(data=anscombe,
aes(xend = x1, yend = fitted),
color = "blue",
linewidth = 1)
Note that diameter and coils are not specified here. By default, geom_spring() draws springs with
10 coils, 3 mm in diameter, so each spring is stretched in proportion to its residual.
Residual springs from any smoother
For regression problems, it is inconvenient to have to fit the same model that has been constructed by geom_smooth()
and add the fitted value to the dataset. geom_residual_springs(), adapted from the
ggsmoothfit repo, does this for you: it uses the same method
and formula as geom_smooth() and draws springs from each observation to its fitted value.
ggplot(anscombe, aes(x = x1, y = y1)) +
geom_point(size = 4, color = "red") +
geom_smooth(method = lm, formula = y ~ x, se = FALSE) +
geom_residual_springs(method = lm, formula = y ~ x, color = "blue")
One way to simplify spring plots for models
is to use broom::augment() for a fitted model to get the data.frame containing all necessary information.
broom::augment(model)## # A tibble: 11 × 8
## y1 x1 .fitted .resid .hat .sigma .cooksd .std.resid
## <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 8.04 10 8.00 0.0390 0.100 1.31 0.0000614 0.0332
## 2 6.95 8 7.00 -0.0508 0.1 1.31 0.000104 -0.0433
## 3 7.58 13 9.50 -1.92 0.236 1.06 0.489 -1.78
## 4 8.81 9 7.50 1.31 0.0909 1.22 0.0616 1.11
## 5 8.33 11 8.50 -0.171 0.127 1.31 0.00160 -0.148
## 6 9.96 14 10.0 -0.0414 0.318 1.31 0.000383 -0.0405
## 7 7.24 6 6.00 1.24 0.173 1.22 0.127 1.10
## 8 4.26 4 5.00 -0.740 0.318 1.27 0.123 -0.725
## 9 10.8 12 9.00 1.84 0.173 1.10 0.279 1.63
## 10 4.82 7 6.50 -1.68 0.127 1.15 0.154 -1.45
## 11 5.68 5 5.50 0.179 0.236 1.31 0.00427 0.166
Then, the anscombe example can be re-created as follows:
ans_mod <- lm(y1 ~ x1, data = anscombe)
ans_aug <- broom::augment(ans_mod)
ggplot(ans_aug) +
aes(x = x1, y = y1) +
geom_point(size = 4, color = "red") +
geom_smooth(method = lm, formula = y~x,
se = FALSE,
linewidth = 1.4) +
geom_spring(
aes(xend = x1, yend = .fitted),
color = "blue",
linewidth = 1)
Smoothing methods & families
It is also important to be able to construct spring plots for any model method that can be represented
by geom_smooth(method = AA, formula = y ~ BB), where:
methodcan be:lm,glm,loessor nearly any other fitting function, such asMASS::rlmfor robust fits ormgcv::gamfor generalized additive models, (TODO: Another reason to implement an observationweightaesthetic param.)formulacan be any model formula involving onlyyandx, such asy ~ xory ~ poly(x, 2)or eveny ~ splines::ns(x, df =)
For example Gaines and Palfrey (1932) actually constructed the machine shown in the figure 7 for fitting the relation \(y = A \; e^{-k x}\) This solved a practical agricultural problem:
Breeders of dairy cattle are accumulating a large body of yearly records of production based on the milk yield and fat test of individual cows by calendar months. The problem is to measure the rate of milk secretion for each cow by fitting the data of the first eleven full months of lactation with the equation \(y = A \; e^{-k x}\), in which \(y\) is milk-energy yield per day, and \(x\) is time in months with origin at one month after calving.

Figure 7: A mechanical spring-driven curve fitting machine,
For this figure, they say, “When the eleven stops, representing the observed y’s, are set the machine immediately indicates the fitted \(A\) and \(k\) constants”.
Principal components
In least squares regression, the springs are constrained to be vertical, because only the errors in \(y\) count. If, instead, the springs are attached perpendicular to the rod, and their feet are free to slide along it, they measure the perpendicular distances \(d_i\) of the points to the line. The rod then comes to rest where the potential energy, \(\frac{k}{2} \sum_i d_i^2\), is a minimum. The line that minimizes the sum of squared perpendicular distances is the first principal component, the major axis of the data ellipse.
At equilibrium the rod must pass through the centroid, \((\bar{x}, \bar{y})\), where the forces of the springs balance. If the rod makes an angle \(\theta\) with the \(x\) axis and \(p_i\) is the position of the foot of spring \(i\) along it, the springs exert a torque \(k \sum_i d_i \, p_i\) about the centroid. This is zero only when the rod lies along one of the eigenvectors of the covariance matrix; the rod is stable along the first and balanced only precariously along the second.
Figure 8 shows the rod released at an angle far from the
first principal component. The code for this is in examples/animate-pca.R in the package source.
Comparing this with Figure 5, the only difference is the direction of
the springs: vertical springs give the regression line; perpendicular springs give the principal axis.

Figure 8: Principal components by springs, animated. The rod (black) pivots about the centroid (white circle), pulled by springs perpendicular to it, and settles on the first principal component (dashed).