svglove-plot
Covariate balance (love plot)
After matching or weighting, are treated and control groups alike on every covariate?
How to read it
- Read each row as one covariate's imbalance: the standardized difference between groups.
- Hollow points are before adjustment, filled ones after.
- After adjustment, points should sit inside the threshold band.
- Callout 1: Before adjustment: imbalanced.
- Callout 2: After adjustment: balanced.
- 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
# 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 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("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)))
fig = go.Figure()
for j, st in enumerate(stages):
g = d[d["_stage"] == str(st)]
marker = dict(size=9, color="white", line=dict(color="grey", width=1.5)) if j == 0 else dict(size=9, color=PALETTE[(j - 1) % len(PALETTE)])
fig.add_scatter(x=g["shown"], y=g[COV].astype(str), mode="markers", name=st or "SMD", marker=marker)
for t in ([THRESHOLD] if ABSOLUTE else [-THRESHOLD, THRESHOLD]):
fig.add_vline(x=t, line=dict(color=REF, dash="dash", width=1))
fig.update_yaxes(categoryorder="array", categoryarray=order)
fig.update_layout(xaxis_title=("|" + SMD + "|") if ABSOLUTE else SMD, yaxis_title=None)
fig.show()Needs pandas, numpy, plotly · reads love-plot-demo.csv · app theme from the optional codesplash helper
# Covariate balance (love plot) — Codesplash Chart Lab (recipe "love-plot")
# controls: threshold=0.1, absolute=true
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("love-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["covariate"]] <- factor(df[["covariate"]])
df[["stage"]] <- factor(df[["stage"]], levels = c("Before", "Nearest-neighbour matching", "Entropy balancing"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
cov_col <- "covariate"
smd_col <- "standardized mean difference"
stage_col <- "stage"
threshold <- 0.1; absolute <- TRUE
d <- df[!is.na(df[[cov_col]]) & !is.na(df[[smd_col]]), ]
d$cov <- as.character(d[[cov_col]]); d$smd <- d[[smd_col]]
d$stage <- if (is.null(stage_col)) "SMD" else factor(as.character(d[[stage_col]]), levels = levels_of(d[[stage_col]]))
d$shown <- if (absolute) abs(d$smd) else d$smd
first <- d[as.character(d$stage) == levels(factor(d$stage))[1], ]
d$cov <- factor(d$cov, levels = unique(first$cov[order(abs(first$smd))])) # largest at the top
p <- ggplot(d, aes(shown, cov)) +
annotate("rect", xmin = if (absolute) 0 else -threshold, xmax = threshold, ymin = -Inf, ymax = Inf, fill = "#19966e", alpha = 0.08) +
geom_vline(xintercept = if (absolute) threshold else c(-threshold, threshold), colour = ref_col, linetype = "dashed") +
geom_line(aes(group = cov), colour = grey_col) +
geom_point(aes(colour = stage, shape = stage), size = 2.4) +
scale_colour_manual(values = c("grey40", cs_cat)) + scale_shape_manual(values = c(1, rep(16, 10))) +
labs(x = if (absolute) paste0("|", smd_col, "|") else smd_col, y = NULL, colour = NULL, shape = NULL) +
theme_cs
print(p)Needs ggplot2 · reads love-plot-demo.csv · app theme from the optional codesplashr helper