svgnull-distribution
Null distribution
How unusual is the observed statistic if the null hypothesis were true?
How to read it
- Read the curve as what the statistic does when the null hypothesis is true.
- Find the observed value on the x axis.
- The shaded area beyond it is the p-value; the red region is where the test would reject.
- Callout 1: The observed statistic.
- Callout 2: Shaded tails: the p-value.
- Callout 3: The rejection region for this α.
Watch out
- The curve assumes the null is true: the shaded area isn't the probability that the null is true.
Defaults
- Alternative
- Two-sided
- Which tail(s) count as at least as extreme as the observed value.
- Also: Greater · Less
- Show the rejection region
- On
- Shade the values that would lead this test to reject.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
- The density is the engine's exact or asymptotic null (t, χ², F, z, …) on a grid; the shaded area beyond the observed value is computed here by the trapezoid rule and approximates p on a fine grid.
- Two-sided tails are reflected about the null's median (0 for t and z), the usual definition for symmetric nulls; the engine's p remains authoritative.
- The rejection region is drawn from the engine's critical values at α when it publishes them.
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")
# controls: alternative=two.sided, critical=true
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("null-distribution-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")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "t"
D = "density"
OBS = "observed"
CL = "critical low"
CH = "critical high"
ALT, SHOW_CRIT = "two.sided", True
d = df.dropna(subset=[X, D]).sort_values(X)
x, y = d[X].to_numpy(float), d[D].to_numpy(float).clip(min=0)
obs, cl, ch = first(OBS), first(CL), first(CH)
cum = np.concatenate([[0.0], np.cumsum(np.diff(x) * (y[1:] + y[:-1]) / 2)])
centre = np.interp(cum[-1] / 2, cum, x) # the null's median: two-sided tails reflect about it
tail = x >= obs if ALT == "greater" else x <= obs if ALT == "less" else np.abs(x - centre) >= abs(obs - centre)
fig, ax = plt.subplots(figsize=(8, 4.5))
if SHOW_CRIT and (cl is not None or ch is not None):
crit = (x <= (cl if cl is not None else -np.inf)) | (x >= (ch if ch is not None else np.inf))
ax.fill_between(x, y, where=crit, color="#c13e2e", alpha=0.16, lw=0, label="rejection region")
ax.fill_between(x, y, where=tail, color=PALETTE[0], alpha=0.4, lw=0, label="area beyond observed (p)")
ax.plot(x, y, color=plt.rcParams["text.color"], linewidth=1.6, label="null density")
ax.axvline(obs, color=PALETTE[0], linewidth=1.6)
ax.annotate(f"observed = {obs:g}", (obs, ax.get_ylim()[1]), xytext=(5, -12), textcoords="offset points", fontsize=9)
ax.set_xlabel(X)
ax.set_ylabel("density under H0")
ax.legend(fontsize=8, loc="upper left")
plt.show()Needs pandas, numpy, matplotlib · reads null-distribution-demo.csv · app theme from the optional codesplash helper
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")
# controls: alternative=two.sided, critical=true
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("null-distribution-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")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "t"
D = "density"
OBS = "observed"
CL = "critical low"
CH = "critical high"
ALT, SHOW_CRIT = "two.sided", True
d = df.dropna(subset=[X, D]).sort_values(X)
x, y = d[X].to_numpy(float), d[D].to_numpy(float).clip(min=0)
obs, cl, ch = first(OBS), first(CL), first(CH)
cum = np.concatenate([[0.0], np.cumsum(np.diff(x) * (y[1:] + y[:-1]) / 2)])
centre = np.interp(cum[-1] / 2, cum, x)
if ALT == "greater":
parts = [x >= obs]
elif ALT == "less":
parts = [x <= obs]
else:
parts = [x <= centre - abs(obs - centre), x >= centre + abs(obs - centre)]
fig = go.Figure()
if SHOW_CRIT:
for m in ([x <= cl] if cl is not None else []) + ([x >= ch] if ch is not None else []):
fig.add_scatter(x=x[m], y=y[m], fill="tozeroy", mode="none", fillcolor="rgba(193, 62, 46, 0.16)", name="rejection region")
for m in parts:
fig.add_scatter(x=x[m], y=y[m], fill="tozeroy", mode="none", fillcolor="rgba(8, 89, 172, 0.4)", name="area beyond observed")
fig.add_scatter(x=x, y=y, mode="lines", line=dict(color=REF, width=2), name="null density")
fig.add_vline(x=obs, line_color=PALETTE[0], annotation_text=f"observed = {obs:g}")
fig.update_layout(xaxis_title=X, yaxis_title="density under H0")
fig.show()Needs pandas, numpy, plotly · reads null-distribution-demo.csv · app theme from the optional codesplash helper
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")
# controls: alternative=two.sided, critical=true
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("null-distribution-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
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
x_col <- "t"
d_col <- "density"
obs_col <- "observed"
cl_col <- "critical low"
ch_col <- "critical high"
alt <- "two.sided"; show_crit <- TRUE
d <- df[!is.na(df[[x_col]]) & !is.na(df[[d_col]]), ]
d <- data.frame(x = d[[x_col]], y = pmax(0, d[[d_col]]))
d <- d[order(d$x), ]
obs <- first_num(obs_col); cl <- first_num(cl_col); ch <- first_num(ch_col)
cum <- c(0, cumsum(diff(d$x) * (head(d$y, -1) + tail(d$y, -1)) / 2))
centre <- approx(cum, d$x, xout = max(cum) / 2)$y # the null's median
d$tail <- if (alt == "greater") d$x >= obs else if (alt == "less") d$x <= obs else abs(d$x - centre) >= abs(obs - centre)
d$side <- ifelse(d$x < centre, "low", "high")
d$crit <- (!is.na(cl) & d$x <= cl) | (!is.na(ch) & d$x >= ch)
p <- ggplot(d, aes(x, y)) +
{ if (show_crit) geom_area(data = d[d$crit, ], aes(group = side), fill = "#c13e2e", alpha = 0.16) } +
geom_area(data = d[d$tail, ], aes(group = side), fill = cs_cat[1], alpha = 0.4) +
geom_line(linewidth = 0.8) + geom_vline(xintercept = obs, colour = cs_cat[1], linewidth = 0.8) +
annotate("text", x = obs, y = max(d$y), label = paste("observed =", format(obs)), hjust = -0.05, vjust = 1, size = 3.2) +
labs(x = x_col, y = "density under H0") + theme_cs
print(p)Needs ggplot2 · reads null-distribution-demo.csv · app theme from the optional codesplashr helper