svgrdd-plot
Regression discontinuity
Does the outcome jump where the running variable crosses the cutoff?
How to read it
- Read the dots as binned means on each side of the cutoff.
- Look for a jump in the fit lines at the cutoff.
- Compare the jump with the bands around it.
- Callout 1: The jump at the cutoff: the estimated effect.
- Callout 2: The local fit below the cutoff.
- Callout 3: Bins further from the cutoff matter less.
Watch out
- If people can manipulate the running variable around the cutoff, the design fails. Check the density.
Defaults
- Cutoff
- 0
- The running variable's value where treatment changes.
- Range -1,000,000,000 to 1,000,000,000, step 0.1
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Bins are the engine's mimicking-variance (rdrobust `rdplot`) or evenly spaced bins; the lines are the local polynomial fits within the bandwidth with their robust bias-corrected bands.
- Rows with kind = fit (or with fit_x and fit_y and no kind) draw the fits; the legend's jump is the difference of the two fits nearest the cutoff — the engine's estimate is authoritative.
# Regression discontinuity — Codesplash Chart Lab (recipe "rdd-plot")
# controls: cutoff=0
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("rdd-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["side"] = pd.Categorical(df["side"].astype("string"), categories=["below (Democrat lost)", "above (Democrat won)"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["bin", "fit"])
_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)))
X = "margin of victory (pp)"
Y = "vote share next election (%)"
SIDE = "side"
FX = "fit_x"
FY = "fit_y"
FL = "fit_low"
FH = "fit_high"
KIND = "kind"
CUTOFF = 0
side = df[SIDE].astype(str) if SIDE else np.where(df[X].fillna(df[FX] if FX else 0) >= CUTOFF, "above", "below")
sides = levels_of(df[SIDE]) if SIDE else ["below", "above"]
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, s in enumerate(sides):
col = PALETTE[i % len(PALETTE)]
b = df[(side == str(s)) & df[X].notna() & df[Y].notna()]
ax.scatter(b[X], b[Y], s=16, color=col, alpha=0.8, label=str(s))
if FX and FY:
f = df[(side == str(s)) & df[FX].notna()].sort_values(FX)
if FL and FH:
ax.fill_between(f[FX], f[FL], f[FH], color=col, alpha=0.18, lw=0)
ax.plot(f[FX], f[FY], color=col, linewidth=2)
ax.axvline(CUTOFF, color=REF, linestyle="--", linewidth=1)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads rdd-plot-demo.csv · app theme from the optional codesplash helper
# Regression discontinuity — Codesplash Chart Lab (recipe "rdd-plot")
# controls: cutoff=0
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("rdd-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["side"] = pd.Categorical(df["side"].astype("string"), categories=["below (Democrat lost)", "above (Democrat won)"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["bin", "fit"])
_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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
X = "margin of victory (pp)"
Y = "vote share next election (%)"
SIDE = "side"
FX = "fit_x"
FY = "fit_y"
FL = "fit_low"
FH = "fit_high"
KIND = "kind"
CUTOFF = 0
side = df[SIDE].astype(str) if SIDE else np.where(df[X].fillna(df[FX] if FX else 0) >= CUTOFF, "above", "below")
sides = levels_of(df[SIDE]) if SIDE else ["below", "above"]
fig = go.Figure()
for i, s in enumerate(sides):
col = PALETTE[i % len(PALETTE)]
b = df[(side == str(s)) & df[X].notna() & df[Y].notna()]
fig.add_scatter(x=b[X], y=b[Y], mode="markers", name=str(s), marker=dict(color=col, size=6))
if FX and FY:
f = df[(side == str(s)) & df[FX].notna()].sort_values(FX)
if FL and FH:
fig.add_scatter(x=f[FX], y=f[FL], mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=f[FX], y=f[FH], mode="lines", line_width=0, fill="tonexty", fillcolor=rgba(col, 0.18), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=f[FX], y=f[FY], mode="lines", line=dict(color=col, width=2), showlegend=False)
fig.add_vline(x=CUTOFF, line=dict(color=REF, dash="dash", width=1))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads rdd-plot-demo.csv · app theme from the optional codesplash helper
# Regression discontinuity — Codesplash Chart Lab (recipe "rdd-plot")
# controls: cutoff=0
library(ggplot2)
library(dplyr)
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("rdd-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["side"]] <- factor(df[["side"]], levels = c("below (Democrat lost)", "above (Democrat won)"))
df[["kind"]] <- factor(df[["kind"]], levels = c("bin", "fit"))
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)]))
x_col <- "margin of victory (pp)"
y_col <- "vote share next election (%)"
side_col <- "side"
fx_col <- "fit_x"
fy_col <- "fit_y"
fl_col <- "fit_low"
fh_col <- "fit_high"
kind_col <- "kind"
cutoff <- 0
side <- if (is.null(side_col)) ifelse(dplyr::coalesce(df[[x_col]], if (is.null(fx_col)) 0 else df[[fx_col]]) >= cutoff, "above", "below") else as.character(df[[side_col]])
sides <- if (is.null(side_col)) c("below", "above") else levels_of(df[[side_col]])
bins <- data.frame(x = df[[x_col]], y = df[[y_col]], side = factor(side, levels = sides))
bins <- bins[!is.na(bins$x) & !is.na(bins$y), ]
p <- ggplot(bins, aes(x, y, colour = side)) + geom_point(alpha = 0.8)
if (!is.null(fx_col) && !is.null(fy_col)) {
fits <- data.frame(x = df[[fx_col]], y = df[[fy_col]], side = factor(side, levels = sides),
lo = if (is.null(fl_col)) NA else df[[fl_col]], hi = if (is.null(fh_col)) NA else df[[fh_col]])
fits <- fits[!is.na(fits$x), ]
p <- p + geom_ribbon(data = fits, aes(x, ymin = lo, ymax = hi, fill = side), inherit.aes = FALSE, alpha = 0.18) +
geom_line(data = fits, aes(x, y, colour = side), linewidth = 1)
}
p <- p + geom_vline(xintercept = cutoff, colour = ref_col, linetype = "dashed") +
scale_colour_manual(values = cs_cat) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = x_col, y = y_col, colour = NULL) + theme_cs
print(p)Needs ggplot2, dplyr · reads rdd-plot-demo.csv · app theme from the optional codesplashr helper