svgrootogram
Hanging rootogram
Does a count model fit the distribution of counts — zeros, overdispersion, the tail?
How to read it
- Read the line as the counts the model expects, on a square-root scale.
- Each bar hangs from the line: its height is the observed count.
- A bar ending above or below zero marks a count the model under- or over-predicts.
- Callout 1: A bar past zero: more zeros than the model predicts.
- Callout 2: The line: the model's expected counts.
- Callout 3: Tail: are large counts well predicted?
Watch out
- The square-root scale makes small mismatches visible but not proportional: read gaps with care.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- Square-root scale (Tukey 1977): each bar spans √expected − √observed to √expected, so a bar bottom below 0 means under-prediction and above 0 over-prediction.
- Expected frequencies are Σᵢ P(Y = k | xᵢ) from the fitted model (Poisson, negative binomial, …).
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")
# 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("rootogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
K = "visits"
OBS = "observed"
EXP = "expected (Poisson)"
d = df.dropna(subset=[K, OBS, EXP]).sort_values(K)
top = np.sqrt(d[EXP]) # bars hang from the expected frequency (square-root scale)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(d[K], np.sqrt(d[OBS]), bottom=top - np.sqrt(d[OBS]), width=0.8, color=GREY, edgecolor=REF, linewidth=0.6)
ax.plot(d[K], top, color=PALETTE[0], linewidth=2, marker="o", ms=4, label=EXP)
ax.axhline(0, color="#ce5342", linewidth=1)
ax.set_xlabel(K)
ax.set_ylabel("√ frequency")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads rootogram-demo.csv · app theme from the optional codesplash helper
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")
# 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("rootogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
K = "visits"
OBS = "observed"
EXP = "expected (Poisson)"
d = df.dropna(subset=[K, OBS, EXP]).sort_values(K)
top = np.sqrt(d[EXP])
fig = go.Figure()
fig.add_bar(x=d[K], y=np.sqrt(d[OBS]), base=top - np.sqrt(d[OBS]), marker=dict(color=GREY, line=dict(color=REF, width=0.6)), name=OBS)
fig.add_scatter(x=d[K], y=top, mode="lines+markers", line=dict(color=PALETTE[0], width=2), name=EXP)
fig.add_hline(y=0, line=dict(color="#ce5342", width=1))
fig.update_layout(xaxis_title=K, yaxis_title="√ frequency", bargap=0.2)
fig.show()Needs pandas, numpy, plotly · reads rootogram-demo.csv · app theme from the optional codesplash helper
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")
# 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("rootogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
k_col <- "visits"
obs_col <- "observed"
exp_col <- "expected (Poisson)"
d <- df[!is.na(df[[k_col]]) & !is.na(df[[obs_col]]) & !is.na(df[[exp_col]]), ]
d <- data.frame(k = d[[k_col]], top = sqrt(d[[exp_col]]), bar = sqrt(d[[obs_col]]))
d <- d[order(d$k), ]
p <- ggplot(d) + geom_rect(aes(xmin = k - 0.4, xmax = k + 0.4, ymin = top - bar, ymax = top), fill = grey_col, colour = ref_col, linewidth = 0.3) +
geom_line(aes(k, top), colour = cs_cat[1], linewidth = 0.9) + geom_point(aes(k, top), colour = cs_cat[1], size = 1.8) +
geom_hline(yintercept = 0, colour = "#ce5342") + labs(x = k_col, y = "√ frequency") + theme_cs
print(p)Needs ggplot2 · reads rootogram-demo.csv · app theme from the optional codesplashr helper