October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Plot a Line of Best Fit in Python with Matplotlib

Use NumPy’s degree-one least-squares fit to estimate a slope and intercept, then plot the observations and fitted line together in Matplotlib.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Fit a straight line to paired numerical data with a degree-one least-squares fit, then draw the observations with scatter and the fitted values with plot. The example below uses NumPy and Matplotlib’s object-oriented Axes interface.

Fit and plot the line

Replace the sample arrays with your own paired observations: each x value must correspond to the y value at the same position.

import numpy as np
import matplotlib.pyplot as plt

# Replace these example arrays with paired observations.
x = np.array([1, 2, 3, 4, 5], dtype=float)
y = np.array([2.1, 2.9, 3.7, 4.2, 5.1], dtype=float)

# A degree-one polynomial is a straight line.
slope, intercept = np.polyfit(x, y, 1)

# Evaluate the fitted equation across the observed x range.
x_fit = np.linspace(x.min(), x.max(), 100)
y_fit = slope * x_fit + intercept

fig, ax = plt.subplots()
ax.scatter(x, y, label="Observed data")
ax.plot(x_fit, y_fit, color="crimson", label="Line of best fit")
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
ax.grid(True, alpha=0.3)
plt.show()

np.polyfit(x, y, 1) estimates the slope and intercept, returned in that order for this two-coefficient line. The fitted values follow y = slope * x + intercept. NumPy documents this least-squares polynomial fit in its polyfit reference.

The calculation and drawing are separate: first estimate the coefficients, then evaluate the equation at positions where you want to display the line. np.linspace supplies evenly spaced positions between the smallest and largest observed x values, so the line overlays the data range instead of joining observations in their original order.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why use scatter for points and plot for the fit?

ax.scatter(x, y) displays the observed pairs as individual points, while ax.plot(x_fit, y_fit) draws the computed line. Matplotlib’s scatter documentation describes plotting y versus x as a scatter plot; its plot reference covers coordinate plotting and line styling.

Labels and a legend distinguish the measurements from the model estimate. The Axes-based form shown above makes it explicit which plot receives each artist and is easier to extend when a figure has multiple axes. Matplotlib documents both the object-oriented and pyplot interfaces in its API reference; state-based calls such as plt.scatter(...) and plt.plot(...) can be convenient for brief interactive work.

Check the data and interpret the fit carefully

  • Use paired numerical data. The x and y arrays need compatible lengths, and values at matching positions must describe the same observations.
  • Check for variation in x. If every x value is identical, the slope cannot be meaningfully identified from those data.
  • Understand what is being minimized. This ordinary polynomial least-squares fit minimizes squared residuals in the response variable. It is not automatically robust to outliers or appropriate for every data-generating process.
  • Do not treat the overlay as proof. A plotted line alone does not establish that the relationship is truly linear or suitable for causal interpretation. Predictions beyond the observed x range are extrapolations and should be treated cautiously.

When to consider a different fitting API

np.polyfit is concise for an ordinary, well-scaled example. NumPy’s reference also discusses numerical conditioning and points readers toward Polynomial.fit for new code. If your values create numerical conditioning concerns, consult the NumPy documentation and choose the fitting representation deliberately rather than assuming the two interfaces behave identically in every numerical setting.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Customize the appearance

Change the color, linestyle, or linewidth passed to ax.plot to restyle the fitted line. Marker appearance is controlled separately through ax.scatter options. Matplotlib documents these controls in its plot and scatter references.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.