Skip to content
svglove-plot

Covariate balance (love plot)

After matching or weighting, are treated and control groups alike on every covariate?

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

How to read it

  1. Read each row as one covariate's imbalance: the standardized difference between groups.
  2. Hollow points are before adjustment, filled ones after.
  3. After adjustment, points should sit inside the threshold band.
  1. Callout 1: Before adjustment: imbalanced.
  2. Callout 2: After adjustment: balanced.
  3. Callout 3: The threshold band.

Watch out

  • Balance on measured covariates says nothing about unmeasured ones.

Defaults

Balance threshold
0.1
The standardized difference below which a covariate counts as balanced; 0.1 is a common choice.
Range 0.01 to 1, step 0.01
Absolute differences
On
Plot the size of each imbalance, ignoring its sign.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Covariates are sorted by |SMD| in the first stage (largest at the top); the first stage is drawn hollow, later stages filled and joined by a grey line per covariate.
  • The shaded region is |SMD| ≤ threshold (0.1 by convention; Austin 2009). Binary covariates use the raw difference in proportions when the engine follows cobalt's convention.
# Covariate balance (love plot) — Codesplash Chart Lab (recipe "love-plot")
# controls: threshold=0.1, absolute=true
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("love-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["stage"] = pd.Categorical(df["stage"].astype("string"), categories=["Before", "Nearest-neighbour matching", "Entropy balancing"])

_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 levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
COV = "covariate"
SMD = "standardized mean difference"
STAGE = "stage"
THRESHOLD, ABSOLUTE = 0.1, True
d = df.dropna(subset=[COV, SMD]).copy()
d["shown"] = d[SMD].abs() if ABSOLUTE else d[SMD]
stages = levels_of(d[STAGE]) if STAGE else [""]
d["_stage"] = d[STAGE].astype(str) if STAGE else ""
first = d[d["_stage"] == str(stages[0])].assign(a=lambda t: t[SMD].abs()).sort_values("a")
order = list(dict.fromkeys(first[COV].astype(str))) + [v for v in d[COV].astype(str).unique() if v not in set(first[COV].astype(str))]
ypos = {v: i for i, v in enumerate(order)}  # largest first-stage |SMD| at the top
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axvspan(0 if ABSOLUTE else -THRESHOLD, THRESHOLD, color="#19966e", alpha=0.08, lw=0)
for t in ([THRESHOLD] if ABSOLUTE else [-THRESHOLD, THRESHOLD]):
    ax.axvline(t, color=REF, linestyle="--", linewidth=1)
for cov, g in d.groupby(COV, observed=True):
    ax.plot(g["shown"], [ypos[str(cov)]] * len(g), color=GREY, linewidth=1.2, zorder=1)
for j, st in enumerate(stages):
    g = d[d["_stage"] == str(st)]
    ys = [ypos[str(v)] for v in g[COV]]
    if j == 0:
        ax.scatter(g["shown"], ys, s=34, facecolors="none", edgecolors="grey", label=st or "SMD", zorder=2)
    else:
        ax.scatter(g["shown"], ys, s=30, color=PALETTE[(j - 1) % len(PALETTE)], label=st, zorder=3)
ax.set_yticks(range(len(order)), order)
ax.set_xlabel(("|" + SMD + "|") if ABSOLUTE else SMD)
ax.legend(fontsize=8, loc="lower right")
plt.show()

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