Plot guides › Chart types

Scatter plot with a regression line

A fitted line on top of a scatter plot summarises the relationship in one slope and intercept. Showing R² in the corner tells the reader how much of the spread the line explains.

Example scatter plot with a regression line made with matplotlib
Rendered from the code below, with example data.

When to use it

Watch out: Don't fit a straight line to an obviously curved relationship. Fit the right model or transform an axis first.

Ask for it in pltchat

Upload your file and type something like:

"scatter of height vs weight with a linear fit, show the equation and R²"

pltchat writes the loader and the plot for your columns, runs it in your browser and shows you the code.

The matplotlib code

Self-contained with example data; swap in pd.read_csv(...) or pd.read_excel(...) for your own file.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
x = rng.uniform(150, 195, 80)                  # height (cm)
y = 0.9 * x - 85 + rng.normal(0, 7, x.size)    # weight (kg)

slope, intercept = np.polyfit(x, y, 1)
r2 = np.corrcoef(x, y)[0, 1] ** 2

fig, ax = plt.subplots(figsize=(6.4, 4))
ax.scatter(x, y, s=20, alpha=0.7)
xs = np.linspace(x.min(), x.max(), 100)
ax.plot(xs, slope * xs + intercept, color="C1", lw=2)
ax.text(0.04, 0.95, f"y = {slope:.2f}x {intercept:+.1f}\nR² = {r2:.2f}",
        transform=ax.transAxes, va="top")
ax.set_xlabel("Height (cm)")
ax.set_ylabel("Weight (kg)")
plt.tight_layout()
plt.show()

Make this with your data

Upload a CSV, Excel, JSON or Parquet file. Your first plot is always free.

Related plots