Skip to content
svgwithin-between

Within and between units

Does the relationship inside a unit point the same way as the relationship across units?

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

How to read it

  1. Read the dots as observations and the larger marks as each unit's mean.
  2. Compare the slopes: within units, between units and pooled.
  3. Slopes that disagree suggest unit-level differences are confounding the pooled estimate.

Watch out

  • The within slope removes stable differences between units, not those that change over time.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • The within slope regresses y on x after subtracting each unit's means: the fixed-effects coefficient without covariates.
  • The between slope is an unweighted regression on the unit means; the pooled slope ignores units.
  • All three lines pass through the grand means so their angles can be compared directly.

Use with care

When within and between slopes differ, pooled OLS mixes two different questions; only the within slope removes what stays constant inside a unit.

# Within and between units — Codesplash Chart Lab (recipe "within-between")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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"]

df = pd.read_csv("within-between-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

_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")
X = "training (hours/week)"
Y = "fitness score"
UNIT = "person"
KIND = None
d = df.dropna(subset=[X, Y])
means = d[d[KIND] == "unit mean"] if KIND else d.iloc[0:0]
obs = d[d[KIND] != "unit mean"] if KIND else d
def ls_slope(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    sxx = ((x - x.mean()) ** 2).sum()
    return ((x - x.mean()) * (y - y.mean())).sum() / sxx if len(x) > 1 and sxx > 1e-12 else None
within, between, pooled = None, None, None
if UNIT:
    grouped = obs.groupby(UNIT, observed=True)
    means = grouped[[X, Y]].mean().reset_index()
    wx, wy = obs[X] - grouped[X].transform("mean"), obs[Y] - grouped[Y].transform("mean")
    within = within if within is not None else ls_slope(wx, wy)
between = between if between is not None else ls_slope(means[X], means[Y])
pooled = pooled if pooled is not None else ls_slope(obs[X], obs[Y])
x_mean, y_mean = obs[X].mean(), obs[Y].mean()
span = np.array([min(obs[X].min(), means[X].min() if len(means) else obs[X].min()), max(obs[X].max(), means[X].max() if len(means) else obs[X].max())])
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(obs[X], obs[Y], s=8, alpha=0.35, color="#8a8f98")
for label, slope, colour, style in [("Within units", within, PALETTE[0], "-"), ("Between units", between, PALETTE[1], "-"), ("Pooled", pooled, REF, "--")]:
    if slope is not None:
        ax.plot(span, y_mean + slope * (span - x_mean), color=colour, linestyle=style, linewidth=2, label=f"{label}: slope {slope:.3g}")
ax.scatter(means[X], means[Y], s=36, color=PALETTE[1], edgecolor="white", linewidth=0.8, zorder=3)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Within and between units")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads within-between-demo.csv · app theme from the optional codesplash helper