Statistics & Probability • Two-Variable Data

Fitting a Linear Function to a Scatter Plot

Transform a cloud of data points into a predictive equation that reveals hidden relationships between two variables.

Historical Context & Motivation

Long before computers could crunch millions of data points in seconds, scientists and statisticians wrestled with a fundamental question: how do you summarize a relationship between two measurements using a single, clean equation? Scatter plots — grids of dots representing paired observations — made patterns visible, but translating those patterns into actionable predictions required a mathematical tool that was both rigorous and simple enough to use by hand.

The quest to fit lines through data has a surprisingly rich history, driven by astronomers who needed precise planetary orbits, economists who wanted to forecast markets, and biologists charting growth rates. Each breakthrough gave us better ways to draw the "best" line through imperfect, noisy data.

1805
Adrien-Marie Legendre, a French mathematician, published the method of least squares in his work on determining comet orbits. He proposed choosing the line that minimizes the sum of squared vertical distances between each data point and the line — the exact method still used today.
1809
Carl Friedrich Gauss independently developed the least-squares method and demonstrated its deep connection to the normal distribution. Gauss showed that if measurement errors follow a bell curve, least squares produces the most probable estimate of the true relationship.
1885
Francis Galton introduced the concept of regression toward the mean while studying the heights of parents and children. He noticed that very tall parents tended to have children slightly shorter than themselves, and very short parents tended to have slightly taller children. His work gave us the word "regression" — and scatter plots became a standard visualization tool.
1896
Karl Pearson formalized the correlation coefficient (r), providing a single number that quantifies the strength and direction of a linear relationship. This metric became the natural companion to the best-fit line, letting analysts judge how well the line actually fits the data.
Modern Era
With computing power, linear regression expanded into multiple regression, machine learning, and big-data analytics. Yet the core idea — fitting a straight line through a scatter plot — remains one of the most widely used techniques in science, business, medicine, and everyday decision-making.

Understanding how to fit a linear function to a scatter plot is not just a Common Core requirement; it is the gateway to every data-driven field you might encounter in college and beyond. The question this lesson addresses is precise: given a collection of (x, y) data pairs that appear to follow a roughly straight-line pattern, how do you find the equation of the line that best represents that pattern, and what does that equation tell you?

Core Principles & Definitions

Before you can fit a line, you need to understand what you are looking at and what "fit" actually means. The following four foundational ideas form the conceptual backbone of this lesson.

1

Scatter Plot

A graph that places one variable along the horizontal axis (x, the explanatory variable) and another along the vertical axis (y, the response variable). Each data pair becomes a dot. The resulting cloud of dots can reveal patterns — or the lack thereof.
2

Linear Association

When the dots in a scatter plot tend to cluster around a straight line — rising, falling, or flat — we say the data show a linear association. The association can be positive (up-right), negative (down-right), or near-zero (no clear trend).
3

Line of Best Fit

A straight line drawn through the scatter plot that comes as close as possible to all the data points simultaneously. It is also called the least-squares regression line or the trend line. Its equation has the form ŷ = mx + b.
4

Residual

The vertical distance between an actual data point and the predicted value on the line: residual = y − ŷ. Positive residuals lie above the line; negative ones below. The least-squares line minimizes the sum of the squared residuals.
Key Takeaway
Think of fitting a line like adjusting a ruler on a tilted stack of textbooks. You can tilt the ruler at many angles, but only one angle minimizes the total gap between the ruler and every book in the stack. The least-squares regression line is that optimal tilt — it balances all the misses above and below so that the overall "miss" (measured by squared distances) is as small as it can possibly be.

Visual Explanation

The diagram below shows a scatter plot with ten data points and the least-squares regression line drawn through them. Notice how the line does not pass through every point — that would be impossible with real-world data — but it threads through the middle of the cloud so that the points above the line and the points below roughly balance each other out.

Scatter plot with 10 data points, the best-fit line ŷ = 3.5x + 38, and selected residual segments.

In the diagram, the cyan line is the regression line ŷ = 3.5x + 38, and the pink dashed segments are residuals — the vertical gaps between selected data points and the line. Some points sit above the line (positive residuals), while others sit below (negative residuals). The least-squares method ensures that when you square each of these pink segments and add them all together, the total is smaller than it would be for any other line you could draw.

The violet dots represent paired observations — in this example, hours of study per week versus exam score. Notice the general upward trend: as study hours increase, exam scores tend to increase as well. This upward drift is precisely the positive linear association that justifies fitting a line rather than, say, a curve.

Mathematical Framework

The equation of any non-vertical line can be written in slope-intercept form. When we use it as a prediction tool, we write it with a "hat" on the y to indicate that ŷ is a predicted value, not an observed one.

Regression Line Equation
ŷ = mx + b
m = slope (rate of change in y per unit increase in x), b = y-intercept (predicted y when x = 0)

The slope m tells you the direction and steepness of the relationship. A positive slope means that as x increases, y tends to increase; a negative slope means y tends to decrease. The y-intercept b gives you the starting value of ŷ when x equals zero — though be careful, because x = 0 may lie outside the range of your data, making the intercept mathematically real but practically meaningless.

