svgevent-study
Event study
Were treated and control units on parallel paths before treatment, and how did the effect evolve after?
How to read it
- Read points left of zero: before treatment. They should hover around zero.
- Read points right of zero: the effect at each period after.
- Check the intervals: do pre-period intervals stay away from zero?
- Callout 1: Pre-period: flat around zero supports parallel trends.
- Callout 2: The reference period.
- Callout 3: The effect grows after treatment.
Watch out
- Flat pre-trends don't prove parallel trends would have continued; test sensitivity.
Defaults
- Reference (omitted) period
- -1
- Send null when the design has no omitted period.
- Range -50 to 50, step 1
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- The reference period is drawn hollow at 0 (its coefficient is normalized away); the dashed line marks treatment onset half a period after it.
- Pre-period coefficients near zero support (but cannot prove) parallel trends; the engine reports the joint pre-trend test and HonestDiD bounds separately.
- Several estimators or cohorts are dodged horizontally so their intervals do not overlap.
# Event study — Codesplash Chart Lab (recipe "event-study")
# controls: reference=-1
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("event-study-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["estimator"] = pd.Categorical(df["estimator"].astype("string"), categories=["TWFE", "Callaway–Sant'Anna"])
_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)))
T = "years relative to adoption"
EST = "effect on employment (pp)"
LO = "ci_low"
HI = "ci_high"
G = "estimator"
REFERENCE = -1 # omitted period, drawn hollow at 0
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values(T)))
fig, ax = plt.subplots(figsize=(8, 4.5))
onset = (REFERENCE if REFERENCE is not None else -1) + 0.5
ax.axvspan(df[T].min() - 0.6, onset, color="grey", alpha=0.06, lw=0)
ax.axhline(0, color="grey", linewidth=0.8)
ax.axvline(onset, color=REF, linestyle="--", linewidth=1)
k = len(series)
for i, (name, d) in enumerate(series):
off = (i - (k - 1) / 2) * 0.16 if k > 1 else 0
col = PALETTE[i % len(PALETTE)]
ax.errorbar(d[T] + off, d[EST], yerr=[d[EST] - d[LO], d[HI] - d[EST]], fmt="o-", color=col, ms=5, lw=1, elinewidth=1.6, label=name or None)
if REFERENCE is not None and not (d[T] == REFERENCE).any():
ax.plot([REFERENCE + off], [0], "o", mfc="white", mec=col, ms=6)
ax.set_xlabel(T)
ax.set_ylabel(EST)
if G: ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads event-study-demo.csv · app theme from the optional codesplash helper
# Event study — Codesplash Chart Lab (recipe "event-study")
# controls: reference=-1
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("event-study-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["estimator"] = pd.Categorical(df["estimator"].astype("string"), categories=["TWFE", "Callaway–Sant'Anna"])
_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)))
T = "years relative to adoption"
EST = "effect on employment (pp)"
LO = "ci_low"
HI = "ci_high"
G = "estimator"
REFERENCE = -1
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values(T)))
fig = go.Figure()
onset = (REFERENCE if REFERENCE is not None else -1) + 0.5
fig.add_vrect(x0=df[T].min() - 0.6, x1=onset, fillcolor="grey", opacity=0.06, line_width=0)
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.add_vline(x=onset, line=dict(color=REF, dash="dash", width=1))
for i, (name, d) in enumerate(series):
off = (i - (len(series) - 1) / 2) * 0.16 if len(series) > 1 else 0
fig.add_scatter(x=d[T] + off, y=d[EST], mode="lines+markers", name=name or EST, marker_color=PALETTE[i % len(PALETTE)],
error_y=dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]))
fig.update_layout(xaxis_title=T, yaxis_title=EST)
fig.show()Needs pandas, numpy, plotly · reads event-study-demo.csv · app theme from the optional codesplash helper
# Event study — Codesplash Chart Lab (recipe "event-study")
# controls: reference=-1
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("event-study-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["estimator"]] <- factor(df[["estimator"]], levels = c("TWFE", "Callaway–Sant'Anna"))
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)]))
t_col <- "years relative to adoption"
est_col <- "effect on employment (pp)"
lo_col <- "ci_low"
hi_col <- "ci_high"
g_col <- "estimator"
reference <- -1
d <- data.frame(t = df[[t_col]], est = df[[est_col]], lo = df[[lo_col]], hi = df[[hi_col]],
g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
onset <- (if (is.null(reference)) -1 else reference) + 0.5
pd <- position_dodge(width = if (is.null(g_col)) 0 else 0.35)
p <- ggplot(d, aes(t, est, colour = g)) +
annotate("rect", xmin = -Inf, xmax = onset, ymin = -Inf, ymax = Inf, fill = "grey50", alpha = 0.06) +
geom_hline(yintercept = 0, colour = "grey50") + geom_vline(xintercept = onset, colour = ref_col, linetype = "dashed") +
geom_line(alpha = 0.5, position = pd) + geom_errorbar(aes(ymin = lo, ymax = hi), width = 0, linewidth = 0.8, position = pd) +
geom_point(size = 2.2, position = pd) +
{ if (!is.null(reference)) annotate("point", x = reference, y = 0, shape = 21, fill = "white", colour = "grey40", size = 2.4) } +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") +
labs(x = t_col, y = est_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads event-study-demo.csv · app theme from the optional codesplashr helper