svgwithin-between
Within and between units
Does the relationship inside a unit point the same way as the relationship across units?
How to read it
- Read the dots as observations and the larger marks as each unit's mean.
- Compare the slopes: within units, between units and pooled.
- 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
# Within and between units — Codesplash Chart Lab (recipe "within-between")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure(go.Scatter(x=obs[X], y=obs[Y], mode="markers", name="observations", marker=dict(color="#8a8f98", size=5, opacity=0.4)))
for label, slope, colour, dash in [("Within units", within, PALETTE[0], "solid"), ("Between units", between, PALETTE[1], "solid"), ("Pooled", pooled, REF, "dash")]:
if slope is not None:
fig.add_scatter(x=span, y=y_mean + slope * (span - x_mean), mode="lines", name=f"{label}: slope {slope:.3g}", line=dict(color=colour, dash=dash, width=2))
fig.add_scatter(x=means[X], y=means[Y], mode="markers", name="unit means", marker=dict(color=PALETTE[1], size=9, line=dict(color="white", width=1)))
fig.update_layout(xaxis_title=X, yaxis_title=Y, title="Within and between units")
fig.show()Needs pandas, numpy, plotly · reads within-between-demo.csv · app theme from the optional codesplash helper
# Within and between units — Codesplash Chart Lab (recipe "within-between")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("within-between-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["person"]] <- factor(df[["person"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
x_col <- "training (hours/week)"
y_col <- "fitness score"
unit_col <- "person"
kind_col <- NULL
d <- data.frame(x = df[[x_col]], y = df[[y_col]])
is_mean <- if (!is.null(kind_col)) as.character(df[[kind_col]]) == "unit mean" else rep(FALSE, nrow(d))
if (!is.null(unit_col)) d$unit <- as.character(df[[unit_col]])
obs <- d[!is_mean & stats::complete.cases(d), , drop = FALSE]
means <- d[is_mean, , drop = FALSE]
ls_slope <- function(x, y) if (length(x) > 1 && sum((x - mean(x))^2) > 1e-12) sum((x - mean(x)) * (y - mean(y))) / sum((x - mean(x))^2) else NA_real_
within <- NA_real_; between <- NA_real_; pooled <- NA_real_
if (!is.null(unit_col)) {
means <- stats::aggregate(cbind(x, y) ~ unit, obs, mean)
if (is.na(within)) within <- ls_slope(obs$x - stats::ave(obs$x, obs$unit), obs$y - stats::ave(obs$y, obs$unit))
}
if (is.na(between)) between <- ls_slope(means$x, means$y)
if (is.na(pooled)) pooled <- ls_slope(obs$x, obs$y)
x_mean <- mean(obs$x); y_mean <- mean(obs$y)
lines <- data.frame(kind = c("Within units", "Between units", "Pooled"), slope = c(within, between, pooled))
lines <- lines[is.finite(lines$slope), ]
lines$intercept <- y_mean - lines$slope * x_mean
p <- ggplot(obs, aes(x, y)) +
geom_point(colour = "#8a8f98", alpha = 0.35, size = 0.9) +
geom_abline(data = lines, aes(slope = slope, intercept = intercept, colour = kind, linetype = kind), linewidth = 0.9) +
geom_point(data = means, aes(x, y), colour = cs_cat[2], size = 2.4) +
scale_colour_manual(values = c("Within units" = cs_cat[1], "Between units" = cs_cat[2], "Pooled" = ref_col), name = NULL) +
scale_linetype_manual(values = c("Within units" = "solid", "Between units" = "solid", "Pooled" = "dashed"), name = NULL) +
labs(x = x_col, y = y_col, title = "Within and between units") + theme_cs
print(p)Needs ggplot2 · reads within-between-demo.csv · app theme from the optional codesplashr helper