To calculate the slope and intercept using the least-squares formulas, you need the means and standard deviations of both variables, along with their correlation coefficient. The formulas below assume you have n data pairs (x₁, y₁), (x₂, y₂), …, (xₙ, yₙ).

Slope Formula
m = r × (sᵧ / sₓ)
r = correlation coefficient, sy = standard deviation of y, sx = standard deviation of x
Intercept Formula
b = ȳ − m × x̄
ȳ = mean of y-values, x̄ = mean of x-values

There is also a "raw-data" version of the slope formula that works directly from sums rather than from r, sx, and sy. Both formulas give the same answer; which one you use depends on what information you have handy.

Alternative Slope (from raw sums)
m = [n∑xᵢyᵢ − (∑xᵢ)(∑yᵢ)] / [n∑xᵢ² − (∑xᵢ)²]
All sums run from i = 1 to n

A critical property of the least-squares line is that it always passes through the point (x̄, ȳ). This means the line goes right through the "center of mass" of the data cloud. When you're sketching a best-fit line by hand, plotting (x̄, ȳ) and then adjusting the slope is a reliable approach.

Key Takeaway
The formulas may look dense, but here is the intuition: the slope is really just the correlation coefficient scaled by how spread out y is relative to x. If y varies a lot compared to x, the line will be steep. If y barely varies, the line will be nearly flat. The correlation tells you how much of that variation actually follows a straight-line pattern — and its sign (positive or negative) determines which way the line tilts.

Residuals & Evaluating the Fit

Drawing the line is only half the job. You also need to judge how well the line captures the data's behavior. The primary tool for this assessment is the residual plot, which graphs each residual (y − ŷ) against the corresponding x-value. If your linear model is appropriate, the residual plot should show a random scatter of points with no obvious pattern — no curves, no fans, no clusters.

Residual plot showing random scatter around the zero line, confirming a good linear fit.

In the residual plot above, the dots bounce above and below the dashed zero line without any curved pattern. This randomness is a good sign — it confirms that a linear model is appropriate for this data set. If you instead saw a U-shape or an arching pattern in the residuals, that would signal that a curve (not a line) better describes the data.

Another way to evaluate fit is the coefficient of determination, denoted . It tells you the proportion of the total variation in y that is explained by the linear relationship with x. For example, if r² = 0.85, then 85% of the variation in exam scores can be accounted for by the variation in study hours; the remaining 15% is due to other factors or random noise.

Coefficient of Determination
r² = (correlation coefficient)²
Ranges from 0 (no linear fit) to 1 (perfect linear fit)

When reporting your regression results, it is good practice to state: (1) the equation ŷ = mx + b, (2) the value of r or r², and (3) the context — what x and y represent, what units they carry, and over what range of x the model is trustworthy. Predicting y for an x-value far outside your data range is called extrapolation, and it is risky because you have no evidence the linear pattern continues that far.

Worked Example

Let's work through a complete problem, from raw data to a finished regression equation and a prediction.

Problem: A teacher records the number of absences and final exam scores for eight students. Find the least-squares regression line and predict the exam score for a student with 6 absences.

StudentAbsences (x)Exam Score (y)
A194
B288
C385
D480
E578
F770
G865
H1055
Finding the Least-Squares Regression Line
1
Step 1 — Compute the means x̄ and ȳSum of x-values: 1 + 2 + 3 + 4 + 5 + 7 + 8 + 10 = 40 Sum of y-values: 94 + 88 + 85 + 80 + 78 + 70 + 65 + 55 = 615
n = 8, so x̄ = 40 / 8 = 5 and ȳ = 615 / 8 = 76.875.
2
Step 2 — Compute the required sums for the slope formulaWe need ∑xiyi and ∑xi². ∑xᵢyᵢ = (1)(94) + (2)(88) + (3)(85) + (4)(80) + (5)(78) + (7)(70) + (8)(65) + (10)(55) = 94 + 176 + 255 + 320 + 390 + 490 + 520 + 550 = 2795 ∑xᵢ² = 1 + 4 + 9 + 16 + 25 + 49 + 64 + 100 = 268
3
Step 3 — Calculate the slope mUsing the raw-sums formula: m = [n∑xᵢyᵢ − (∑xᵢ)(∑yᵢ)] / [n∑xᵢ² − (∑xᵢ)²] = [8(2795) − (40)(615)] / [8(268) − (40)²] = [22360 − 24600] / [2144 − 1600] = −2240 / 544 ≈ −4.118
4
Step 4 — Calculate the y-intercept bb = ȳ − m × x̄ = 76.875 − (−4.118)(5) = 76.875 + 20.59 ≈ 97.465
5
Step 5 — Write the regression equationŷ = −4.12x + 97.47 Interpretation: for each additional absence, the model predicts a decrease of about 4.12 points on the final exam. The y-intercept of 97.47 represents the predicted score for a student with zero absences.
6
Step 6 — Predict the score for x = 6ŷ = −4.12(6) + 97.47 = −24.72 + 97.47 = 72.75
According to our model, a student with 6 absences would be expected to score approximately 72.75 on the final exam. Since 6 is within the range of our data (1 to 10), this is an interpolation and a reasonable prediction.

