svgunit-effects
Unit effects
How far apart are the units once the regressors are held fixed, and how precisely is each one known?
How to read it
- Read each row as one unit's level once the regressors are held fixed.
- Rows are sorted, with the mean effect marked.
- Compare intervals: which units sit well apart from the mean?
Watch out
- With few observations per unit these estimates are noisy, and the extremes are the likeliest to be exaggerated.
Defaults
No settings: the chart draws one way.
Pinned in the code
- α̂ᵢ = ȳᵢ − x̄ᵢ'b̂, with SE √(s²/Tᵢ + x̄ᵢ'V̂x̄ᵢ) from the classical covariance, as plm's fixef.
- With short panels each α̂ᵢ rests on few rows and is noisy (the incidental parameters problem): read the spread, not any one unit's rank.
# Unit effects — Codesplash Chart Lab (recipe "unit-effects")
# controls: defaults
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("unit-effects-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["region 1", "region 2", "region 3", "region 4", "region 5", "region 6", "region 7", "region 8", "region 9", "region 10", "region 11", "region 12", "region 13", "region 14"])
_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")
LABEL = "region"
EFFECT = "fixed effect"
LOW, HIGH = "lower", "upper"
REFERENCE = None
d = df.dropna(subset=[EFFECT]).sort_values(EFFECT, ascending=False, kind="mergesort") # largest first
reference = REFERENCE if REFERENCE else d[EFFECT].mean()
pos = np.arange(len(d))
fig, ax = plt.subplots(figsize=(7, max(3, 0.28 * len(d))))
if LOW and HIGH:
ax.hlines(pos, d[LOW], d[HIGH], color=PALETTE[0], alpha=0.55)
ax.scatter(d[EFFECT], pos, s=28, color=PALETTE[0], zorder=3)
ax.axvline(reference, color=REF, linestyle="--", label=f"mean {reference:.3g}")
ax.set_yticks(pos, d[LABEL].astype(str))
ax.invert_yaxis()
ax.set_xlabel(EFFECT)
ax.set_title("Unit effects")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads unit-effects-demo.csv · app theme from the optional codesplash helper
# Unit effects — Codesplash Chart Lab (recipe "unit-effects")
# controls: defaults
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("unit-effects-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["region 1", "region 2", "region 3", "region 4", "region 5", "region 6", "region 7", "region 8", "region 9", "region 10", "region 11", "region 12", "region 13", "region 14"])
_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")
LABEL = "region"
EFFECT = "fixed effect"
LOW, HIGH = "lower", "upper"
REFERENCE = None
d = df.dropna(subset=[EFFECT]).sort_values(EFFECT, ascending=False, kind="mergesort")
reference = REFERENCE if REFERENCE else d[EFFECT].mean()
error = dict(type="data", symmetric=False, array=d[HIGH] - d[EFFECT], arrayminus=d[EFFECT] - d[LOW], color=PALETTE[0]) if LOW and HIGH else None
fig = go.Figure(go.Scatter(x=d[EFFECT], y=d[LABEL].astype(str), mode="markers", error_x=error, marker=dict(color=PALETTE[0], size=8), name="effect"))
fig.add_vline(x=reference, line_dash="dash", line_color=REF, annotation_text=f"mean {reference:.3g}")
fig.update_yaxes(autorange="reversed")
fig.update_layout(xaxis_title=EFFECT, title="Unit effects")
fig.show()Needs pandas, numpy, plotly · reads unit-effects-demo.csv · app theme from the optional codesplash helper
# Unit effects — Codesplash Chart Lab (recipe "unit-effects")
# controls: defaults
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("unit-effects-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("region 1", "region 2", "region 3", "region 4", "region 5", "region 6", "region 7", "region 8", "region 9", "region 10", "region 11", "region 12", "region 13", "region 14"))
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
label_col <- "region"
effect_col <- "fixed effect"
low_col <- "lower"; high_col <- "upper"
reference <- NA_real_
d <- data.frame(unit = as.character(df[[label_col]]), effect = df[[effect_col]])
if (!is.null(low_col) && !is.null(high_col)) { d$low <- df[[low_col]]; d$high <- df[[high_col]] }
d <- d[is.finite(d$effect), ]
d <- d[order(-d$effect), ] # largest first
d$unit <- factor(d$unit, levels = rev(d$unit))
if (is.na(reference) || reference == 0) reference <- mean(d$effect)
p <- ggplot(d, aes(effect, unit)) +
geom_vline(xintercept = reference, colour = ref_col, linetype = "dashed") +
{ if ("low" %in% names(d)) geom_segment(aes(x = low, xend = high, yend = unit), colour = cs_cat[1], alpha = 0.55) } +
geom_point(colour = cs_cat[1], size = 2) +
labs(x = effect_col, y = NULL, title = "Unit effects", subtitle = sprintf("mean %.3g", reference)) + theme_cs
print(p)Needs ggplot2 · reads unit-effects-demo.csv · app theme from the optional codesplashr helper