Skip to content
svgnull-distribution

Null distribution

How unusual is the observed statistic if the null hypothesis were true?

Demo data · seed 20261101 · 161 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the curve as what the statistic does when the null hypothesis is true.
  2. Find the observed value on the x axis.
  3. The shaded area beyond it is the p-value; the red region is where the test would reject.
  1. Callout 1: The observed statistic.
  2. Callout 2: Shaded tails: the p-value.
  3. 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