You find the equation of the line of best fit by computing the slope m = [nΣxy − (Σx)(Σy)] / [nΣx² − (Σx)²], then the intercept b = ȳ − m x̄, which gives ŷ = mx + b. This least-squares line passes through the point (x̄, ȳ) and minimizes the sum of squared vertical residuals. The formula works the same whether you're fitting a trendline in Excel, working a statistics problem by hand, or running a regression in Desmos — the steps below cover all three, plus what changes when your data has outliers or your line must be forced through the origin.
Gather Your Data and Count the Pairs Before You Compute Anything
Every least-squares calculation needs a clean table of paired values. Count your data points first — that count is n, and it appears in both the slope numerator and denominator. If n differs between your slope and intercept computations, you've already made an arithmetic error.
Write x and y in two columns, one row per pair. Keep the original units (dollars, minutes, degrees) but compute in plain numbers. A pair with a missing x or y isn't a data point — drop the whole row rather than substituting zero, since a zero substitution drags the regression line toward the origin and inflates the slope.
For a typical stats exercise (like the classic "hours studied vs. exam score" problem), you'll see n = 5 to n = 8 pairs. Real data from a spreadsheet might be n = 30 or n = 300. The formula doesn't care about size, but hand computation becomes punishing past about n = 10 — switch to a calculator or software once you pass that threshold.
One check worth doing before you start: scatterplot the points. If they follow a curve (a U-shape, an S-curve, an exponential climb), a straight line of best fit will be a poor description no matter how carefully you compute it. The equation will still exist; it just won't mean what you think it means.
Lay Out the Five Sums That Feed the Slope Formula
Least squares needs five totals: Σx, Σy, Σxy, Σx², and Σy². Build them in a working table alongside your raw data so each row contributes to every sum at once. Skipping Σy² is fine if you only need the equation, but you'll want it later if you're also computing r² or the correlation coefficient.
Here's a worked table for a small dataset — hours studied (x) against exam score (y) for five students:
| x (hours) | y (score) | xy | x² | y² |
|---|---|---|---|---|
| 1 | 55 | 55 | 1 | 3,025 |
| 2 | 62 | 124 | 4 | 3,844 |
| 3 | 68 | 204 | 9 | 4,624 |
| 4 | 75 | 300 | 16 | 5,625 |
| 5 | 82 | 410 | 25 | 6,724 |
| Σx = 15 | Σy = 342 | Σxy = 1,093 | Σx² = 55 | Σy² = 23,842 |
Verify each column sums independently before moving on. A single transcription slip in one cell propagates into the slope and intercept, and the resulting line will look "off" without any obvious cause. Recount the Σxy column against the individual products — that's where typos cluster.
If you're doing this in a spreadsheet, put the sums in named cells and reference them in your slope formula rather than retyping numbers. That way, editing one data point updates the entire equation and you can see the line move in real time.
Compute the Slope First, Then the Intercept From the Means
Plug your five sums into the slope formula: m = [nΣxy − (Σx)(Σy)] / [nΣx² − (Σx)²]. With n = 5 and the totals above, the numerator is 5(1,093) − (15)(342) = 5,465 − 5,130 = 335. The denominator is 5(55) − 15² = 275 − 225 = 50. So m = 335 / 50 = 6.7.
Now compute the means: x̄ = 15/5 = 3 and ȳ = 342/5 = 68.4. The intercept is b = ȳ − m x̄ = 68.4 − (6.7)(3) = 68.4 − 20.1 = 48.3. The line of best fit is ŷ = 6.7x + 48.3.
Interpret it in context: each additional hour of study is associated with a 6.7-point score increase, and a student who studied zero hours is predicted to score 48.3. The intercept is a modeling anchor, not necessarily a real prediction — if nobody in your data studied zero hours, treat b as an extrapolation.
Sanity-check the sign of m. If your scatterplot trends upward but m comes out negative, you've almost certainly swapped the numerator or flipped a subtraction. Similarly, if m is absurdly large (say, in the hundreds when your y values range over 50 points), suspect a wrong Σx² entry.
Read the Equation Off Excel, Google Sheets, or Desmos Without Doing the Algebra
Spreadsheet trendlines do the arithmetic for you, but you have to switch the equation display on — it's off by default, and most people miss it. The steps below work in Excel for Microsoft 365, Excel 2021, and Google Sheets; menu labels are near-identical across both.
1: Select your two columns of data (x on the left, y on the right). 2: Insert → Scatter chart, choosing the plain markers-only style. 3: Click any data point to select the series, then right-click and choose Add Trendline. 4: In the Format Trendline pane, select Linear. 5: Tick Display Equation on chart and, optionally, Display R-squared value on chart. 6: Read the equation off the chart in the form y = mx + b (Excel writes it as y = 6.7x + 48.3).
In Google Sheets the path is Chart editor → Customize → Series → Trendline, with a checkbox labeled "Show equation." In Desmos, type your data as a table, then enter y_1 ~ mx_1 + b — Desmos returns m and b automatically with uncertainty estimates.
If the equation box doesn't appear, the usual culprits are: a non-numeric column (numbers stored as text), blank cells treated as zeros, or a chart type that isn't a true scatter (a "line chart" with categories won't fit a trendline). Fix the data type first, then re-add the trendline.
Force the Line Through the Origin Only When Zero Must Mean Zero
Setting the intercept to zero (b = 0) is a stronger claim than "the data starts near zero." It says that at x = 0, ŷ must equal 0 exactly — which is appropriate when you're modeling something like distance traveled over time where zero time genuinely means zero distance, or cost proportional to quantity with no fixed overhead.
In Excel, tick Set Intercept = 0.0 in the Trendline options. The formula then becomes ŷ = mx, and m reduces to Σxy / Σx². In the worked dataset above, forcing b = 0 gives m = 1,093/55 ≈ 19.87 — dramatically different from 6.7, and a clear signal that zero-intercept fitting distorts the trend if a real intercept exists.
The Excel documentation warns that forcing the intercept to zero makes R² unreliable, because the standard R² formula assumes a computed intercept. So if you force b = 0, report the fit quality with caution or use a different goodness-of-fit measure. The equation is still valid for prediction within your data range; the R² figure just isn't comparable to a free-intercept fit.
The most common mistake here: students force the intercept to zero because "the graph should start at zero." That's a graphing convention, not a statistical claim. Unless the physical model genuinely requires ŷ = 0 at x = 0, leave the intercept free.
Watch for Outliers, Curved Data, and the Intercept Trap That Skews Predictions
A single extreme point can swing the slope dramatically under least squares, because each residual is squared and a point far from the line dominates the sum. In a dataset of 10 points clustered around (5, 50), one point at (20, 200) can pull the slope upward by several units. Always inspect a scatterplot before trusting the equation.
If you spot an outlier, check whether it's a data-entry error first (a misplaced decimal, a typo). If it's a genuine observation, either keep it and acknowledge the fit is influenced by it, or fit again without it and compare the two equations. Reported regressions in real studies often show both.
Curved data is the second trap. If the scatterplot bends, a linear fit misleads. Excel's trendline offers polynomial and exponential options for a reason; the equation box updates to show that model instead. A linear line of best fit through curved data will systematically under-predict near the bend and over-predict at the tails.
The intercept trap: b has units of y and represents the predicted y when x = 0, even if x never reaches 0. For a regression of salary on years of experience where the youngest worker has three years, b is a hypothetical starting salary, not an observed one. Reporting it as fact without that caveat is a common error in student write-ups.
Know When a Hand-Computed Line Beats the Software Result
For a statistics class, hand computation is often required — the point is the method, and grading depends on showing the sums. For work where accuracy matters (forecasting, quality control, medical trending), use the software. Two reasons: floating-point precision and reproducibility.
Hand computation can diverge from Excel by small amounts due to rounding of intermediate sums. If your hand-computed slope is 6.7 and Excel returns 6.7032, you didn't make a mistake — you rounded prematurely. Carry at least four decimal places through the intercept calculation, then round the final equation to the precision your audience needs.
Compare the cases in this table before choosing a tool:
| Situation | Method worth using | Why |
|---|---|---|
| Stats homework, n ≤ 10 | Paper + calculator | Shows the sums required for full credit |
| Course project, n = 20+ | Excel or Google Sheets | Fast, reproducible, chart included |
| Interpolation on a curve | Desmos y_1 ~ mx_1 + b | Auto-adjusted fit with uncertainty |
| Forced origin fit | Excel "Set Intercept = 0.0" | Handles b = 0 correctly with a warning about R² |
| Reporting to a client | Software + rounded equation | Publication-ready within 2 decimal places |
For graded work where you need to show your reasoning, do it by hand and check against Excel to spot errors. For anything operational, trust the tool and record the dataset version so the equation can be regenerated.
Verify Your Equation Before You Report It — Three Checks That Catch Most Errors
The first check: plot the line on the scatterplot and confirm it passes through the middle of the cloud. Least squares minimizes squared vertical distance, so the line should split the points roughly evenly above and below. If most points sit on one side, something's wrong with the arithmetic.
The second check: verify the line passes through (x̄, ȳ), the mean point. This is a built-in property of least squares — if it doesn't, either the slope or intercept is off. For the worked example, (3, 68.4) must satisfy ŷ = 6.7(3) + 48.3 = 68.4. ✓
The third check: compute one residual by hand. Take a point in the middle of the data range, plug its x into the equation, and compare the predicted ŷ to the actual y. For x = 3, ŷ = 68.4, and the observed y is 68 — a residual of −0.4. If your residual for a mid-range point exceeds a few percent of the y-range, suspect a summing error.
The r² value from Excel's trendline box tells you what fraction of variance in y is explained by x. For the worked example, r² ≈ 0.998 — a near-perfect linear fit, which is unusual in real data and often a sign that the dataset is small or synthetic. Anything above 0.95 on real data warrants a second look to make sure you haven't dropped rows.
FAQ
What does the line of best fit equation actually minimize?
It minimizes the sum of squared vertical residuals — the squared differences between each observed y and the y the line predicts at that x. Squaring doubles down on large misses, which is why a single outlier can swing the slope. Horizontal distance is never what's minimized in ordinary least squares; if you need that, look into orthogonal regression instead, which fits a different line.
Why does my hand-computed slope differ slightly from Excel's?
Rounding is almost always the cause. Excel carries roughly 15 significant digits through the calculation, while hand work rounds intermediate sums to two or three decimals. Carry four decimals through Σxy, Σx², and Σy², calculate m, then round the final equation to two decimals — the mismatch will usually drop below 0.01.
Can b (the intercept) ever be negative, and is that a problem?
Yes, and no — a negative intercept isn't an error by itself. It means the model predicts a negative y when x = 0. That's fine if x = 0 is outside the data range or if a negative y is physically plausible in context (a business loss, a temperature below zero). It's problematic only when it contradicts the units of the problem, such as a negative predicted population.
Should I report R² with my equation, or is the equation enough?
Report R² whenever you're making claims about fit quality, since the equation alone doesn't tell you how well the line describes the data. An r² of 0.4 and an r² of 0.95 imply very different confidence in the model. If you forced the intercept through zero, flag that Excel's R² becomes unreliable in that mode and interpret the fit with more caution.
What if my data has a point that drags the line way off?
That point is an outlier, and it deserves inspection before you average it into the fit. Check for data-entry errors first; if the point is genuine, fit twice — once with and once without it — and report both slopes. The difference between the two slopes quantifies how much influence that one point has on the model.
How do I write the equation in the y = mx + b format if a tool shows it differently?
Excel may write "y = 6.7x + 48.3," Desmos may return "m = 6.7, b = 48.3," and some stats software returns slope and intercept in separate fields. All are the same equation. Just reorder into y = mx + b, rename m and b to slope and intercept if your audience expects those terms, and confirm the sign on b — negative intercepts are written with a minus sign, not hidden in a subtraction.
Do I need Σy² if I only want the equation of the line of best fit?
No. Σy² is only needed if you're computing r², the correlation coefficient, or the standard error of the estimate. For the slope and intercept, the four sums Σx, Σy, Σxy, and Σx² are sufficient. You can add Σy² later if your instructor or client asks for fit quality, and the equation itself won't change.