Skip to content
svgbrushablescatter

Scatter plot

How do two numeric variables move together?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the overall direction: rising, falling or flat.
  2. Read how tightly the points follow the fit line, and whether the fit should be straight at all.
  3. Look for points far from the rest and for groups that behave differently.
  1. Callout 1: The fit line: the average trend, with its band.
  2. Callout 2: A cloud of one group: does the trend hold inside each group?
  3. Callout 3: Points far from the rest: check them before fitting.

Watch out

  • A strong pattern does not show that one variable causes the other.
  • A trend across groups can reverse inside them (Simpson's paradox).

Defaults

Fit
OLS + 95% CI
Add a straight-line (OLS) or flexible (LOESS) trend line.
Also: None · LOESS
LOESS span
0.75
The share of points in each local fit: smaller follows the data closely, larger is smoother.
Range 0.2 to 1, step 0.05
Point radius
3
The size of each point.
Range 1 to 6, step 0.5
Opacity
0.7
How see-through points are; lower reveals density in crowded areas.
Range 0.1 to 1, step 0.1
Renderer
Auto (canvas > 5,000)
Draw as vector shapes or to a canvas; canvas stays fast with many points.
Also: SVG · Canvas

Pinned in the code

  • OLS: ŷ = a + b·x by least squares; the band is the 95 % confidence interval of the mean, ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx).
  • LOESS: local linear fits with tricube weights over the nearest span·n points (degree 1, no robustness iterations; R `loess(degree = 1, family = "gaussian")`).
  • Rows with a missing x or y are dropped.
# Scatter plot — Codesplash Chart Lab (recipe "scatter")
# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from statsmodels.nonparametric.smoothers_lowess import lowess
import matplotlib.dates as mdates

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("scatter-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def ols_band(x, y, level=0.95, points=60):
    """y = a + b·x with the pointwise CI of the mean: ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx)."""
    n, mx = x.size, x.mean()
    sxx = ((x - mx) ** 2).sum()
    b = ((x - mx) * (y - y.mean())).sum() / sxx
    a = y.mean() - b * mx
    s = np.sqrt(((y - a - b * x) ** 2).sum() / (n - 2))
    grid = np.linspace(x.min(), x.max(), points)
    fit = a + b * grid
    half = stats.t.ppf(1 - (1 - level) / 2, n - 2) * s * np.sqrt(1 / n + (grid - mx) ** 2 / sxx)
    return grid, fit, fit - half, fit + half, a, b
def loess_curve(x, y, span, points=60):
    """Local linear fits, tricube weights over the floor(span·n) nearest points, no robustness
    iterations — R loess(degree = 1, family = "gaussian", surface = "direct")."""
    grid = np.linspace(x.min(), x.max(), points)
    return grid, lowess(y, x, frac=span, it=0, delta=0.0, xvals=grid)

d = df.dropna(subset=["spend_k", "revenue_k"])  # rows with a missing x or y are dropped
xv = d["spend_k"].to_numpy(dtype=float)
yv = d["revenue_k"].to_numpy(dtype=float)

fig, ax = plt.subplots(figsize=(7, 4.5))
for i, lv in enumerate(freq_levels(d["segment"])):
    m = (d["segment"].astype(str) == lv).to_numpy()
    ax.scatter(xv[m], yv[m], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=lv, s=20.25, alpha=0.7, edgecolors="none")  # marker shape per group, as in the app
ax.legend(title="segment", fontsize=8)
grid, fit, lo, hi, a, b = ols_band(xv, yv)
ax.fill_between(grid, lo, hi, color=REF, alpha=0.15, linewidth=0, label="95% CI")
ax.plot(grid, fit, color=REF, linewidth=2, label=f"OLS: y = {a:.3g} + {b:.3g}·x")
ax.set_xlabel("spend_k")
ax.set_ylabel("revenue_k")
plt.show()

Needs pandas, numpy, matplotlib, scipy, statsmodels · reads scatter-demo.csv · app theme from the optional codesplash helper