svgoverlap-density
Propensity score overlap
Do treated and control units share a range of propensity scores (overlap / positivity)?
How to read it
- Read the top and bottom histograms as each group's propensity scores.
- Check that they cover the same range: that's the shaded common support.
- Compare the outline after weighting.
- Callout 1: Treated units.
- Callout 2: Control units.
- Callout 3: The common-support region.
Watch out
- Few controls at high propensity scores makes results depend on extreme weights.
Defaults
- Mirror the second group
- On
- Flip the second group below the axis, so shapes can be compared.
- Bins
- 25
- How many bins to divide the range into.
- Range 5 to 80, step 1
Pinned in the code
- Draws the scores the engine estimated; the chart bins them on shared edges ([0, 1] when every score lies in it) and scales each group to a density.
- Common support = [max of the group minimums, min of the group maximums]; little mass outside it means weights and matches rely less on extrapolation.
- With a weight role, the outlines are the weighted densities (e.g. ATT or overlap weights) on the same bins.
# Propensity score overlap — Codesplash Chart Lab (recipe "overlap-density")
# controls: mirrored=true, bins=25
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("overlap-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["treated", "control"])
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)))
S = "propensity score"
G = "group"
W = "ATT weight"
BINS, MIRRORED = 25, True
d = df.dropna(subset=[S, G])
groups = levels_of(d[G].astype(str))[:2]
lo, hi = (0, 1) if d[S].between(0, 1).all() else (d[S].min(), d[S].max())
edges = np.linspace(lo, hi, BINS + 1) # shared edges
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, g in enumerate(groups):
s = d.loc[d[G].astype(str) == g, S]
dens, _ = np.histogram(s, bins=edges, density=True)
sign = -1 if (MIRRORED and i == 1) else 1
ax.bar(edges[:-1], sign * dens, width=np.diff(edges), align="edge", color=PALETTE[i], alpha=0.65, label=g)
if W:
wd, _ = np.histogram(s, bins=edges, weights=d.loc[d[G].astype(str) == g, W], density=True)
ax.stairs(sign * wd, edges, color="black", linewidth=1.2)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xlabel(S)
ax.set_ylabel("density")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads overlap-density-demo.csv · app theme from the optional codesplash helper
# Propensity score overlap — Codesplash Chart Lab (recipe "overlap-density")
# controls: mirrored=true, bins=25
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("overlap-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["treated", "control"])
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)))
S = "propensity score"
G = "group"
W = "ATT weight"
BINS, MIRRORED = 25, True
d = df.dropna(subset=[S, G])
groups = levels_of(d[G].astype(str))[:2]
lo, hi = (0, 1) if d[S].between(0, 1).all() else (d[S].min(), d[S].max())
edges = np.linspace(lo, hi, BINS + 1)
fig = go.Figure()
for i, g in enumerate(groups):
dens, _ = np.histogram(d.loc[d[G].astype(str) == g, S], bins=edges, density=True)
sign = -1 if (MIRRORED and i == 1) else 1
fig.add_bar(x=(edges[:-1] + edges[1:]) / 2, y=sign * dens, width=np.diff(edges), name=g, marker_color=PALETTE[i], opacity=0.7)
fig.update_layout(barmode="overlay", xaxis_title=S, yaxis_title="density", bargap=0)
fig.show()Needs pandas, numpy, plotly · reads overlap-density-demo.csv · app theme from the optional codesplash helper
# Propensity score overlap — Codesplash Chart Lab (recipe "overlap-density")
# controls: mirrored=true, bins=25
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("overlap-density-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["group"]] <- factor(df[["group"]], levels = c("treated", "control"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
s_col <- "propensity score"
g_col <- "group"
w_col <- "ATT weight"
bins <- 25; mirrored <- TRUE
d <- data.frame(s = df[[s_col]], g = as.character(df[[g_col]]))
d <- d[!is.na(d$s) & !is.na(d$g), ]
groups <- utils::head(levels_of(d$g), 2)
rng <- if (all(d$s >= 0 & d$s <= 1)) c(0, 1) else range(d$s)
edges <- seq(rng[1], rng[2], length.out = bins + 1)
h <- do.call(rbind, lapply(seq_along(groups), function(i) {
x <- d$s[d$g == groups[i]]
cnt <- graphics::hist(x, breaks = edges, plot = FALSE, right = FALSE, include.lowest = TRUE)$counts
dens <- cnt / (length(x) * diff(edges))
data.frame(xmin = utils::head(edges, -1), xmax = edges[-1], y = if (mirrored && i == 2) -dens else dens, g = groups[i])
}))
h$g <- factor(h$g, levels = groups)
p <- ggplot(h) + geom_rect(aes(xmin = xmin, xmax = xmax, ymin = 0, ymax = y, fill = g), alpha = 0.65) +
geom_hline(yintercept = 0, colour = "grey50") + scale_fill_manual(values = cs_cat) +
labs(x = s_col, y = "density", fill = NULL) + theme_cs
print(p)Needs ggplot2 · reads overlap-density-demo.csv · app theme from the optional codesplashr helper