Strengths, Limitations, & Common Pitfalls

The least-squares regression line is an extraordinarily useful tool, but it has boundaries. Understanding where it excels and where it fails will make you a more thoughtful data analyst.

StrengthsLimitations
Simple to compute and easy to interpret — the slope and intercept have clear real-world meanings.Only captures linear relationships. If the true pattern is curved, the line will be misleading.
Unique: for any data set there is exactly one least-squares line, so results are reproducible.Sensitive to outliers. A single extreme point can dramatically pull the line away from the majority of data.
Provides a basis for prediction and for quantifying the strength of a relationship (via r²).Correlation does not imply causation. A strong line does not prove that x causes y.
The residual plot gives a clear diagnostic for whether the linear model is appropriate.Extrapolation beyond the observed data range is unreliable and can produce absurd predictions.
Key Takeaway
Think of the regression line as a GPS route: it is accurate and reliable on roads you have already mapped (the data range), but if you drive off the edge of the map (extrapolation), the GPS is just guessing. And just because two variables travel in the same direction does not mean one is steering the other — ice cream sales and sunburn rates both rise in summer, but buying ice cream does not cause sunburn. Always look at context before claiming causation.

Connection to Advanced Theory

The simple line you have learned to fit in this lesson is the starting point for a much larger family of models. In college-level statistics and data science courses, you will encounter extensions that handle more complex situations while still building on the same least-squares idea.

This LessonWhat Comes Next
One explanatory variable (simple linear regression)Multiple regression: two or more explanatory variables predict y simultaneously (e.g., predicting exam score from both study hours and sleep hours).
Line (ŷ = mx + b)Polynomial and nonlinear regression: curves such as quadratics, exponentials, and logarithmic models fit data that curves rather than following a straight path.
r² as a measure of fitAdjusted r² and residual standard error: more nuanced measures that account for the number of predictors and provide uncertainty intervals around predictions.
Eyeballing whether a line is appropriateHypothesis testing on slope: formal tests (t-tests) determine whether the slope is statistically significantly different from zero, ensuring the apparent trend is not just noise.

Even in advanced machine learning, where algorithms like neural networks and random forests dominate, linear regression is frequently used as a baseline model — the simplest explanation against which fancier methods are compared. Mastering it now gives you a conceptual anchor that will serve you throughout any quantitative career path.

Practice Problems

PROBLEM 1CONCEPTUAL
A scatter plot of daily temperature (°F) versus number of hot chocolates sold at a café shows a downward trend from left to right. The correlation coefficient is r = −0.89. Explain in your own words what this tells you about the relationship, and state whether a linear model is likely appropriate.
PROBLEM 2BASIC CALCULATION
Given x̄ = 12, ȳ = 45, sx = 4, sy = 10, and r = 0.80, find the equation of the least-squares regression line.
PROBLEM 3INTERMEDIATE
Five data points are given: (2, 10), (4, 18), (6, 24), (8, 34), (10, 40). Use the raw-sums slope formula to find the least-squares regression line, then predict ŷ when x = 7.
PROBLEM 4APPLIED / MULTI-STEP
A city transportation department collected data on the number of bike lanes (x) and the annual number of cycling commuters (in thousands, y) across 6 districts: (3, 1.8), (5, 2.9), (7, 4.1), (9, 5.5), (11, 6.2), (14, 8.0). Find the regression line, calculate r², and use the line to estimate how many cycling commuters a district with 10 bike lanes would have. Discuss whether this estimate is reliable.
PROBLEM 5CRITICAL THINKING / SYNTHESIS
A student fits a regression line to a data set of hours of television watched per day (x) versus GPA (y) and obtains ŷ = −0.15x + 3.8 with r² = 0.42. They conclude: "Watching TV causes GPA to drop. If a student stops watching TV entirely, their GPA will be 3.8." Identify two distinct errors in this reasoning and explain why each is problematic.

Lesson Summary

When a scatter plot of two-variable data shows a roughly straight-line pattern, we can fit a least-squares regression line of the form ŷ = mx + b. The slope m describes the rate at which the response variable changes per unit increase in the explanatory variable, while the y-intercept b gives the predicted response when the explanatory variable equals zero. The slope is calculated as m = r × (sᵧ / sₓ), and the line always passes through the point (x̄, ȳ), anchoring it to the center of the data.

To evaluate whether the line is a good fit, examine the residual plot for random scatter (no curves or patterns) and check the coefficient of determination r², which measures the proportion of variability in y explained by x. A strong fit does not imply causation — always consider lurking variables and context. Predictions are most trustworthy within the range of observed data (interpolation) and become unreliable outside it (extrapolation). Mastering this skill connects you to the broader world of multiple regression, nonlinear modeling, and data science.

Varsity Tutors • Statistics & Probability (Common Core) • Fitting a Linear Function to a Scatter Plot