Skip to content
CodeSplashChart cookbook

Chart Lab · one-file edition

Chart cookbook

Every chart CodeSplash can draw: the question it answers, how to read it, the settings it starts with, and the code that draws the same chart in matplotlib, plotly, ggplot2 or DuckDB SQL.

recipes
293
families
21
charts, light and dark
586
reading cards
293
code snippets
946

Generated 2026-11-08 from the app's chart registry. Each chart is the app's own offscreen SVG export of seeded demo data (seed 20261101) at its default settings, in light and dark: the theme button switches between them. The code reads the same demo rows from <recipe>-demo.csv (Chart Lab → Code → Download demo CSV).

Distributions

Shape, spread and outliers of one or more numeric variables.

17

Distributions

svgbrushable#histogram

Histogram

How is one numeric variable distributed?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Find the tallest bars: that is where values are most common.
  2. Follow the outline for shape: one hump or two, a long tail on one side, gaps.
  3. Change the bin rule. A feature that survives other bin widths is real; one that vanishes came from the binning.
  1. Callout 1: The tallest bars: the most common values.
  2. Callout 2: A second hump: two groups may be mixed in this column.
  3. Callout 3: The tail: how far values stretch from the centre.

Watch out

  • With few rows the shape is mostly noise: a bumpy histogram of 30 values says little about modes.
  • Bin edges can create or hide a mode. Check a density curve or another bin rule before you describe a shape.

Defaults

Bin rule
Freedman–Diaconis
How the bin width is chosen. Freedman–Diaconis resists outliers; Sturges suits small, near-normal data.
Also: Sturges · Scott · Rice · Square root · Doane · Manual
Bins (manual)
30
The number of bins when the bin rule is manual.
Range 2 to 200, step 1
Y axis
Density
Show counts, density or shares on the y axis.
Also: Count
Density curve (KDE)
On
Draw a smoothed curve over the bars, to judge shape apart from the bins.
Bandwidth rule
nrd0 (Silverman, R default)
The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
Also: nrd (Scott variant) · Scott (scipy default)
Bandwidth × adjust
1
Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
Range 0.25 to 4, step 0.25
Normal fit
Off
Overlay the normal curve with this mean and standard deviation.
Rug (≤ 5,000 points)
Off
Add one tick per value along the axis.

Pinned in the code

  • Edges: numpy-style equal width over [min, max]; bins are [a, b) and the last bin is closed.
  • Bin rules (numpy `histogram_bin_edges`): Freedman–Diaconis h = 2·IQR·n^(−1/3), Sturges ⌈log₂n⌉+1, Scott h = 3.49·σ·n^(−1/3), Rice 2·n^(1/3), √n, Doane.
  • Quartiles are type 7; σ uses n − 1.
  • KDE: Gaussian kernel, bandwidth = rule × adjust (R `density(bw = "nrd0", adjust)`); ≥ 20,000 points are thinned for the curve only.
  • Normal fit: N(x̄, s²) density.
# Histogram — Codesplash Chart Lab (recipe "histogram")
# controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde, norm

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("histogram-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

x = df["score"].dropna().to_numpy(dtype=float)
edges = np.histogram_bin_edges(x, bins="fd")  # numpy edges, [a, b) like the app
width = edges[1] - edges[0]

fig, ax = plt.subplots(figsize=(7, 4))
ax.hist(x, bins=edges, density=True, color=PALETTE[0], alpha=0.85, edgecolor="white", linewidth=0.6)
grid = np.linspace(edges[0], edges[-1], 512)
scale = 1.0  # density → density
h = bandwidth(x, "nrd0") * 1
kde = gaussian_kde(x, bw_method=h / x.std(ddof=1))  # scipy takes the bandwidth relative to sd
ax.plot(grid, kde(grid) * scale, color=PALETTE[1], linewidth=2, label=f"KDE (h = {h:.3g})")
ax.set_xlabel("score")
ax.set_ylabel("Density")
ax.legend()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads histogram-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#box-violin

Box & violin

How does a numeric variable differ across groups?

Demo data · seed 20261101 · 240 rows · default settings · 640 × 360

How to read it

  1. Compare the medians first: the line inside each box.
  2. Compare the box heights: each box holds the middle half of its group, so a taller box means more spread.
  3. Check the points beyond the whiskers, then the violin outline for a shape the box cannot show, such as two humps.
  1. Callout 1: Line in the box: the median. Dot: the mean.
  2. Callout 2: Beyond the whiskers: values flagged as unusual, not errors.
  3. Callout 3: Violin width: how many values sit at that level.

Watch out

  • A box plot hides two-humped data. Turn on the violin or look at the raw points.
  • Violins are smoothed, so they can suggest values beyond the data's range, especially in small groups.

Defaults

Violin (KDE)
On
Add a smoothed outline of each group's shape.
Notches (median CI)
Off
Add notches around each median. Notches that don't overlap suggest different medians.
Mean marker
On
Mark the mean as well as the median. A gap between them signals skew.
Whisker × IQR
1.5
How far whiskers reach, in multiples of the box's height; 1.5 is Tukey's rule.
Range 0.5 to 3, step 0.5

Pinned in the code

  • Quartiles are type 7 (R default; not base `boxplot.stats` hinges).
  • Whiskers reach the most extreme points within k × IQR of the box (k = 1.5); points beyond are drawn as outliers.
  • Notches: median ± 1.58·IQR/√n (McGill, Tukey & Larsen 1978).
  • Violins: Gaussian KDE with bw.nrd0, truncated to the data range, scaled to the widest group.
# Box & violin — Codesplash Chart Lab (recipe "box-violin")
# controls: violin=true, notch=false, mean=true, whisker=1.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cbook

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("box-violin-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Control", "Treatment A", "Treatment B"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

def kde(v, h, grid):
    """Gaussian kernel density by direct summation on `grid` (the app's method)."""
    v = np.asarray(v, dtype=float)
    grid = np.asarray(grid, dtype=float)
    out = np.empty(grid.size)
    for i in range(0, grid.size, 32):  # chunks keep memory small for large samples
        z = (grid[i:i + 32, None] - v[None, :]) / h
        out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
    return out / (v.size * h * np.sqrt(2 * np.pi))

parts = groups(df, "outcome", "arm", max_levels=12)
stats = []
for label, v in parts:
    s = cbook.boxplot_stats(v, whis=1.5, labels=[label])[0]  # type-7 quartiles; whiskers within 1.5 × IQR
    half = 1.58 * s["iqr"] / np.sqrt(v.size)  # notch: McGill et al. 1.58·IQR/√n (matplotlib's default is 1.57)
    s.update(cilo=s["med"] - half, cihi=s["med"] + half)
    stats.append(s)

fig, ax = plt.subplots(figsize=(7, 4))
pos = np.arange(len(parts))
# violins: Gaussian KDE with bw.nrd0 per group, truncated to the data range, one density scale
curves = []
for label, v in parts:
    grid = np.linspace(v.min(), v.max(), 64)
    curves.append((grid, kde(v, bandwidth(v, "nrd0"), grid) if v.size > 1 else np.zeros(64)))
top = max(d.max() for _, d in curves) or 1.0
for i, (grid, d) in enumerate(curves):
    half = 0.42 * d / top
    ax.fill_betweenx(grid, i - half, i + half, color=PALETTE[i % len(PALETTE)], alpha=0.25, linewidth=0)
ax.bxp(stats, positions=pos, widths=0.18, shownotches=False, showmeans=True, patch_artist=True,
       boxprops=dict(facecolor=plt.rcParams["axes.facecolor"], edgecolor=plt.rcParams["text.color"]),
       medianprops=dict(color=plt.rcParams["text.color"], linewidth=1.5),
       meanprops=dict(marker="D", markerfacecolor=PALETTE[1], markeredgecolor="white"),
       flierprops=dict(marker="o", markerfacecolor="none", markeredgecolor=PALETTE[0]))
ax.set_xticks(pos, [label for label, _ in parts])
ax.set_xlabel("arm")
ax.set_ylabel("outcome")
plt.show()

Needs pandas, numpy, matplotlib · reads box-violin-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#density

Density curve

What is the smooth shape of a distribution, and how much does it depend on the bandwidth?

Demo data · seed 20261101 · 900 rows · default settings · 640 × 360

How to read it

  1. Read the height as relative concentration: higher means more values nearby, and the total area under the curve is 1.
  2. Compare the curves at half and twice the bandwidth: trust the features that appear in all three.
  3. Use the rug along the axis to see where the real values are, and whether the curve runs past them.
  1. Callout 1: The peak: where values concentrate.
  2. Callout 2: The same data at half and twice the bandwidth: wiggles that vanish were noise.
  3. Callout 3: Rug: one tick per value.

Watch out

  • The curve's height is not a probability; only areas under it are.
  • Smoothing spills past natural limits: a density of ages or prices can show mass below zero.

Defaults

Bandwidth rule
nrd0 (Silverman, R default)
The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
Also: nrd (Scott variant) · Scott (scipy default)
Bandwidth × adjust
1
Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
Range 0.25 to 4, step 0.25
Compare bandwidths ×0.5 / ×1 / ×2
On
Only without a group.
Fill under curve
On
Shade the area under each curve.
Rug (≤ 5,000 points)
On
Add one tick per value along the axis.

Pinned in the code

  • Gaussian kernel; bandwidth = rule × adjust (R `density(bw = "nrd0", adjust)`; scipy `gaussian_kde` uses Scott).
  • Evaluated on 160 points over [min − 3·bw, max + 3·bw] (R's default cut = 3), direct summation.
  • Per-group curves each use their own bandwidth and integrate to 1; the selected-rows curve is scaled by its share of rows.
# Density curve — Codesplash Chart Lab (recipe "density")
# controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=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("density-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

def kde(v, h, grid):
    """Gaussian kernel density by direct summation on `grid` (the app's method)."""
    v = np.asarray(v, dtype=float)
    grid = np.asarray(grid, dtype=float)
    out = np.empty(grid.size)
    for i in range(0, grid.size, 32):  # chunks keep memory small for large samples
        z = (grid[i:i + 32, None] - v[None, :]) / h
        out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
    return out / (v.size * h * np.sqrt(2 * np.pi))

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "income_k", None, max_levels=6)
pooled = np.concatenate([v for _, v in parts])
base = bandwidth(pooled, "nrd0") * 1
curves = [(f"bw {base * k:.3g} (×{k:g})", pooled, base * k) for k in (0.5, 1, 2)]  # compare bandwidths
pad = 3 * max(h for _, _, h in curves)  # R density(cut = 3)
grid = np.linspace(pooled.min() - pad, pooled.max() + pad, 160)

fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v, h) in enumerate(curves):
    y = kde(v, h, grid)
    ax.plot(grid, y, color=PALETTE[i], linewidth=2 if i == 1 else 1.5, linestyle="--" if i == 0 else "-", label=label)
    if i == 1:
        ax.fill_between(grid, y, color=PALETTE[i], alpha=0.22, linewidth=0)
if pooled.size <= 5000:
    ax.plot(pooled, np.zeros_like(pooled), "|", color=plt.rcParams["text.color"], alpha=0.3, markersize=10)
ax.set_xlabel("income_k")
ax.set_ylabel("Density")
if len(curves) > 1:
    ax.legend()
plt.show()

Needs pandas, numpy, matplotlib · reads density-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#ridgeline

Ridgeline

How do the distributions of many groups compare and shift?

Demo data · seed 20261101 · 720 rows · default settings · 640 × 360

How to read it

  1. Read each row as one group's distribution, on a shared x axis.
  2. Follow the peaks from row to row to see the level shift.
  3. Compare widths to see whether spread changes along with the level.
  1. Callout 1: A peak: where this group's values concentrate.
  2. Callout 2: The short vertical line: this group's median.
  3. Callout 3: Rows are in this order; choose an order that means something.

Watch out

  • Overlap hides part of each curve, so compare peaks and medians rather than areas.
  • Each curve is smoothed separately: a small group's bump may be noise.

Defaults

Overlap
1.6
How much neighbouring curves overlap.
Range 0.5 to 3, step 0.1
Order
As in data / dictionary
How rows or groups are ordered.
Also: By median
Median line
On
Mark each group's median.
Bandwidth rule
nrd0 (Silverman, R default)
The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
Also: nrd (Scott variant) · Scott (scipy default)
Bandwidth × adjust
1
Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
Range 0.25 to 4, step 0.25

Pinned in the code

  • Each ridge is a Gaussian KDE with its own bandwidth (rule × adjust) on a shared grid over [min − 3·bw, max + 3·bw].
  • All ridges share one height scale (global maximum density), as `ggridges::geom_density_ridges(scale = overlap)`.
  • Median: type-7 quantile.
# Ridgeline — Codesplash Chart Lab (recipe "ridgeline")
# controls: overlap=1.6, order=data, median=true, bandwidth=nrd0, adjust=1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("ridgeline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.Categorical(df["month"].astype("string"), categories=["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"])

def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

def kde(v, h, grid):
    """Gaussian kernel density by direct summation on `grid` (the app's method)."""
    v = np.asarray(v, dtype=float)
    grid = np.asarray(grid, dtype=float)
    out = np.empty(grid.size)
    for i in range(0, grid.size, 32):  # chunks keep memory small for large samples
        z = (grid[i:i + 32, None] - v[None, :]) / h
        out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
    return out / (v.size * h * np.sqrt(2 * np.pi))

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"]  # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
parts = [(label, v) for label, v in groups(df, "temp_c", "month", max_levels=24) if v.size > 1]
hs = [bandwidth(v, "nrd0") * 1 for _, v in parts]  # each ridge its own bandwidth
pooled = np.concatenate([v for _, v in parts])
pad = 3 * max(hs)
grid = np.linspace(pooled.min() - pad, pooled.max() + pad, 140)
dens = [kde(v, h, grid) for (_, v), h in zip(parts, hs)]
top = max(d.max() for d in dens)  # one height scale for all ridges (ggridges scale = overlap)
overlap = 1.6
k = len(parts)
colors = PALETTE if k <= 8 else [CMAP(0.25 + 0.7 * i / max(1, k - 1)) for i in range(k)]

fig, ax = plt.subplots(figsize=(7, 1.5 + 0.45 * k))
for i, ((label, v), d) in enumerate(zip(parts, dens)):
    base = k - 1 - i  # first group on top; lower ridges overlap the ones above
    ridge = base + overlap * d / top
    color = colors[i % len(colors)]
    ax.fill_between(grid, base, ridge, color=color, alpha=0.55, linewidth=0, zorder=i)
    ax.plot(grid, ridge, color=color, linewidth=1.2, zorder=i + 0.5)
    m = np.median(v)
    ax.vlines(m, base, base + overlap * np.interp(m, grid, d) / top, color=plt.rcParams["text.color"], alpha=0.6, linewidth=1.2, zorder=i + 0.6)
ax.set_yticks([k - 1 - i for i in range(k)], [label for label, _ in parts])
ax.grid(axis="y", visible=False)
ax.set_xlabel("temp_c")
plt.show()

Needs pandas, numpy, matplotlib · reads ridgeline-demo.csv · app theme from the optional codesplash helper

  • ggridges::geom_density_ridges(scale = overlap) draws the same picture; the code builds the ridges with base ggplot2 so no extension package is needed.

Distributions

svgbrushable#ecdf

ECDF

What share of values falls below any threshold, and how do groups differ across the whole range?

Demo data · seed 20261101 · 570 rows · default settings · 640 × 360

How to read it

  1. Pick a value on the x axis and read up: the curve's height is the share of rows at or below that value.
  2. Read across at 50% to find each group's median, at 90% for the upper tail.
  3. Where one curve sits to the right of another across the whole range, that group has larger values throughout.
  1. Callout 1: Read across at 50%: each group's median.
  2. Callout 2: The curve further right has larger values at that share.
  3. Callout 3: The band: uncertainty around each curve.

Watch out

  • Steep is not high: a steep section means many values packed into a narrow range.
  • Crossing curves mean no group is larger throughout; say where each one leads.

Defaults

DKW 95% band
On
Shade a band that holds the whole true curve 95% of the time.
Median reference
On
Draw a reference at 50%, so you can read medians off the curve.
Show 1 − F (exceedance)
Off
Plot the share above each value rather than below it.

Pinned in the code

  • F̂(x) = #{xᵢ ≤ x}/n, right-continuous steps (R `ecdf`, `scipy.stats.ecdf`).
  • Band: Dvoretzky–Kiefer–Wolfowitz, F̂ ± ε with ε = √(ln(2/α)/(2n)), α = 0.05, clipped to [0, 1] — simultaneous over x.
  • Median marker at the type-7 median.
# ECDF — Codesplash Chart Lab (recipe "ecdf")
# controls: band=true, median=true, complement=false
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("ecdf-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["device"] = pd.Categorical(df["device"].astype("string"), categories=["Desktop", "Mobile", "Tablet"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "minutes", "device", max_levels=8)
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    color = PALETTE[i % len(PALETTE)]
    many = len(parts) > 1  # several groups: a dash and a median marker shape per group, as in the app
    ax.ecdf(v, complementary=False, color=color, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if many else "-", label=label)  # F̂(x) = #{xᵢ ≤ x}/n, right-continuous
    xs = np.unique(v)
    F = np.searchsorted(np.sort(v), xs, side="right") / v.size
    eps = np.sqrt(np.log(2 / 0.05) / (2 * v.size))  # DKW 95% band, simultaneous over x
    lo, hi = np.clip(F - eps, 0, 1), np.clip(F + eps, 0, 1)
    ax.fill_between(xs, lo, hi, step="post", color=color, alpha=0.15, linewidth=0)
    ax.axvline(np.median(v), color=color, linestyle=":", linewidth=1)  # type-7 median
    ax.plot([np.median(v)], [0.5], linestyle="none", marker=SERIES_MARKERS[i % 8] if many else "o", markersize=6, markerfacecolor=plt.rcParams["axes.facecolor"], markeredgecolor=color, markeredgewidth=1.5)
ax.set_xlabel("minutes")
ax.set_ylabel("F(x)")
if len(parts) > 1:
    ax.legend()
plt.show()

Needs pandas, numpy, matplotlib · reads ecdf-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#qq

Normal Q–Q plot

Is a variable (or a set of residuals) approximately normal, and where does it depart?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Points on the straight line: the data match a normal shape.
  2. Look at the ends. Points above the line on the right and below on the left mean heavy tails; curving one way means skew.
  3. Compare with the envelope: points outside it stray further than chance alone would usually allow.
  1. Callout 1: Points on the line: this part of the data matches a normal shape.
  2. Callout 2: Above the line at the right: larger values than a normal would give.
  3. Callout 3: Below the line at the left: the lower tail is heavier too.

Watch out

  • With thousands of rows, tiny departures fall outside the envelope without mattering for most methods.
  • In small samples, even normal data can wander. Judge the pattern, not one point.

Defaults

Pointwise envelope
On
Shade the range a correct normal sample would stay inside at each point.
Envelope level
95%
How often a correct normal sample would stay inside the envelope at each point.
Also: 99%
Detrended (worm plot)
Off
Subtract the line, so small departures are easier to see.

Pinned in the code

  • Plotting positions: R `ppoints(n)` = (i − a)/(n + 1 − 2a), a = 3/8 for n ≤ 10 else 1/2; theoretical quantiles Φ⁻¹(pᵢ).
  • Reference line: R `qqline` through the type-7 first and third quartiles of the sample and of N(0, 1) (robust to tails).
  • Envelope: exact pointwise band from uniform order statistics, U₍ᵢ₎ ~ Beta(i, n−i+1) → Φ⁻¹(qbeta(α/2…1−α/2)) mapped through the qqline (not a simulation; not simultaneous). Points outside are flagged.
  • Detrended: sample − qqline(z), the envelope shifted the same way.
# Normal Q–Q plot — Codesplash Chart Lab (recipe "qq")
# controls: envelope=true, level=0.95, detrended=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("qq-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def ppoints(n):
    """R ppoints(n): (i − a)/(n + 1 − 2a) with a = 3/8 for n ≤ 10, else 1/2."""
    a = 3 / 8 if n <= 10 else 0.5
    return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)

x = np.sort(df["residual"].dropna().to_numpy(dtype=float))
n = x.size
z = stats.norm.ppf(ppoints(n))  # theoretical normal quantiles at R's plotting positions
q1, q3 = np.quantile(x, [0.25, 0.75])  # type 7, like R qqline
slope = (q3 - q1) / (stats.norm.ppf(0.75) - stats.norm.ppf(0.25))
intercept = q1 - slope * stats.norm.ppf(0.25)
line = intercept + slope * z
# exact pointwise envelope: U(i) ~ Beta(i, n − i + 1), through Φ⁻¹ and the qqline (not simultaneous)
i = np.arange(1, n + 1)
alpha = 1 - 0.95
lo = intercept + slope * stats.norm.ppf(stats.beta.ppf(alpha / 2, i, n - i + 1))
hi = intercept + slope * stats.norm.ppf(stats.beta.ppf(1 - alpha / 2, i, n - i + 1))
outside = (x < lo) | (x > hi)
y, ref = x, line

fig, ax = plt.subplots(figsize=(6, 5))
ax.fill_between(z, lo, hi, color=PALETTE[0], alpha=0.15, linewidth=0, label=f"{1 - alpha:.0%} pointwise envelope")
ax.plot(z, ref, color=plt.rcParams["text.color"], linewidth=1, label="qqline (quartiles)")
ax.scatter(z[~outside], y[~outside], s=14, color=PALETTE[0], linewidths=0)
ax.scatter(z[outside], y[outside], s=18, color=PALETTE[3], linewidths=0, label=f"{outside.sum()} outside the envelope")
ax.set_xlabel("Theoretical quantiles (normal)")
ax.set_ylabel("residual")
ax.legend()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads qq-demo.csv · app theme from the optional codesplash helper

  • DuckDB has no inverse normal function, so there is no geometry SQL for Q–Q plots.

Distributions

svgbrushable#pp

Normal P–P plot

Does the centre of a distribution match a normal shape?

Demo data · seed 20261101 · 250 rows · default settings · 640 × 360

How to read it

  1. Points on the diagonal: the fitted normal's probabilities match the data's.
  2. An S shape around the diagonal means the data's centre differs from a normal's.
  3. Use the band to judge whether a departure is more than noise.
  1. Callout 1: Diagonal: where the data and the fitted normal agree.
  2. Callout 2: Sagging below the diagonal in the middle: a shape mismatch near the centre.
  3. Callout 3: Band: the range noise alone would allow.

Watch out

  • It is least sensitive in the tails. Use a Q–Q plot when the tails matter.

Defaults

95% Kolmogorov band
On
Shade the range a correct normal fit would stay inside 95% of the time.

Pinned in the code

  • x: plotting positions R `ppoints(n)`; y: Φ((x₍ᵢ₎ − x̄)/s) with s using n − 1.
  • Band: ±ε around y = x with the DKW constant ε = √(ln(2/0.05)/(2n)); with estimated mean and SD it is conservative (Lilliefors) — a visual guide, not a test.
# Normal P–P plot — Codesplash Chart Lab (recipe "pp")
# controls: band=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("pp-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def ppoints(n):
    """R ppoints(n): (i − a)/(n + 1 − 2a) with a = 3/8 for n ≤ 10, else 1/2."""
    a = 3 / 8 if n <= 10 else 0.5
    return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)

x = np.sort(df["repair_h"].dropna().to_numpy(dtype=float))
n = x.size
p = ppoints(n)  # theoretical: R plotting positions
F = stats.norm.cdf((x - x.mean()) / x.std(ddof=1))  # empirical: Φ((x − x̄)/s), s with n − 1

fig, ax = plt.subplots(figsize=(5.5, 5))
eps = np.sqrt(np.log(2 / 0.05) / (2 * n))  # DKW constant: a visual guide (conservative with estimated mean/SD)
t = np.linspace(0, 1, 101)
ax.fill_between(t, np.clip(t - eps, 0, 1), np.clip(t + eps, 0, 1), color=PALETTE[0], alpha=0.15, linewidth=0, label="95% Kolmogorov band")
ax.plot([0, 1], [0, 1], color=plt.rcParams["text.color"], linewidth=1)
ax.scatter(p, F, s=12, color=PALETTE[0], linewidths=0)
ax.set_xlabel("Theoretical cumulative probability")
ax.set_ylabel("Empirical: Φ((repair_h − mean) / sd)")
ax.legend()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads pp-demo.csv · app theme from the optional codesplash helper

  • DuckDB has no normal CDF function, so there is no geometry SQL for P–P plots.

Distributions

svgbrushable#raincloud

Raincloud

How do groups compare in shape, summary and individual observations at once?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read the cloud for each group's shape.
  2. Read the box for its median and middle half.
  3. Read the rain to check the summaries against the real observations and spot gaps or clumps.
  1. Callout 1: Cloud: the shape of the distribution.
  2. Callout 2: Box: the median and the middle half.
  3. Callout 3: Rain: one dot per observation, jittered vertically.

Watch out

  • The vertical jitter in the rain carries no meaning; only horizontal position does.

Defaults

Cloud (half violin)
On
Show the smoothed shape of each group.
Box plot
On
Show the median and the middle half of each group.
Raw points
On
Show each observation behind the summary.
Bandwidth × adjust
1
Multiply the bandwidth: below 1 shows more detail and noise, above 1 gives a smoother curve.
Range 0.25 to 4, step 0.25

Pinned in the code

  • Cloud: Gaussian KDE (bw.nrd0 × adjust) over [min − bw, max + bw], scaled to the tallest group.
  • Box: type-7 quartiles, whiskers to the most extreme points within 1.5 × IQR.
  • Rain: deterministic seeded vertical jitter (identical across renders and exports).
# Raincloud — Codesplash Chart Lab (recipe "raincloud")
# controls: cloud=true, box=true, points=true, adjust=1
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cbook

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("raincloud-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["condition"] = pd.Categorical(df["condition"].astype("string"), categories=["Congruent", "Neutral", "Incongruent"])

def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

def kde(v, h, grid):
    """Gaussian kernel density by direct summation on `grid` (the app's method)."""
    v = np.asarray(v, dtype=float)
    grid = np.asarray(grid, dtype=float)
    out = np.empty(grid.size)
    for i in range(0, grid.size, 32):  # chunks keep memory small for large samples
        z = (grid[i:i + 32, None] - v[None, :]) / h
        out[i:i + 32] = np.exp(-0.5 * z * z).sum(axis=1)
    return out / (v.size * h * np.sqrt(2 * np.pi))

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "rt_ms", "condition", max_levels=8)
k = len(parts)
clouds = []
for label, v in parts:
    h = bandwidth(v, "nrd0") * 1
    grid = np.linspace(v.min() - h, v.max() + h, 96)  # cloud over [min − bw, max + bw]
    clouds.append((grid, kde(v, h, grid) if v.size > 1 else np.zeros(96)))
top = max(d.max() for _, d in clouds) or 1.0  # scaled to the tallest group
rng = np.random.default_rng(11)  # rain jitter is cosmetic (vertical only); values are never moved

fig, ax = plt.subplots(figsize=(7, 1.2 + 1.2 * k))
for i, ((label, v), (grid, d)) in enumerate(zip(parts, clouds)):
    base = k - 1 - i  # first group on top
    color = PALETTE[i % len(PALETTE)]
    ax.fill_between(grid, base, base + 0.45 * d / top, color=color, alpha=0.5, linewidth=0)
    # box: type-7 quartiles, whiskers within 1.5 × IQR
    ax.bxp([cbook.boxplot_stats(v, whis=1.5)[0]], positions=[base - 0.1], widths=0.08, orientation="horizontal",
           showfliers=False, patch_artist=True, boxprops=dict(facecolor=plt.rcParams["axes.facecolor"], edgecolor=plt.rcParams["text.color"]),
           medianprops=dict(color=plt.rcParams["text.color"]), manage_ticks=False)
    ax.scatter(v, base - 0.27 + rng.uniform(-0.07, 0.07, v.size), s=7, color=color, alpha=0.6, linewidths=0)
ax.set_yticks([k - 1 - i for i in range(k)], [label for label, _ in parts])
ax.grid(axis="y", visible=False)
ax.set_xlabel("rt_ms")
plt.show()

Needs pandas, numpy, matplotlib · reads raincloud-demo.csv · app theme from the optional codesplash helper

  • Rain jitter is drawn from a seeded generator in each language, so dot positions differ from the app; values (and every box and cloud) are identical.

Distributions

svgbrushable#strip

Strip plot with mean ± CI

What do all the observations look like per group, next to the group mean and its uncertainty?

Demo data · seed 20261101 · 100 rows · default settings · 640 × 360

How to read it

  1. Look at the dots first: each one is an observation, spread sideways only so they don't overlap.
  2. Read the bar beside them: the group mean with its interval.
  3. Compare intervals with the spread of the dots: a narrow interval is about the mean, not about individual values.
  1. Callout 1: Each dot is one observation.
  2. Callout 2: The bar: mean and its interval.
  3. Callout 3: A wide spread in one group: does the mean describe it well?

Watch out

  • Check which interval is shown: a standard deviation, a standard error and a confidence interval have very different widths.

Defaults

Interval
95% CI (t)
What the interval shows: a confidence interval, a standard error or a standard deviation.
Also: ± 1 SE · ± 1 SD · None
Jitter width
0.5
How far points spread sideways, so they don't overlap; the spread has no meaning.
Range 0 to 1, step 0.1
Point radius
2.5
The size of each point.
Range 1 to 5, step 0.5

Pinned in the code

  • Interval: x̄ ± t(0.975, n−1)·s/√n (s with n − 1); SE = s/√n; SD = s. Say which one in captions — they are not interchangeable.
  • Jitter is deterministic (seeded per group) and only horizontal; values are never moved.
# Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")
# controls: interval=ci, jitter=0.5, size=2.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("strip-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Phosphate", "Both"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "yield_t_ha", "fertilizer", max_levels=12)
rng = np.random.default_rng(23)  # horizontal jitter only (cosmetic); values are never moved
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    ax.scatter(i + rng.uniform(-0.5 / 2, 0.5 / 2, v.size), v, s=(2 * 2.5) ** 2, color=PALETTE[i % len(PALETTE)], alpha=0.55, linewidths=0)
    n, m, s = v.size, v.mean(), v.std(ddof=1)
    if n > 1:
        half = stats.t.ppf(0.975, n - 1) * s / np.sqrt(n)  # 95% CI: t(0.975, n − 1) · s/√n
        ax.errorbar(i, m, yerr=half, fmt="o", color=plt.rcParams["text.color"], capsize=4, markersize=5, zorder=3)
ax.set_xticks(range(len(parts)), [label for label, _ in parts])
ax.set_xlabel("fertilizer")
ax.set_ylabel("yield_t_ha")
ax.set_title("mean ± 95% CI (t)", loc="left", fontsize=9)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads strip-demo.csv · app theme from the optional codesplash helper

  • Jitter comes from a seeded generator in each language, so dot positions differ from the app; values, means and intervals are identical.

Distributions

svgbrushable#beeswarm

Beeswarm

Where exactly does every observation sit, without overlap, for small to medium groups?

Demo data · seed 20261101 · 210 rows · default settings · 640 × 360

How to read it

  1. Read each dot's vertical position: it sits at its exact value.
  2. The sideways spread only avoids overlap, so a wide swarm means many rows near that value.
  3. Compare the median lines across groups, then the swarm shapes.
  1. Callout 1: The line: this group's median.
  2. Callout 2: A wide swarm: many values close together.
  3. Callout 3: Compare swarm positions across groups.

Watch out

  • Above about 1,000 points per group the swarm overflows. Use a violin or a box plot.

Defaults

Point radius
3
The size of each point.
Range 1.5 to 6, step 0.5
Median line
On
Mark each group's median.

Pinned in the code

  • Greedy swarm in value order: each point takes the smallest sideways offset (alternating sides) that keeps circles of radius r apart; values are never shifted (`beeswarm` swarm method, seaborn `swarmplot`).
  • If a swarm is wider than its band it is compressed horizontally (positions along the value axis are exact).
  • Median: type 7.
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")
# controls: size=3, median=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

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("beeswarm-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["ward"] = pd.Categorical(df["ward"].astype("string"), categories=["Cardiology", "Maternity", "Pediatrics"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "age", "ward", max_levels=8)
long = pd.DataFrame({"group": np.repeat([label for label, _ in parts], [v.size for _, v in parts]), "value": np.concatenate([v for _, v in parts])})
fig, ax = plt.subplots(figsize=(7, 4))
# seaborn's swarm: greedy, values never shifted (the app's layout is the same idea, in its own pixel grid)
sns.swarmplot(data=long, x="group", y="value", hue="group", order=[label for label, _ in parts], palette=[PALETTE[i % len(PALETTE)] for i in range(len(parts))],
              size=3, legend=False, warn_thresh=1, ax=ax)
for i, (_, v) in enumerate(parts):
    ax.hlines(np.median(v), i - 0.4, i + 0.4, color=plt.rcParams["text.color"], linewidth=1.5)  # type-7 median
ax.set_xlabel("ward")
ax.set_ylabel("age")
plt.show()

Needs pandas, numpy, matplotlib, seaborn · reads beeswarm-demo.csv · app theme from the optional codesplash helper

  • matplotlib uses seaborn's swarmplot; plotly and R port the app's greedy layout for a 640 × 360 px plot. Offsets are cosmetic — values are never shifted.
  • A swarm is a point layout, not an aggregate, so there is no geometry SQL.

Distributions

svgbrushable#dot-plot

Dot plot (Wilkinson)

What does a small sample look like, observation by observation?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Count the dots: each one is one observation, stacked in its bin.
  2. Look at the stack heights for the shape, as you would on a histogram.
  3. Notice isolated dots: in a small sample each one matters.
  1. Callout 1: A tall stack: many observations share nearly the same value.
  2. Callout 2: An isolated dot: one observation far from the rest.

Watch out

  • Stacks shift a little with the bin width: read counts, not exact positions.

Defaults

Range ÷ binwidth
30
How many bins fit across the range: more bins give more detail and shorter stacks.
Range 5 to 80, step 1

Pinned in the code

  • Binning: Wilkinson dot-density (ggplot2 `geom_dotplot(method = "dotdensity")`): scan sorted values; a value ≥ the current bin end starts a bin [x, x + w).
  • Stack centre = midpoint of the first and last value in the bin; binwidth w = range / 30 by default.
  • Dot diameter = w in x units, shrunk if the tallest stack would not fit (stacks never overflow).
# Dot plot (Wilkinson) — Codesplash Chart Lab (recipe "dot-plot")
# controls: bins=30
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("dot-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def dot_density(x, w):
    """Wilkinson dot-density binning (ggplot2 method = "dotdensity"): scan the sorted values;
    a value ≥ the current bin end starts a new bin [x, x + w). Returns (centre, count) per stack."""
    stacks, end = [], -np.inf
    for v in np.sort(x):
        if v >= end:
            stacks.append([])
            end = v + w
        stacks[-1].append(v)
    return [((s[0] + s[-1]) / 2, len(s)) for s in stacks]  # centre = midpoint of first and last value

x = df["sleep_h"].dropna().to_numpy(dtype=float)
w = (x.max() - x.min()) / 30  # binwidth = range / 30
stacks = dot_density(x, w)
tallest = max(count for _, count in stacks)

fig, ax = plt.subplots(figsize=(7, 4))
for centre, count in stacks:
    for j in range(count):  # dot diameter = binwidth in x units
        ax.add_patch(plt.Circle((centre, (j + 0.5) * w), 0.47 * w, color=PALETTE[0], linewidth=0))
ax.set_xlim(x.min() - w, x.max() + w)
ax.set_ylim(0, max(tallest * w, (x.max() - x.min()) / 4))
ax.set_aspect("equal")
ax.yaxis.set_visible(False)
ax.grid(axis="y", visible=False)
ax.set_xlabel("sleep_h")
plt.show()

Needs pandas, numpy, matplotlib · reads dot-plot-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#boxen

Letter-value (boxen) plot

How do the tails of large samples compare across groups?

Demo data · seed 20261101 · 4,500 rows · default settings · 640 × 360

How to read it

  1. Find the median line, then the widest box: it holds the middle half.
  2. Each narrower box halves the tail again, so the stack shows how the tails behave.
  3. Compare how quickly boxes shrink across groups: slow shrinking means a long tail.
  1. Callout 1: Widest box: the middle half.
  2. Callout 2: Each narrower box covers half of what remains in the tail.
  3. Callout 3: Dots: values beyond the last box.

Watch out

  • It needs large samples. With a few hundred rows the outer boxes rest on a handful of values.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Letter values at tail probabilities 2^−(d+1), d = 1…k (fourths, eighths, sixteenths…), type-7 quantiles.
  • Depth k = ⌊log₂ n − log₂(0.007·n)⌋ + 1 so about 0.7 % of points remain beyond the deepest box and are drawn as outliers (Hofmann et al. "tail" stopping rule).
  • Box width and opacity shrink with depth; the line is the median.
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgb

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("boxen-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=["North", "South", "West"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

def letter_values(v, outlier_share=0.007):
    """Letter values (Hofmann, Wickham & Kafadar 2017): tail probabilities 2^−(d+1), d = 1…k, type 7;
    k = ⌊log₂ n − log₂ max(1, 0.007·n)⌋ + 1 leaves about 0.7 % of points beyond the deepest box."""
    n = v.size
    k = max(1, int(np.floor(np.log2(n) - np.log2(max(1.0, n * outlier_share)))) + 1)
    return [(d, *np.quantile(v, [2.0 ** -(d + 1), 1 - 2.0 ** -(d + 1)])) for d in range(1, k + 1)]

parts = [(label, v) for label, v in groups(df, "order_value", "region", max_levels=8) if v.size > 3]
bg = np.array(to_rgb(plt.rcParams["axes.facecolor"]))
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    color = np.array(to_rgb(PALETTE[i % len(PALETTE)]))
    boxes = letter_values(v)
    k = len(boxes)
    for d, lo, hi in reversed(boxes):  # deepest first, so the wider, darker central boxes sit on top (as the app draws)
        half = 0.4 * (1 - 0.7 * (d - 1) / k)
        share = (92 - 72 * (d - 1) / max(1, k - 1)) / 100
        ax.add_patch(plt.Rectangle((i - half, lo), 2 * half, hi - lo, color=color * share + bg * (1 - share), linewidth=0))
    ax.hlines(np.median(v), i - 0.4, i + 0.4, color=plt.rcParams["text.color"], linewidth=2)
    _, lo, hi = boxes[-1]
    out = v[(v < lo) | (v > hi)]  # beyond the deepest box
    ax.scatter(np.full(out.size, i), out, s=8, color=color, alpha=0.6, linewidths=0)
ax.autoscale_view()
ax.set_xlim(-0.6, len(parts) - 0.4)
ax.set_xticks(range(len(parts)), [label for label, _ in parts])
ax.set_xlabel("region")
ax.set_ylabel("order_value")
plt.show()

Needs pandas, numpy, matplotlib · reads boxen-demo.csv · app theme from the optional codesplash helper

  • seaborn's boxenplot(k_depth="proportion") rounds the depth slightly differently, so the code draws the letter values itself.

Distributions

svgbrushable#freq-poly

Frequency polygon

How do the distributions of several groups compare on the same bins?

Demo data · seed 20261101 · 860 rows · default settings · 640 × 360

How to read it

  1. Follow one line at a time: its height at each point is the count or share in that bin.
  2. Compare where each group peaks.
  3. Use shares rather than counts when group sizes differ.
  1. Callout 1: A peak: the most common range for this group.
  2. Callout 2: Another group peaks further right: larger values.
  3. Callout 3: A line resting on zero: no values there.

Watch out

  • Lines imply continuity between bins; a sharp peak may only be one bin.

Defaults

Bin rule
Freedman–Diaconis
How the bin width is chosen. Freedman–Diaconis resists outliers; Sturges suits small, near-normal data.
Also: Sturges · Scott · Rice · Square root · Doane
Y axis
Percent of group
Show counts, density or shares on the y axis.
Also: Count · Density

Pinned in the code

  • Bins: one shared set of equal-width numpy-style edges over the pooled range (rule on the pooled data), [a, b) with the last bin closed.
  • Polygon through bin midpoints, closed to zero half a bin beyond each end (ggplot2 `geom_freqpoly`).
  • Percent = bin count / group n, so groups of different sizes are comparable.
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")
# controls: bins=fd, value=percent
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("freq-poly-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["mode"] = pd.Categorical(df["mode"].astype("string"), categories=["Car", "Transit", "Bike"])

def groups(frame, value, group=None, max_levels=12):
    """(label, values) per group in level order; rows missing the value or the group are dropped."""
    if group is None:
        return [(value, frame[value].dropna().to_numpy(dtype=float))]
    d = frame[[value, group]].dropna()
    out = []
    for level in list(d[group].cat.categories)[:max_levels]:
        v = d.loc[d[group] == level, value].to_numpy(dtype=float)
        if v.size:
            out.append((str(level), v))
    return out

parts = groups(df, "commute_min", "mode", max_levels=8)
pooled = np.concatenate([v for _, v in parts])
edges = np.histogram_bin_edges(pooled, bins="fd")  # one shared set of numpy edges on the pooled data
w = edges[1] - edges[0]
xs = np.r_[edges[0] - w / 2, (edges[:-1] + edges[1:]) / 2, edges[-1] + w / 2]  # closed to zero half a bin beyond each end
fig, ax = plt.subplots(figsize=(7, 4))
for i, (label, v) in enumerate(parts):
    counts, _ = np.histogram(v, bins=edges)  # [a, b), last bin closed
    many = len(parts) > 1  # several groups: a dash and a dot shape per group, as in the app
    ax.plot(xs, np.r_[0, counts / v.size * 100, 0], color=PALETTE[i % len(PALETTE)], linewidth=2, linestyle=SERIES_DASHES[i % 8] if many else "-", marker=SERIES_MARKERS[i % 8] if many else "o", markersize=4 if many else 3, markevery=slice(1, -1), label=label)
ax.set_xlabel("commute_min")
ax.set_ylabel("Percent of group")
if len(parts) > 1:
    ax.legend()
plt.show()

Needs pandas, numpy, matplotlib · reads freq-poly-demo.csv · app theme from the optional codesplash helper

Distributions

svg#stem-leaf

Stem-and-leaf

What are the actual values of a small sample, shown as a sideways histogram?

Demo data · seed 20261101 · 48 rows · default settings · 640 × 360

How to read it

  1. Read a row as stem plus leaf: the stem is the leading digit and each leaf is the next digit of one value.
  2. Turn your head sideways: the leaf lengths form a histogram.
  3. Check the note above the display for where the decimal point falls.
  1. Callout 1: Stem: the leading digit.
  2. Callout 2: Leaves: the next digit of each value in this row.
  3. Callout 3: The longest rows: where values concentrate.

Watch out

  • Only useful for small samples: beyond a hundred or so values use a histogram.

Defaults

Scale (stem length)
1
A larger scale spreads values over more stems.
Range 0.5 to 4, step 0.5

Pinned in the code

  • Exact port of R's `stem(x, scale, width = 80, atom = 1e-08)` (graphics/src/stem.c): line width and stem unit (×1, ×2 or ×5 splits) chosen from the range and n; leaves are rounded, not truncated.
  • The note says where the decimal point sits relative to the bar; the right column is the line count.
# Stem-and-leaf — Codesplash Chart Lab (recipe "stem-leaf")
# controls: scale=1
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("stem-leaf-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def stem(x, scale=1.0, width=80, atom=1e-8):
    """Port of R's stem() (src/library/graphics/src/stem.c): returns (note, lines)."""
    x = np.sort(np.asarray(x, dtype=float))
    x = x[np.isfinite(x)]
    n = x.size
    if n <= 1:
        return "", []
    if x[-1] > x[0]:
        r = atom + (x[-1] - x[0]) / scale
        c = 10.0 ** int(1 - np.floor(np.log10(r) + 1e-7))
        mm = min(2, max(0, int(r * c / 25)))
        k = 3 * mm + 2 - int(150 / (n + 50))
        if (k - 1) * (k - 2) * (k - 5) == 0:
            c *= 10
        x1 = max(abs(x[0]), abs(x[-1]))
        while x1 * c > 2147483647:
            c /= 10
    else:
        r = atom + abs(x[0]) / scale
        c = 10.0 ** int(1 - np.floor(np.log10(r) + 1e-7))
        k = 2
    mu = 10
    if k * (k - 4) * (k - 8) == 0:
        mu = 5
    if (k - 1) * (k - 5) * (k - 6) == 0:
        mu = 20
    lo = np.floor(x[0] * c / mu) * mu
    hi = np.floor(x[-1] * c / mu) * mu
    ldigits = int(np.floor(np.log10(-lo))) + 1 if lo < 0 else 0
    hdigits = int(np.floor(np.log10(hi))) if hi > 0 else 0
    ndigits = max(ldigits, hdigits)
    if lo < 0 and np.floor(x[0] * c) == lo:
        lo -= mu
    hi = lo + mu
    if np.floor(x[0] * c + 0.5) > hi:
        lo = hi
        hi = lo + mu
    pdigits = 1 - int(np.floor(np.log10(c) + 0.5))
    if pdigits == 0:
        note = "The decimal point is at the |"
    else:
        note = f"The decimal point is {abs(pdigits)} digit(s) to the {'right' if pdigits > 0 else 'left'} of the |"

    def stem_text(close, dist):
        s = "-0" if int(close / 10) == 0 and dist < 0 else str(int(close / 10))
        return s.rjust(ndigits)

    lines, i = [], 0
    while True:
        label = stem_text(int(hi), int(lo)) if lo < 0 else stem_text(int(lo), int(hi))
        leaves, j = "", 0
        while i < n:
            xi = int(x[i] * c - 0.5) if x[i] < 0 else int(x[i] * c + 0.5)
            if (hi == 0 and x[i] >= 0) or (lo < 0 and xi > hi) or (lo >= 0 and xi >= hi):
                break
            j += 1
            if j <= width - 12:
                leaves += str(abs(xi) % 10)
            i += 1
        lines.append(f"  {label} | {leaves}" + (f"+{j - width}" if j > width else ""))
        if i >= n:
            break
        hi += mu
        lo += mu
    return note, lines

note, lines = stem(df["score"].dropna().to_numpy(dtype=float), scale=1)
text = "\n".join([note, ""] + lines)
print(text)
fig, ax = plt.subplots(figsize=(7, 0.8 + 0.2 * (len(lines) + 2)))
ax.axis("off")
ax.text(0, 1, text, family="monospace", va="top", ha="left", fontsize=9, transform=ax.transAxes)
ax.set_title("Stem-and-leaf display of score", loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads stem-leaf-demo.csv · app theme from the optional codesplash helper

  • A stem-and-leaf display is text: plotly has no equivalent and the leaves are not SQL-friendly, so only matplotlib (a port of R's stem()) and R are emitted.

Distributions

svgbrushable#hist2d

2-D histogram

Where are two numeric variables jointly concentrated when there are too many points to plot?

Demo data · seed 20261101 · 4,000 rows · default settings · 640 × 360

How to read it

  1. Find the darkest cells: that is where most rows sit.
  2. Read the overall tilt of the dark area for the direction of the relationship.
  3. Check the colour bar: it tells you how many rows each shade means.
  1. Callout 1: Darkest cells: where most rows fall.
  2. Callout 2: Colour bar: rows per cell.

Watch out

  • A linear colour scale hides sparse cells; try the log scale to see outliers.
  • Cell size changes the picture. Try other bin counts before describing a pattern.

Defaults

Bins (x)
30
How many cells along the x axis.
Range 5 to 200, step 1
Bins (y)
20
How many cells along the y axis.
Range 5 to 200, step 1
Colour scale
Linear
Linear shows the dense cells; log or square root reveals the sparse ones too.
Also: log(1 + count)

Pinned in the code

  • numpy `histogram2d(x, y, bins=[kx, ky])`: equal-width edges over [min, max] per axis, bins [a, b) with the last bin closed; rows with a missing coordinate are dropped.
  • Colour: sequential ramp on count (or log(1 + count)); empty cells show the ramp's low end.
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")
# controls: binsX=30, binsY=20, scale=linear
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("hist2d-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"]  # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
d = df[["height_cm", "weight_kg"]].dropna()
H, xe, ye = np.histogram2d(d["height_cm"], d["weight_kg"], bins=[30, 20])  # equal-width edges over [min, max], [a, b) with the last closed
Z = H
fig, ax = plt.subplots(figsize=(7, 4.5))
mesh = ax.pcolormesh(xe, ye, Z.T, cmap=CMAP)  # empty cells show the ramp's low end
fig.colorbar(mesh, ax=ax, label="count")
ax.grid(False)
ax.set_xlabel("height_cm")
ax.set_ylabel("weight_kg")
plt.show()

Needs pandas, numpy, matplotlib · reads hist2d-demo.csv · app theme from the optional codesplash helper

Distributions

svgbrushable#hexbin

Hexbin

Where do many points concentrate in two dimensions, without the square-bin artefacts?

Demo data · seed 20261101 · 5,000 rows · default settings · 640 × 360

How to read it

  1. Find the darkest hexagons: the densest part of the data.
  2. Read the shape the hexagons trace for the relationship.
  3. Look for isolated light hexagons far from the main cloud: rare combinations worth checking.
  1. Callout 1: Darkest hexagons: the most rows.
  2. Callout 2: Isolated hexagons: rare combinations.
  3. Callout 3: Colour bar: rows per hexagon.

Watch out

  • Without the log scale a few dense hexagons can wash out everything else.

Defaults

Hexes across
30
How many hexagons span the width: more gives finer detail and more noise.
Range 8 to 80, step 1
Log colour scale
On
Colour by the logarithm of the count, so sparse areas stay visible.

Pinned in the code

  • Lattice of matplotlib `hexbin(gridsize = nx)`: ny = ⌊nx/√3⌋, two offset rectangular lattices; each point goes to the nearer centre under (Δx)² + 3(Δy)² in grid units; x padded by 1e−9 of the range.
  • Pointy-top hexagons with vertices at (±sx/2, ±sy/6) and (0, ±sy/3) in data units; empty hexes are not drawn (mincnt = 1).
  • Colour: sequential ramp on count or log(1 + count).
# Hexbin — Codesplash Chart Lab (recipe "hexbin")
# controls: gridsize=30, log=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("hexbin-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"]  # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
d = df[["distance_km", "fare_usd"]].dropna()
fig, ax = plt.subplots(figsize=(7, 4.5))
# matplotlib's own hexbin lattice — the app reproduces it; empty hexes are not drawn (mincnt=1)
hb = ax.hexbin(d["distance_km"], d["fare_usd"], gridsize=30, mincnt=1, bins="log", cmap=CMAP,
               linewidths=0.2, edgecolors=plt.rcParams["axes.facecolor"])
fig.colorbar(hb, ax=ax, label="count (log scale)")
ax.grid(False)
ax.set_xlabel("distance_km")
ax.set_ylabel("fare_usd")
plt.show()

Needs pandas, numpy, matplotlib · reads hexbin-demo.csv · app theme from the optional codesplash helper

  • matplotlib's hexbin is the reference the app reproduces. plotly has no hexbin trace, so hexagons are drawn as filled shapes in 9 colour steps; ggplot2 uses polygons (no hexbin package needed).
  • Exact ties at a half-way grid position round half-to-even in numpy, R and the SQL (round_even), but half-up in the app — a point there can land in the neighbouring hex.

Distributions

svgbrushable#density-2d

2-D density contours

What is the smooth joint shape of two variables — how many modes, which direction?

Demo data · seed 20261101 · 500 rows · default settings · 640 × 360

How to read it

  1. Read the bands like a contour map: each inner band is denser than the one around it.
  2. Count the separate peaks: each may be a distinct group.
  3. Read each band's orientation for how the two variables move together inside that group.
  1. Callout 1: The innermost band: the top of this hill.
  2. Callout 2: A second hill: a second cluster of rows.
  3. Callout 3: Colour bar: estimated density.

Watch out

  • Smoothing can join separate groups or draw density where there are no rows. Turn on the points to check.

Defaults

Contour levels
7
How many contour bands to draw.
Range 3 to 14, step 1
Grid points per axis
60
How finely the density is computed; more is slower and smoother.
Range 25 to 120, step 5
Filled bands
On
Fill between contours rather than drawing lines only.
Points
On
Show the individual points as well.

Pinned in the code

  • MASS `kde2d`: product Gaussian kernel with SDs h/4 where h = `bandwidth.nrd` = 4·1.06·min(s, IQR/1.34)·n^(−1/5) per axis (type-7 quartiles).
  • Grid: n × n points over the data range expanded by 15 % per side so outer contours close (kde2d's default lims are the bare range).
  • Bands: marching squares (d3-contour) at k equally spaced levels max·i/(k + 1), i = 1…k, linear interpolation between grid points.
# 2-D density contours — Codesplash Chart Lab (recipe "density-2d")
# controls: levels=7, grid=60, fill=true, points=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("density-2d-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"]  # the app's sequential ramp
CMAP = LinearSegmentedColormap.from_list("codesplash", SEQ)
def bandwidth_nrd(v):
    """MASS::bandwidth.nrd: 4 · 1.06 · min(sd, IQR/1.34) · n^(−1/5), quartiles type 7."""
    q1, q3 = np.quantile(v, [0.25, 0.75])
    sd = v.std(ddof=1)
    return 4 * 1.06 * min(sd, (q3 - q1) / 1.34 or sd) * v.size ** (-1 / 5)


def kde2d(x, y, n, lims):
    """MASS::kde2d: product Gaussian kernel with standard deviations h/4 on an n × n grid."""
    hx, hy = bandwidth_nrd(x) / 4, bandwidth_nrd(y) / 4
    gx, gy = np.linspace(lims[0], lims[1], n), np.linspace(lims[2], lims[3], n)
    ax_ = np.exp(-0.5 * ((gx[:, None] - x[None, :]) / hx) ** 2) / np.sqrt(2 * np.pi)
    ay_ = np.exp(-0.5 * ((gy[:, None] - y[None, :]) / hy) ** 2) / np.sqrt(2 * np.pi)
    return gx, gy, ax_ @ ay_.T / (x.size * hx * hy)  # z[i, j] at (gx[i], gy[j])

d = df[["duration_min", "waiting_min"]].dropna()
xs, ys = d["duration_min"].to_numpy(dtype=float), d["waiting_min"].to_numpy(dtype=float)
ex, ey = 0.15 * np.ptp(xs), 0.15 * np.ptp(ys)  # grid over the range expanded by 15 % per side so contours close
gx, gy, z = kde2d(xs, ys, 60, (xs.min() - ex, xs.max() + ex, ys.min() - ey, ys.max() + ey))
levels = z.max() * np.arange(1, 7 + 1) / (7 + 1)  # equally spaced levels max·i/(k + 1)

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.contourf(gx, gy, z.T, levels=[*levels, z.max()], cmap=CMAP, alpha=0.9)
ax.contour(gx, gy, z.T, levels=levels, colors=plt.rcParams["text.color"], linewidths=0.6, alpha=0.6)
ax.scatter(xs, ys, s=4, color=PALETTE[0], alpha=0.35, linewidths=0)
ax.set_xlabel("duration_min")
ax.set_ylabel("waiting_min")
plt.show()

Needs pandas, numpy, matplotlib · reads density-2d-demo.csv · app theme from the optional codesplash helper

  • R uses MASS::kde2d (ships with R); Python ports it so both grids and contour levels match the app.

Categories & comparison

Counts, shares and summaries across groups.

14

Categories & comparison

svgbrushable#bar

Bar chart

How often does each category occur?

Demo data · seed 20261101 · 2,000 rows · default settings · 640 × 360

How to read it

  1. Compare bar lengths: they all start at zero, so length is the value.
  2. Read from the longest down for the ranking.
  3. Check whether an “Other” bar groups levels beyond the top ones.
  1. Callout 1: Bar length: the count or share.
  2. Callout 2: The small categories together may still matter.

Watch out

  • Never cut the y axis on a bar chart: bars encode length, so a truncated axis exaggerates differences.

Defaults

Value
Count
Show counts or shares.
Also: Percent
Orientation
Columns
Draw bars vertically or horizontally; horizontal suits long labels.
Also: Bars
Order
By frequency
How rows or groups are ordered.
Also: Alphabetical
Top levels
12
How many levels to show; the rest are grouped into Other.
Range 3 to 30, step 1
Colour
Single
How bars or lines are coloured.
Also: By level
Value labels
On
Print each value on the chart.

Pinned in the code

  • Levels sorted by descending count (ties alphabetical) unless an order is declared in the data dictionary.
  • Levels beyond the top k are pooled into “Other” (drawn in neutral grey); missing values are excluded and reported separately.
  • Percent = count / non-missing rows.
# Bar chart — Codesplash Chart Lab (recipe "bar")
# controls: value=count, orientation=vertical, order=freq, top=12, color=single, labels=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("bar-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

counts = df["channel"].dropna().astype(str).value_counts()  # missing values excluded
counts = counts.sort_values(ascending=False, kind="stable")  # by frequency
if len(counts) > 12:  # pool levels beyond the top 12 into "Other"
    top = counts.sort_values(ascending=False).iloc[:12]
    counts = pd.concat([counts[counts.index.isin(top.index)], pd.Series({"Other": counts.drop(top.index).sum()})])
values = counts
colors = [PALETTE[0] if k != "Other" else "#9aa0a6" for k in values.index]

fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.bar(values.index, values.values, color=colors)
ax.bar_label(bars, fmt="%d", padding=2, fontsize=8)
ax.set_ylabel("Count")
ax.tick_params(axis="x", labelrotation=30)
ax.set_xlabel("channel")
plt.show()

Needs pandas, numpy, matplotlib · reads bar-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#bar-grouped

Grouped bars

How do category counts compare across subgroups?

Demo data · seed 20261101 · 1,200 rows · default settings · 640 × 360

How to read it

  1. Compare the same colour across clusters to see how one subgroup changes across categories.
  2. Compare colours within a cluster to see how subgroups differ inside one category.
  3. Use shares within subgroup when subgroup sizes differ.
  1. Callout 1: One cluster: one category, split by subgroup.
  2. Callout 2: Same colour, next cluster: how that subgroup changes.

Watch out

  • More than about four subgroups becomes hard to compare. Try small multiples.

Defaults

Value
Count
Show counts or shares.
Also: % within subgroup
Top categories
8
How many categories to show; the rest are grouped.
Range 3 to 20, step 1
Value labels
Off
Print each value on the chart.

Pinned in the code

  • Category levels follow the data dictionary order, else descending frequency; levels beyond the top k (6 for subgroups) pool into “Other”, drawn in neutral grey.
  • “% within subgroup” divides each count by its subgroup total, so every colour sums to 100 % across categories (column percentages of the category × subgroup table).
  • Rows with a missing category or subgroup are excluded.
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")
# controls: value=count, top=8, labels=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("bar-grouped-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro", "Enterprise"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def crosstab(frame, a, b, max_a, max_b):
    """a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last."""
    d = frame[[a, b]].dropna()
    pooled, cats = {}, []
    for col, cap in ((a, max_a), (b, max_b)):
        lv = levels(frame[col])
        keep = lv[:cap]
        v = d[col].astype(str)
        pooled[col] = v.where(v.isin(keep), "Other")
        cats.append(keep + (["Other"] if len(lv) > cap else []))
    tab = pd.crosstab(pd.Categorical(pooled[a], categories=cats[0]), pd.Categorical(pooled[b], categories=cats[1]), dropna=False)
    tab.index, tab.columns = pd.Index(cats[0], name=a), pd.Index(cats[1], name=b)
    return tab

tab = crosstab(df, "plan", "region", 8, 6)  # categories × subgroups
values = tab
colors = ["#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)] for j, s in enumerate(values.columns)]

fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(values.index))
k = len(values.columns)
width = 0.8 / k
for j, s in enumerate(values.columns):
    hatch = SERIES_HATCHES[7 if s == "Other" else j % 8]  # texture per subgroup, as in the app
    bars = ax.bar(xs + (j - (k - 1) / 2) * width, values[s].fillna(0), width, label=s, color=colors[j], hatch=hatch, hatchcolor=HATCH_INK, linewidth=0)
ax.set_xticks(xs, list(values.index))
ax.set_xlabel("plan")
ax.set_ylabel("Count")
ax.legend(title="region")
plt.show()

Needs pandas, numpy, matplotlib · reads bar-grouped-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#bar-stacked

Stacked bars

How is each category made up of subgroups?

Demo data · seed 20261101 · 900 rows · default settings · 640 × 360

How to read it

  1. Read the whole bar for the total, or switch to 100% to compare composition.
  2. Compare the first and last segments: they share a baseline.
  3. Use the segment labels for the middle ones, which start at different points.
  1. Callout 1: Segment length: this subgroup's share.
  2. Callout 2: Middle segments float, so compare them by their labels.
  3. Callout 3: The last segment lines up on the right edge when stacked to 100%.

Watch out

  • A 100% stack hides how different the totals are, so check the counts as well.

Defaults

Scale
100 %
How the values map to the axis or the colour.
Also: Count
Orientation
Bars
Draw bars vertically or horizontally; horizontal suits long labels.
Also: Columns
Top categories
10
How many categories to show; the rest are grouped.
Range 3 to 20, step 1
Segment labels
On
Print a value on each segment.

Pinned in the code

  • Segments stack in subgroup level order (dictionary order, else frequency); levels beyond the top 6 pool into “Other”.
  • 100 % mode divides by the category's row total (row percentages); segment labels show that share and are hidden when the segment is too small to hold them.
  • Only the first segment shares a common baseline — compare inner segments with the 100 % view or grouped bars.
# Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")
# controls: mode=percent, orientation=horizontal, top=10, labels=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("bar-stacked-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["priority"] = pd.Categorical(df["priority"].astype("string"), categories=["Critical", "High", "Medium", "Low"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def crosstab(frame, a, b, max_a, max_b):
    """a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last."""
    d = frame[[a, b]].dropna()
    pooled, cats = {}, []
    for col, cap in ((a, max_a), (b, max_b)):
        lv = levels(frame[col])
        keep = lv[:cap]
        v = d[col].astype(str)
        pooled[col] = v.where(v.isin(keep), "Other")
        cats.append(keep + (["Other"] if len(lv) > cap else []))
    tab = pd.crosstab(pd.Categorical(pooled[a], categories=cats[0]), pd.Categorical(pooled[b], categories=cats[1]), dropna=False)
    tab.index, tab.columns = pd.Index(cats[0], name=a), pd.Index(cats[1], name=b)
    return tab

tab = crosstab(df, "team", "priority", 10, 6)  # categories × stack levels
values = tab.div(tab.sum(axis=1).replace(0, np.nan), axis=0).fillna(0) * 100  # row %
colors = ["#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)] for j, s in enumerate(values.columns)]
cats = list(values.index)[::-1]  # first category on top
rows = values.loc[cats]

fig, ax = plt.subplots(figsize=(8, 4.5))
base = np.zeros(len(cats))
for j, s in enumerate(values.columns):
    w = rows[s].to_numpy()
    bars = ax.barh(cats, w, left=base, color=colors[j], label=s, height=0.7)
    for rect, v, tot in zip(bars, w, rows.sum(axis=1)):  # label segments big enough to hold it
        if tot and v / tot >= 0.06:
            cx, cy = rect.get_x() + rect.get_width() / 2, rect.get_y() + rect.get_height() / 2
            ax.text(cx, cy, f"{v:.0f}%", ha="center", va="center", fontsize=7, color="white")
    base += w
ax.set_xlabel("% of category")
ax.set_ylabel("team")
ax.legend(title="priority", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads bar-stacked-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#bar-ranked

Ranked bars

Which categories lead on a total, mean or median?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Read top down: categories are ranked by the aggregate.
  2. Check the labels for the exact values.
  3. Check which aggregate is shown: a total favours big categories, a mean does not.
  1. Callout 1: The leader on this aggregate.
  2. Callout 2: The value label on each bar.

Watch out

  • A top-N view hides the rest: say how much the omitted categories add up to.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count
Top N
12
How many categories to show.
Range 3 to 30, step 1
Order
Largest first
How rows or groups are ordered.
Also: Smallest first
Value labels
On
Print each value on the chart.

Pinned in the code

  • Aggregates per category: sum, mean, median (type-7 quantile) or row count; rows with a missing category or value are dropped.
  • Ranked by the aggregate (ties alphabetical) and cut to the top N — the rest are not pooled, so the axis is not a share of a total.
  • Bars start at zero; for means and medians a selection shows the selected rows' aggregate as a marker, for sums and counts as an inner bar.
# Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")
# controls: stat=sum, top=12, order=desc, labels=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("bar-ranked-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

d = df[["product", "revenue"]].dropna()  # rows with a missing category or value dropped
agg = d.groupby(d["product"].astype(str))["revenue"].agg("sum").rename("value").reset_index()
agg = agg[np.isfinite(agg["value"].astype(float))]
agg = agg.sort_values(["value", "product"], ascending=[False, True]).head(12)  # ties alphabetical

fig, ax = plt.subplots(figsize=(7, 4.5))
y = np.arange(len(agg))[::-1]  # first ranked on top
bars = ax.barh(y, agg["value"], color=PALETTE[0], height=0.7)
for yi, v in zip(y, agg["value"]):
    ax.annotate(f"{v:,.0f}" if abs(v) >= 100 else f"{v:.3g}", (v, yi), xytext=(3, 0), textcoords="offset points", va="center", fontsize=8)
ax.axvline(0, color=plt.rcParams["axes.edgecolor"], linewidth=0.8)  # bars/stems start at zero
ax.set_yticks(y, agg["product"])
ax.set_xlabel("Sum of revenue")
ax.set_ylabel("product")
plt.show()

Needs pandas, numpy, matplotlib · reads bar-ranked-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#lollipop

Lollipop chart

How do categories rank on an aggregate, with less ink than bars?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Read the dot's position: it marks the value, and the stem connects it to zero.
  2. Read top down for the ranking.
  3. Compare gaps between neighbours to see which differences matter.
  1. Callout 1: The dot marks the value.
  2. Callout 2: The stem: a guide back to zero, with less ink than a bar.

Watch out

  • It compares one aggregate and shows no uncertainty. Small categories may rank high by chance.

Defaults

Aggregate
Mean
How rows combine into one number per group or period, such as a sum or a mean.
Also: Sum · Median · Count
Top N
14
How many categories to show.
Range 3 to 30, step 1
Order
Largest first
How rows or groups are ordered.
Also: Smallest first
Value labels
On
Print each value on the chart.

Pinned in the code

  • Same aggregates and ranking as ranked bars (sum, mean, type-7 median, count); stems start at zero so lengths stay comparable.
  • Use for many categories or when values are similar — the dot carries the value, the stem only guides the eye.
# Lollipop chart — Codesplash Chart Lab (recipe "lollipop")
# controls: stat=mean, top=14, order=desc, labels=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("lollipop-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

d = df[["product", "revenue"]].dropna()  # rows with a missing category or value dropped
agg = d.groupby(d["product"].astype(str))["revenue"].agg("mean").rename("value").reset_index()
agg = agg[np.isfinite(agg["value"].astype(float))]
agg = agg.sort_values(["value", "product"], ascending=[False, True]).head(14)  # ties alphabetical

fig, ax = plt.subplots(figsize=(7, 4.5))
y = np.arange(len(agg))[::-1]  # first ranked on top
ax.hlines(y, 0, agg["value"], color=PALETTE[0], linewidth=1.5)
ax.plot(agg["value"], y, "o", color=PALETTE[0], markersize=8)
for yi, v in zip(y, agg["value"]):
    ax.annotate(f"{v:,.0f}" if abs(v) >= 100 else f"{v:.3g}", (v, yi), xytext=(8, 0), textcoords="offset points", va="center", fontsize=8)
ax.axvline(0, color=plt.rcParams["axes.edgecolor"], linewidth=0.8)  # bars/stems start at zero
ax.set_yticks(y, agg["product"])
ax.set_xlabel("Mean revenue")
ax.set_ylabel("product")
plt.show()

Needs pandas, numpy, matplotlib · reads lollipop-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#cleveland-dot

Cleveland dot plot

How do categories compare on one value — and across up to three groups?

Demo data · seed 20261101 · 480 rows · default settings · 640 × 360

How to read it

  1. Compare the dots in a row to see how the groups differ inside one category.
  2. Read the line joining them as the size of that gap.
  3. Read the column of dots down the rows for how one group changes across categories.
  1. Callout 1: One dot per group in this row.
  2. Callout 2: The line joining dots: the gap between groups.
  3. Callout 3: No zero baseline: the axis zooms to the data's range.

Watch out

  • The axis doesn't start at zero, so gaps look large. Check the scale before calling one big.

Defaults

Aggregate
Mean
How rows combine into one number per group or period, such as a sum or a mean.
Also: Sum · Median · Count
Top N
12
How many categories to show.
Range 3 to 30, step 1
Sort
By value
How rows are sorted.
Also: Alphabetical

Pinned in the code

  • Position on a common scale is the most accurately judged encoding (Cleveland & McGill 1984); the axis need not include zero because dots are read by position, not length.
  • Rows are sorted by the aggregate over all rows (sum, mean, type-7 median or count); the first three group levels by frequency get a dot each.
  • A thin segment spans the group values on a row so gaps are easy to read.
# Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")
# controls: stat=mean, top=12, sort=value
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("cleveland-dot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["sex"] = pd.Categorical(df["sex"].astype("string"), categories=["Female", "Male"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

d = df.dropna(subset=["country", "life_expectancy"]).copy()
d["_cat"] = d["country"].astype(str)
overall = d.groupby("_cat")["life_expectancy"].agg("mean").rename("overall").reset_index()  # orders the rows
overall = overall[np.isfinite(overall["overall"].astype(float))]
overall = overall.sort_values(["overall", "_cat"], ascending=[False, True]).head(12)  # ties alphabetical
groups = levels(df["sex"])[:3]  # first three group levels (dictionary order, else frequency)
d = d[d["sex"].notna()]
d["_g"] = d["sex"].astype(str)
cells = d[d["_g"].isin(groups)].groupby(["_cat", "_g"])["life_expectancy"].agg("mean").unstack()
cells = cells.reindex(index=overall["_cat"], columns=groups)

fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(cells))[::-1]  # first row on top
ax.hlines(y, cells.min(axis=1), cells.max(axis=1), color="#9aa0a6", linewidth=2, zorder=1)  # span of the group values
for j, grp in enumerate(groups):
    ax.scatter(cells[grp], y, s=48, color=PALETTE[j], label=grp, zorder=2)
ax.set_yticks(y, cells.index)
ax.set_xlabel("Mean life_expectancy")  # no zero baseline: dots are read by position
ax.set_ylabel("country")
ax.legend(title="sex")
plt.show()

Needs pandas, numpy, matplotlib · reads cleveland-dot-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#dumbbell

Dumbbell chart

How did each category change between two periods or conditions?

Demo data · seed 20261101 · 800 rows · default settings · 640 × 360

How to read it

  1. Read the two dots as before and after.
  2. Read the bar's length as the size of the change and the label as its value.
  3. Rows are sorted by change, so the biggest movers are together.
  1. Callout 1: The later value.
  2. Callout 2: The earlier value; the bar between them is the change.
  3. Callout 3: The change, with its sign.

Watch out

  • It shows only two moments. A large change may be noise or part of a longer swing.

Defaults

Aggregate
Mean
How rows combine into one number per group or period, such as a sum or a mean.
Also: Sum · Median · Count
Sort
By change
How rows are sorted.
Also: By latest value · Alphabetical
Top N
12
How many categories to show.
Range 3 to 30, step 1
Change labels
On
Print the change beside each row.

Pinned in the code

  • From/to are the first two levels of the period role (dictionary order, else frequency); categories missing either period are dropped.
  • Each dot is the aggregate (mean by default; sum, type-7 median, count) of the category's rows in that period; the label is to − from.
  • Sorted by the change (descending) so the biggest movers sit on top.
# Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")
# controls: stat=mean, sort=gap, top=12, labels=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("dumbbell-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["year"] = pd.Categorical(df["year"].astype("string"), categories=["2025", "2026"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

periods = levels(df["year"])[:2]  # from → to: the first two period levels
d = df[["department", "engagement", "year"]].dropna()
d = d.assign(_cat=d["department"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["engagement"].agg("mean").unstack().reindex(columns=periods).dropna()  # both periods needed
w.columns = ["start", "end"]  # from → to
w["gap"] = w["end"] - w["start"]
w = w.rename_axis("level").reset_index()
w = w.sort_values(["gap", "level"], ascending=[False, True]).head(12)  # biggest movers on top

fig, ax = plt.subplots(figsize=(7, 5))
y = np.arange(len(w))[::-1]  # first row on top
ax.hlines(y, w["start"], w["end"], color="#ced1d6", linewidth=5, zorder=1)
ax.scatter(w["start"], y, s=60, color="#9aa0a6", label=periods[0], zorder=2)
ax.scatter(w["end"], y, s=60, color=PALETTE[0], label=periods[1], zorder=3)
for yi, row in zip(y, w.itertuples()):
    ax.annotate(f"{row.gap:+.3g}", (max(row.start, row.end), yi), xytext=(8, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_yticks(y, w["level"])
ax.set_xlabel("Mean engagement")
ax.set_ylabel("department")
ax.legend()
plt.show()

Needs pandas, numpy, matplotlib · reads dumbbell-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#slope

Slope chart

Which categories rose or fell between two points in time — and did the ranking change?

Demo data · seed 20261101 · 192 rows · default settings · 640 × 360

How to read it

  1. Follow each line from left to right: up means it rose.
  2. Check where lines cross: the ranking changed there.
  3. Read the labels at both ends for the values.
  1. Callout 1: A steep rising line: a big gain.
  2. Callout 2: Coloured lines: the biggest movers.
  3. Callout 3: End labels: the second period's value.

Watch out

  • Two time points cannot show a trend, and many crossing lines become unreadable.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count
Colour
Emphasise biggest movers
How bars or lines are coloured.
Also: Up / down
Movers emphasised
3
How many of the biggest movers get colour.
Range 1 to 8, step 1
Categories
8
How many categories to show; the rest are grouped.
Range 3 to 15, step 1

Pinned in the code

  • Values are per-category aggregates (sum by default) of the first two period levels; categories missing a period are dropped.
  • The top N categories by the second period's value are drawn; the N largest absolute changes are emphasised (increase in blue, decrease in orange-red), the rest are grey.
  • End labels are nudged apart (≥ 12.5 px) so they never overlap; lines keep their true end positions.
# Slope chart — Codesplash Chart Lab (recipe "slope")
# controls: stat=sum, color=emphasis, emphasis=3, top=8
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("slope-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["year"] = pd.Categorical(df["year"].astype("string"), categories=["2024", "2026"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

periods = levels(df["year"])[:2]  # from → to: the first two period levels
d = df[["brand", "units_k", "year"]].dropna()
d = d.assign(_cat=d["brand"].astype(str), _per=d["year"].astype(str))
d = d[d["_per"].isin(periods)]
w = d.groupby(["_cat", "_per"])["units_k"].agg("sum").unstack().reindex(columns=periods).dropna()  # both periods needed
w.columns = ["start", "end"]  # from → to
w["gap"] = w["end"] - w["start"]
w = w.rename_axis("level").reset_index()
w = w.sort_values("end", ascending=False, kind="stable").head(8)  # top N by the second period
movers = set(w.loc[w["gap"].abs().sort_values(ascending=False, kind="stable").index[:3], "level"])  # largest |change|
w["color"] = [(PALETTE[0] if g >= 0 else "#ce5342") if lvl in movers else "#9aa0a6" for lvl, g in zip(w["level"], w["gap"])]

def nudge(ys, gap):
    """Spread label positions so neighbours are at least `gap` apart (lines keep their true ends)."""
    ys = np.asarray(ys, dtype=float)
    order = np.argsort(ys)
    out = ys.copy()
    for k in range(1, len(order)):
        out[order[k]] = max(out[order[k]], out[order[k - 1]] + gap)
    return out

fig, ax = plt.subplots(figsize=(6, 5))
for row in w.itertuples():
    ax.plot([0, 1], [row.start, row.end], color=row.color, linewidth=2.2 if row.color != "#9aa0a6" else 1.2, marker="o")
gap = 0.035 * (np.nanmax(w[["start", "end"]].to_numpy()) - np.nanmin(w[["start", "end"]].to_numpy()) or 1)
for side, col, ha in ((0, "start", "right"), (1, "end", "left")):
    for yl, row in zip(nudge(w[col], gap), w.itertuples()):
        value = row.start if side == 0 else row.end
        text = f"{row.level}  {value:,.4g}" if side == 0 else f"{value:,.4g}  {row.level}"
        ax.text(side + (-0.04 if side == 0 else 0.04), yl, text, ha=ha, va="center", fontsize=8, color=row.color)
ax.set_xticks([0, 1], periods)
ax.set_xlim(-0.6, 1.6)
ax.set_ylabel("Sum of units_k")
ax.grid(axis="x", visible=False)
plt.show()

Needs pandas, numpy, matplotlib · reads slope-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svg#likert

Likert diverging bars

How do agreement levels compare across survey items?

Demo data · seed 20261101 · 400 rows · default settings · 640 × 360

How to read it

  1. The centre of the chart is neutral: disagreement grows to the left, agreement to the right.
  2. Compare how far each bar reaches on each side.
  3. Read the order: items are ranked by net agreement.
  1. Callout 1: Centre: the neutral responses straddle zero.
  2. Callout 2: Right side: the share who agree.
  3. Callout 3: Left side: the share who disagree.

Watch out

  • Response categories are ordered but not evenly spaced, so a mean of codes can mislead.
  • Check the sample size per item before ranking small differences.

Defaults

Order
By net agreement
How rows or groups are ordered.
Also: As listed
Percent labels
On
Print each segment's share.

Pinned in the code

  • Shares are per item over its non-missing responses; response order comes from the dictionary's ordinal levels (default 5-point Strongly disagree … Strongly agree).
  • With an odd number of levels the middle level is neutral and is split half left, half right of zero, so bars centre on neutral (Robbins & Heiberger 2011).
  • Net agreement = agree shares − disagree shares (neutral excluded); items are ranked by it.
  • A selection adds a thin outlined bar under each item with the selected respondents' shares.
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")
# controls: sort=net, labels=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("likert-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Meaningful work"] = pd.Categorical(df["Meaningful work"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Clear goals"] = pd.Categorical(df["Clear goals"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Manager support"] = pd.Categorical(df["Manager support"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Fair pay"] = pd.Categorical(df["Fair pay"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Work–life balance"] = pd.Categorical(df["Work–life balance"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])
df["Growth opportunities"] = pd.Categorical(df["Growth opportunities"].astype("string"), categories=["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"])

ITEMS = ["Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities"]
LEVELS = ["Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"]  # response order from the data dictionary
COLORS = ["#c95443", "#da8477", "#ced1d6", "#6691ca", "#2a69b5"]  # disagree … neutral … agree
k = len(LEVELS)
mid = (k - 1) / 2  # with an odd number of levels the middle one is neutral
shares = {}
for item in ITEMS:
    s = df[item].dropna().astype(str)
    s = s[s.isin(LEVELS)]
    shares[item] = s.value_counts().reindex(LEVELS, fill_value=0) / max(len(s), 1)  # share of non-missing responses
shares = pd.DataFrame(shares).T * 100  # items × levels, percent
neg = shares[[l for j, l in enumerate(LEVELS) if j < mid]].sum(axis=1)
pos = shares[[l for j, l in enumerate(LEVELS) if j > mid]].sum(axis=1)
neutral = shares[[l for j, l in enumerate(LEVELS) if j == mid]].sum(axis=1)
net = pos - neg  # net agreement
start = -(neg + neutral / 2)  # half the neutral share on each side of zero
order = list(net.sort_values(ascending=False, kind="stable").index)  # by net agreement

fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(order))[::-1]  # first item on top
for yi, item in zip(y, order):
    left = start[item]
    for j, lvl in enumerate(LEVELS):
        w = shares.loc[item, lvl]
        ax.barh(yi, w, left=left, color=COLORS[j], height=0.7, label=lvl if yi == y[0] else None)
        if w >= 6:
            ax.text(left + w / 2, yi, f"{w:.0f}", ha="center", va="center", fontsize=7)
        left += w
ax.axvline(0, color=plt.rcParams["axes.edgecolor"], linewidth=1)
ax.set_yticks(y, order)
ax.xaxis.set_major_formatter(lambda v, _: f"{abs(v):.0f}%")
ax.set_xlabel("Share of responses, centred on neutral (disagree left, agree right)")
ax.legend(ncol=k, loc="upper center", bbox_to_anchor=(0.5, -0.15), fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads likert-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#pareto

Pareto chart

Which few categories account for most of the total?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read the bars left to right: categories are sorted by size.
  2. Follow the line for the running share of the total.
  3. Where the line crosses the reference: everything left of it is the vital few.
  1. Callout 1: The largest category.
  2. Callout 2: The running total crosses the reference here.
  3. Callout 3: The long tail of small categories.

Watch out

  • It ranks frequency, not cost or severity. The biggest bar is not always the most important problem.

Defaults

Categories shown
10
How many categories to show before grouping the rest into Other.
Range 3 to 30, step 1
Reference %
80
Where to draw the reference line on the cumulative axis.
Range 50 to 95, step 5
Cumulative labels
Off
Print the running share at each bar.

Pinned in the code

  • Bars are row counts (or the sum of a value) per category, sorted descending (ties alphabetical); categories beyond the first N pool into “Other”, which is kept last as is conventional.
  • Cumulative % = running total / grand total, read on the right axis; bars up to and including the one that crosses the reference (80 % by default) are the “vital few”.
  • Negative values are not meaningful in a Pareto chart and are excluded.
# Pareto chart — Codesplash Chart Lab (recipe "pareto")
# controls: top=10, threshold=80, cumLabels=false
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("pareto-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

d = df[["defect"]].dropna().assign(_value=1.0)  # no value column: count rows
sums = d.groupby(d["defect"].astype(str))["_value"].sum()
sums = sums[sums > 0]  # non-positive totals are not meaningful in a Pareto chart
r = sums.rename("value").reset_index().sort_values(["value", "defect"], ascending=[False, True])  # ties alphabetical
r["share"] = r["value"] / r["value"].sum()
r["cumulative"] = r["share"].cumsum()
if len(r) > 10:  # pool the rest into "Other", kept last
    rest = r.iloc[10:]
    other = pd.DataFrame({"defect": ["Other"], "value": [rest["value"].sum()], "share": [rest["share"].sum()], "cumulative": [1.0]})
    r = pd.concat([r.iloc[:10], other], ignore_index=True)
THRESHOLD = 0.8
vital = int(np.argmax(r["cumulative"].to_numpy() >= THRESHOLD - 1e-12))  # bars up to the crossing are the vital few
colors = ["#9aa0a6" if lvl == "Other" else (PALETTE[0] if i <= vital else PALETTE[0] + "73") for i, lvl in enumerate(r["defect"])]

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(r["defect"], r["value"], color=colors)
ax.set_ylabel("Count")
ax.set_xlabel("defect")
ax.tick_params(axis="x", labelrotation=35)
ax2 = ax.twinx()  # cumulative share on a 0–100 % axis
ax2.plot(r["defect"], r["cumulative"] * 100, color=PALETTE[1], marker="o", linewidth=2)
ax2.axhline(THRESHOLD * 100, color=PALETTE[1], linestyle="--", linewidth=1)
ax2.set_ylim(0, 105)
ax2.set_ylabel("Cumulative %")
ax2.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads pareto-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#mosaic

Mosaic plot

Are two categorical variables associated — and which cells drive it?

Demo data · seed 20261101 · 2,201 rows · default settings · 640 × 360

How to read it

  1. Read column width as the size of each column level.
  2. Read the heights inside a column as the row shares for that level.
  3. Use the colours: strong shades mark cells far from what independence predicts.
  1. Callout 1: A strongly shaded cell: many more rows than independence predicts.
  2. Callout 2: Same column, lower row: fewer than predicted.
  3. Callout 3: Pale cells: close to what independence predicts.

Watch out

  • Residual shading depends on sample size, so large tables shade strongly for small differences.

Defaults

Shading
Pearson residuals
Whether to shade cells by their standardized residual or by level.
Also: Standardized residuals · Row levels
Percent labels
On
Print each segment's share.
Column levels
8
How many column levels to show; the rest are grouped.
Range 2 to 12, step 1

Pinned in the code

  • Column widths ∝ the column variable's marginal counts; tile heights ∝ the conditional share of each row level within the column (Hartigan & Kleiner 1981).
  • Pearson residuals rᵢⱼ = (oᵢⱼ − eᵢⱼ)/√eᵢⱼ with eᵢⱼ = rowᵢ·colⱼ/n (R `chisq.test()$residuals`); standardized residuals divide by √(eᵢⱼ(1 − rowᵢ/n)(1 − colⱼ/n)) (`$stdres`).
  • Shading follows vcd's cut-offs: |r| < 2 neutral, 2–4 medium, ≥ 4 strong; blue = more than expected, orange-red = fewer. χ² is Pearson's without continuity correction.
  • Row-level labels sit at the marginal shares (spine-plot convention); percent labels are shares within the column.
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")
# controls: shading=pearson, labels=true, top=8
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("mosaic-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["class"] = pd.Categorical(df["class"].astype("string"), categories=["1st", "2nd", "3rd", "Crew"])
df["outcome"] = pd.Categorical(df["outcome"].astype("string"), categories=["Survived", "Died"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def crosstab(frame, a, b, max_a, max_b):
    """a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last."""
    d = frame[[a, b]].dropna()
    pooled, cats = {}, []
    for col, cap in ((a, max_a), (b, max_b)):
        lv = levels(frame[col])
        keep = lv[:cap]
        v = d[col].astype(str)
        pooled[col] = v.where(v.isin(keep), "Other")
        cats.append(keep + (["Other"] if len(lv) > cap else []))
    tab = pd.crosstab(pd.Categorical(pooled[a], categories=cats[0]), pd.Categorical(pooled[b], categories=cats[1]), dropna=False)
    tab.index, tab.columns = pd.Index(cats[0], name=a), pd.Index(cats[1], name=b)
    return tab

tab = crosstab(df, "class", "outcome", 8, 6)  # columns of the mosaic × rows within them
o = tab.to_numpy(dtype=float)
n, rt, ct = o.sum(), o.sum(axis=1), o.sum(axis=0)
e = np.outer(rt, ct) / n  # expected counts under independence
with np.errstate(divide="ignore", invalid="ignore"):
    resid = np.where(e > 0, (o - e) / np.sqrt(e), 0)  # Pearson residuals, chisq.test()$residuals
    pearson = np.where(e > 0, (o - e) / np.sqrt(e), 0)
chi2 = (pearson ** 2).sum()  # Pearson χ², no continuity correction
dof = max(0, (np.count_nonzero(rt) - 1) * (np.count_nonzero(ct) - 1))
SHADES = ["#c13e2e", "#df9489", "#f3f5f8", "#799fd1", "#0859ac"]  # r ≤ −4, −4…−2, |r| < 2, 2…4, ≥ 4 (vcd cut-offs)
def shade(r):
    s = 2 if abs(r) >= 4 else 1 if abs(r) >= 2 else 0
    return SHADES[2 + int(np.sign(r)) * s]
GAP = 0.012
widths = rt / n * (1 - GAP * (len(rt) - 1))  # column widths ∝ the column variable's margins
lefts = np.concatenate([[0], np.cumsum(widths + GAP)[:-1]])
tiles = []  # (i, j, x, y, w, h) with y measured from the top
for i in range(len(rt)):
    usable = 1 - GAP * (len(ct) - 1)
    top = 0.0
    for j in range(len(ct)):
        h = o[i, j] / rt[i] * usable if rt[i] else 0  # heights ∝ the share within the column
        tiles.append((i, j, lefts[i], top, widths[i], h))
        top += h + GAP

from matplotlib.patches import Patch, Rectangle
fig, ax = plt.subplots(figsize=(8, 5))
for i, j, x0, y0, w, h in tiles:
    color = shade(resid[i, j])
    ax.add_patch(Rectangle((x0, 1 - y0 - h), w, h, facecolor=color, edgecolor="white", linewidth=0.5))
    if w > 0.05 and h > 0.05:
        ax.text(x0 + w / 2, 1 - y0 - h / 2, f"{o[i, j] / rt[i]:.0%}", ha="center", va="center", fontsize=7)
ax.set_xticks(lefts + widths / 2, list(tab.index))
marg = ct / n  # row-level labels at the marginal shares (spine-plot convention)
ax.set_yticks(1 - (np.cumsum(marg) - marg / 2), list(tab.columns))
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.grid(False)
ax.set_xlabel("class")
ax.set_ylabel("outcome")
ax.legend(handles=[Patch(color=s, label=l) for s, l in zip(SHADES, ["r ≤ −4", "−4 < r ≤ −2", "|r| < 2", "2 ≤ r < 4", "r ≥ 4"])],
          title=f"χ²({dof}) = {chi2:.1f}", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads mosaic-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svg#waffle

Waffle chart

What share of the whole does each category hold — in countable units?

Demo data · seed 20261101 · 1,000 rows · default settings · 640 × 360

How to read it

  1. Count squares: each one is 1% of the rows.
  2. Compare blocks of colour.
  3. Read the legend for exact percentages.
  1. Callout 1: Each square: 1% of rows.
  2. Callout 2: The legend gives each share.

Watch out

  • It rounds to whole percents, so very small categories may lose or gain a square.

Defaults

Categories
6
How many categories to show; the rest are grouped.
Range 2 to 8, step 1
Percent in legend
On
Print each category's share in the legend.

Pinned in the code

  • Each of the 100 squares is 1 % of non-missing rows; squares are allocated by the largest-remainder (Hamilton) method so they always total 100.
  • Levels sorted by frequency; beyond the top k they pool into “Other” (neutral grey). Squares fill row by row from the top left.
  • Shares under 0.5 % may get no square — the legend percentages are exact.
# Waffle chart — Codesplash Chart Lab (recipe "waffle")
# controls: top=6, percents=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("waffle-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def hamilton(values, cells=100):
    """Largest-remainder (Hamilton) allocation: cells always total `cells`; ties go to the earlier level."""
    exact = np.asarray(values, dtype=float) / np.sum(values) * cells
    out = np.floor(exact).astype(int)
    rest = sorted(range(len(exact)), key=lambda i: (-(exact[i] - np.floor(exact[i])), i))
    for i in rest[: cells - out.sum()]:
        out[i] += 1
    return out

keep = levels(df["heating"])[:6]
s = df["heating"].dropna().astype(str)
counts = s.where(s.isin(keep), "Other").value_counts().reindex(keep + (["Other"] if (~s.isin(keep)).any() else []), fill_value=0)
cells = hamilton(counts.to_numpy())  # each of the 100 squares is 1 % of non-missing rows
colors = ["#9aa0a6" if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(counts.index)]
owner = np.repeat(np.arange(len(cells)), cells)  # squares fill row by row from the top left
hatches = [SERIES_HATCHES[7 if l == "Other" else i % 8] for i, l in enumerate(counts.index)]  # texture per level, as in the app
labels = [f"{l}  {v / counts.sum():.1%}" for l, v in counts.items()]

from matplotlib.patches import Patch, Rectangle
fig, ax = plt.subplots(figsize=(7, 4.5))
for k, who in enumerate(owner):
    row, col = divmod(k, 10)
    ax.add_patch(Rectangle((col, 9 - row), 0.9, 0.9, facecolor=colors[who], hatch=hatches[who], hatchcolor=HATCH_INK, linewidth=0))
ax.set_xlim(-0.1, 10)
ax.set_ylim(-0.1, 10)
ax.set_aspect("equal")
ax.axis("off")
ax.legend(handles=[Patch(facecolor=col, hatch=h, hatchcolor=HATCH_INK, linewidth=0, label=lab) for col, h, lab in zip(colors, hatches, labels)], loc="center left", bbox_to_anchor=(1.02, 0.5))
plt.show()

Needs pandas, numpy, matplotlib · reads waffle-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#point-range

Point-range (mean ± CI)

How do group means compare, with their uncertainty?

Demo data · seed 20261101 · 209 rows · default settings · 640 × 360

How to read it

  1. Compare the group means: the dark dots.
  2. Read the bars as the uncertainty of each mean.
  3. Check the raw points behind them for how varied individuals are.
  1. Callout 1: The dot: the group mean. The bar: its interval.
  2. Callout 2: Raw points: individuals vary far more than the mean does.

Watch out

  • Two overlapping intervals do not prove that two means are equal. Test the difference directly.

Defaults

Interval
Confidence interval (t)
What the interval shows: a confidence interval, a standard error or a standard deviation.
Also: ± 1 standard error · ± 1 standard deviation
Confidence level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.8 to 0.99, step 0.01
Raw points
On
Show each observation behind the summary.
Order
As in data
How rows or groups are ordered.
Also: By mean

Pinned in the code

  • CI: x̄ ± t(1 − α/2, n − 1)·s/√n per group (R `t.test(x)$conf.int`; independent groups, no pooling); SD uses n − 1.
  • ± SE and ± SD intervals are descriptive, not inferential — the axis label says which interval is drawn.
  • Overlapping 95 % CIs do not imply a non-significant difference (Cumming & Finch 2005); use the Analyze module for tests.
  • Raw points are jittered deterministically (seeded) so the picture is stable.
# Point-range (mean ± CI) — Codesplash Chart Lab (recipe "point-range")
# controls: interval=ci, level=0.95, points=true, sort=data
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("point-range-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["condition"] = pd.Categorical(df["condition"].astype("string"), categories=["Baseline", "Caffeine", "Sleep-deprived", "Music", "Dual task"])

d = df[["reaction_ms", "condition"]].dropna()
d["_g"] = d["condition"].astype(str)
order = [str(l) for l in df["condition"].cat.categories] if isinstance(df["condition"].dtype, pd.CategoricalDtype) else list(pd.unique(d["_g"]))
s = d.groupby("_g")["reaction_ms"].agg(["count", "mean", "std"]).reindex([l for l in order if l in set(d["_g"])])  # std uses n − 1
s["se"] = s["std"] / np.sqrt(s["count"])
s["half"] = stats.t.ppf(1 - (1 - 0.95) / 2, s["count"] - 1) * s["se"]  # t interval per group, as R t.test(x)$conf.int
s["half"] = s["half"].fillna(0)  # n < 2: the interval collapses to the mean
s = s.head(15)
LABEL = "reaction_ms (mean ± 95 % CI)"

fig, ax = plt.subplots(figsize=(7, 4.5))
xs = np.arange(len(s))
for i, level in enumerate(s.index):  # raw points, deterministic jitter
    v = d.loc[d["_g"] == level, "reaction_ms"].to_numpy()
    jitter = ((np.arange(1, v.size + 1) * 0.618034) % 1 - 0.5) * 0.36
    ax.scatter(i + jitter, v, s=8, color="#9aa0a6", alpha=0.5, zorder=1)
ax.errorbar(xs, s["mean"], yerr=s["half"], fmt="o", color=PALETTE[0], ecolor=PALETTE[0], elinewidth=2, capsize=4, markersize=7, zorder=3)
ax.set_xticks(xs, s.index)
ax.set_xlabel("condition")
ax.set_ylabel(LABEL)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads point-range-demo.csv · app theme from the optional codesplash helper

Categories & comparison

svgbrushable#interaction

Interaction plot

Does the effect of one factor depend on another?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Follow each line: it shows the mean across one factor at one level of the other.
  2. Parallel lines: the first factor's effect is the same at both levels.
  3. Non-parallel or crossing lines: the effect depends on the other factor.
  1. Callout 1: The lines spread apart here: the factors interact.
  2. Callout 2: The lines start close together at this level.
  3. Callout 3: Error bars: is the gap between the lines more than noise?

Watch out

  • Non-parallel lines may be noise. Check the interaction term's test and interval before you interpret them.

Defaults

Error bars
Confidence interval (t)
What the bars show: a confidence interval, a standard error or a standard deviation.
Also: ± 1 SE · None
Confidence level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.8 to 0.99, step 0.01
Dodge traces
On
Nudge lines sideways so their error bars don't overlap.

Pinned in the code

  • Each point is the mean of the outcome in one x × trace cell; error bars are per-cell t intervals x̄ ± t(1 − α/2, n − 1)·s/√n (no pooled error term) or ± SE.
  • Lines connect cell means within a trace level; roughly parallel lines suggest additive effects. This is a descriptive plot — test the interaction (and get estimated marginal means) in Analyze.
  • Traces are dodged horizontally so intervals do not overlap; x levels follow the dictionary order, else frequency.
# Interaction plot — Codesplash Chart Lab (recipe "interaction")
# controls: interval=ci, level=0.95, dodge=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("interaction-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fertilizer"] = pd.Categorical(df["fertilizer"].astype("string"), categories=["None", "Nitrogen", "Compost"])
df["irrigation"] = pd.Categorical(df["irrigation"].astype("string"), categories=["Low", "High"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

xl = levels(df["fertilizer"])[:10]
tl = levels(df["irrigation"])[:6]
d = df[["yield_t_ha", "fertilizer", "irrigation"]].dropna()
d = d.assign(_x=d["fertilizer"].astype(str), _t=d["irrigation"].astype(str))
d = d[d["_x"].isin(xl) & d["_t"].isin(tl)]
cells = d.groupby(["_t", "_x"])["yield_t_ha"].agg(["count", "mean", "std"])
cells["half"] = (stats.t.ppf(1 - (1 - 0.95) / 2, cells["count"] - 1) * cells["std"] / np.sqrt(cells["count"])).fillna(0)  # per-cell t interval
DODGE = 0.08

fig, ax = plt.subplots(figsize=(7, 4.5))
for k, t in enumerate(tl):
    if t not in cells.index.get_level_values(0):
        continue
    sub = cells.loc[t].reindex(xl).dropna(subset=["mean"])
    xs = np.array([xl.index(v) for v in sub.index]) + (k - (len(tl) - 1) / 2) * DODGE
    ax.errorbar(xs, sub["mean"], yerr=sub["half"], fmt="-o", capsize=3, color=PALETTE[k % len(PALETTE)], label=t)
ax.set_xticks(range(len(xl)), xl)
ax.set_xlabel("fertilizer")
ax.set_ylabel("Mean yield_t_ha")
ax.legend(title="irrigation")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads interaction-demo.csv · app theme from the optional codesplash helper

Relationships

How two or more variables move together.

9

Relationships

svgbrushable#scatter

Scatter plot

How do two numeric variables move together?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Read the overall direction: rising, falling or flat.
  2. Read how tightly the points follow the fit line, and whether the fit should be straight at all.
  3. Look for points far from the rest and for groups that behave differently.
  1. Callout 1: The fit line: the average trend, with its band.
  2. Callout 2: A cloud of one group: does the trend hold inside each group?
  3. Callout 3: Points far from the rest: check them before fitting.

Watch out

  • A strong pattern does not show that one variable causes the other.
  • A trend across groups can reverse inside them (Simpson's paradox).

Defaults

Fit
OLS + 95% CI
Add a straight-line (OLS) or flexible (LOESS) trend line.
Also: None · LOESS
LOESS span
0.75
The share of points in each local fit: smaller follows the data closely, larger is smoother.
Range 0.2 to 1, step 0.05
Point radius
3
The size of each point.
Range 1 to 6, step 0.5
Opacity
0.7
How see-through points are; lower reveals density in crowded areas.
Range 0.1 to 1, step 0.1
Renderer
Auto (canvas > 5,000)
Draw as vector shapes or to a canvas; canvas stays fast with many points.
Also: SVG · Canvas

Pinned in the code

  • OLS: ŷ = a + b·x by least squares; the band is the 95 % confidence interval of the mean, ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx).
  • LOESS: local linear fits with tricube weights over the nearest span·n points (degree 1, no robustness iterations; R `loess(degree = 1, family = "gaussian")`).
  • Rows with a missing x or y are dropped.
# Scatter plot — Codesplash Chart Lab (recipe "scatter")
# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from statsmodels.nonparametric.smoothers_lowess import lowess
import matplotlib.dates as mdates

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("scatter-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def ols_band(x, y, level=0.95, points=60):
    """y = a + b·x with the pointwise CI of the mean: ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx)."""
    n, mx = x.size, x.mean()
    sxx = ((x - mx) ** 2).sum()
    b = ((x - mx) * (y - y.mean())).sum() / sxx
    a = y.mean() - b * mx
    s = np.sqrt(((y - a - b * x) ** 2).sum() / (n - 2))
    grid = np.linspace(x.min(), x.max(), points)
    fit = a + b * grid
    half = stats.t.ppf(1 - (1 - level) / 2, n - 2) * s * np.sqrt(1 / n + (grid - mx) ** 2 / sxx)
    return grid, fit, fit - half, fit + half, a, b
def loess_curve(x, y, span, points=60):
    """Local linear fits, tricube weights over the floor(span·n) nearest points, no robustness
    iterations — R loess(degree = 1, family = "gaussian", surface = "direct")."""
    grid = np.linspace(x.min(), x.max(), points)
    return grid, lowess(y, x, frac=span, it=0, delta=0.0, xvals=grid)

d = df.dropna(subset=["spend_k", "revenue_k"])  # rows with a missing x or y are dropped
xv = d["spend_k"].to_numpy(dtype=float)
yv = d["revenue_k"].to_numpy(dtype=float)

fig, ax = plt.subplots(figsize=(7, 4.5))
for i, lv in enumerate(freq_levels(d["segment"])):
    m = (d["segment"].astype(str) == lv).to_numpy()
    ax.scatter(xv[m], yv[m], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=lv, s=20.25, alpha=0.7, edgecolors="none")  # marker shape per group, as in the app
ax.legend(title="segment", fontsize=8)
grid, fit, lo, hi, a, b = ols_band(xv, yv)
ax.fill_between(grid, lo, hi, color=REF, alpha=0.15, linewidth=0, label="95% CI")
ax.plot(grid, fit, color=REF, linewidth=2, label=f"OLS: y = {a:.3g} + {b:.3g}·x")
ax.set_xlabel("spend_k")
ax.set_ylabel("revenue_k")
plt.show()

Needs pandas, numpy, matplotlib, scipy, statsmodels · reads scatter-demo.csv · app theme from the optional codesplash helper

Relationships

svgbrushable#bubble

Bubble chart

How do two variables relate when a third sets each point's weight?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Read position as for any scatter: the two main variables.
  2. Read bubble area as the third variable; use the size legend.
  3. Colour marks the group: look for groups that sit apart.
  1. Callout 1: Large bubbles: heavy rows, which can hide the small ones.
  2. Callout 2: Size legend: area shows the value.
  3. Callout 3: Labels on the largest points.

Watch out

  • People judge area poorly, so don't read exact ratios from bubble sizes.

Defaults

Log X axis
On
Space the x axis by ratios, which suits values spanning orders of magnitude.
Bubble scale
1
Make all bubbles larger or smaller; their relative areas stay the same.
Range 0.5 to 2, step 0.25
Label largest
5
Name the largest bubbles.
Range 0 to 20, step 1

Pinned in the code

  • Area ∝ value: r = r_max·√(v / v_max) (ggplot2 `scale_size_area`), so twice the value has twice the ink; zero and negative sizes draw no bubble.
  • Bubbles are drawn largest first so smaller ones stay visible; rows missing x, y or size are dropped (and x ≤ 0 on a log axis).
  • Size legend values are round numbers ≤ the maximum at about 1, ¼ and 1⁄16 of it (radii ≈ 1, ½, ¼).

Use with care

People judge areas poorly; keep the size variable secondary and give exact values in tooltips or a table.

# Bubble chart — Codesplash Chart Lab (recipe "bubble")
# controls: logX=true, scale=1, labels=5
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("bubble-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=["Africa", "Americas", "Asia", "Europe", "Oceania"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

d = df.dropna(subset=["gdp_per_capita_k", "life_expectancy", "population_m"])
d = d[d["gdp_per_capita_k"] > 0]  # log axis: x ≤ 0 cannot be drawn
d = d.sort_values("population_m", ascending=False, kind="stable")  # largest first, small bubbles on top
v = d["population_m"].clip(lower=0).to_numpy(dtype=float)  # zero/negative sizes draw no bubble
area = (22 ** 2) * v / v.max()  # area ∝ value (ggplot2 scale_size_area)

fig, ax = plt.subplots(figsize=(7, 4.5))
levels = freq_levels(d["region"])
key = d["region"].astype(str).to_numpy()
# each colour group also gets its own marker shape (same area), as in the app; other levels use the 8th
groups = [(lv, key == lv, i) for i, lv in enumerate(levels)] + [(None, ~np.isin(key, levels), 7)]
for lv, m, i in groups:
    if m.any():
        ax.scatter(d["gdp_per_capita_k"][m], d["life_expectancy"][m], s=area[m], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], alpha=0.7, edgecolors="white", linewidths=0.6)
    if lv is not None:
        ax.scatter([], [], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=lv)
ax.legend(title="region", fontsize=8)
for _, row in d.head(5).iterrows():  # label the 5 largest
    ax.annotate(str(row["country"]), (row["gdp_per_capita_k"], row["life_expectancy"]), fontsize=8, ha="center", va="center")
ax.set_xscale("log")
ax.set_xlabel("gdp_per_capita_k (log scale)")
ax.set_ylabel("life_expectancy")
ax.set_title("Bubble area proportional to population_m", fontsize=10, loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads bubble-demo.csv · app theme from the optional codesplash helper

Relationships

svgbrushable#scatter-marginal

Scatter with marginals

How do two variables relate, and how is each distributed?

Demo data · seed 20261101 · 333 rows · default settings · 640 × 360

How to read it

  1. Read the scatter for the relationship.
  2. Read the top and right panels for each variable on its own.
  3. Check whether a hump in a marginal lines up with a cluster in the scatter.
  1. Callout 1: The scatter: the two variables together.
  2. Callout 2: Top panel: the x variable on its own.
  3. Callout 3: Right panel: the y variable on its own.

Watch out

  • A marginal cannot show what happens jointly: two clusters can share the same marginal shape.

Defaults

Marginals
Histogram
What to draw on the top and right edges.
Also: Density (by colour)
Bin rule
Freedman–Diaconis
How the bin width is chosen. Freedman–Diaconis resists outliers; Sturges suits small, near-normal data.
Also: Sturges · Scott · Rice · Square root · Doane
Bandwidth rule
nrd0 (Silverman, R default)
The rule that sets how much the curve is smoothed. Scott and Silverman suit one-humped data.
Also: nrd (Scott variant) · Scott (scipy default)
Fit
None
Add a straight-line (OLS) or flexible (LOESS) trend line.
Also: OLS + 95% CI
Point radius
2.5
The size of each point.
Range 1 to 5, step 0.5

Pinned in the code

  • Marginal histograms use numpy-style equal-width bins over each variable's [min, max] ([a, b), last bin closed) with the chosen rule.
  • Density marginals: Gaussian KDE per colour group (bandwidth rule as chosen), each scaled by its group share so the curves add up to the overall density (seaborn `jointplot(kind="kde", common_norm=True)`).
  • Marginals share the scatter's axes; rows missing x or y are dropped everywhere.
# Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")
# controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("scatter-marginal-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["Adelie", "Chinstrap", "Gentoo"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def bandwidth(v, rule="nrd0"):
    """R bw.nrd0 / bw.nrd, or scipy's Scott rule — as the app computes it."""
    v = np.asarray(v, dtype=float)
    n, sd = v.size, v.std(ddof=1)
    iqr = np.subtract(*np.percentile(v, [75, 25]))
    if rule == "scott":
        return sd * n ** (-1 / 5)
    lo = min(sd, iqr / 1.34) or sd or abs(v[0]) or 1.0
    return (0.9 if rule == "nrd0" else 1.06) * lo * n ** (-1 / 5)

d = df.dropna(subset=["bill_length_mm", "flipper_length_mm"])  # rows missing x or y are dropped everywhere
xv = d["bill_length_mm"].to_numpy(dtype=float)
yv = d["flipper_length_mm"].to_numpy(dtype=float)
groups = [(lv, (d["species"].astype(str) == lv).to_numpy(), PALETTE[i % len(PALETTE)]) for i, lv in enumerate(freq_levels(d["species"]))]

fig = plt.figure(figsize=(7, 6))
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4), hspace=0.05, wspace=0.05)
ax = fig.add_subplot(gs[1, 0])
top = fig.add_subplot(gs[0, 0], sharex=ax)
right = fig.add_subplot(gs[1, 1], sharey=ax)
for i, (lv, m, col) in enumerate(groups):  # marker shape per group, as in the app
    ax.scatter(xv[m], yv[m], s=14.0625, color=col, marker=SERIES_MARKERS[i % 8], alpha=0.75, edgecolors="none", label=lv)
# numpy-style equal-width bins over each variable's [min, max] ([a, b), last bin closed)
top.hist(xv, bins=np.histogram_bin_edges(xv, bins="fd"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5)
right.hist(yv, bins=np.histogram_bin_edges(yv, bins="fd"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5, orientation="horizontal")
top.axis("off")
right.axis("off")
ax.set_xlabel("bill_length_mm")
ax.set_ylabel("flipper_length_mm")
ax.legend(title="species", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads scatter-marginal-demo.csv · app theme from the optional codesplash helper

Relationships

svgbrushable#connected-scatter

Connected scatter

How did two variables move together over time?

Demo data · seed 20261101 · 26 rows · default settings · 640 × 360

How to read it

  1. Start at the labelled first point and follow the path through time.
  2. Use the arrows and the colour ramp for direction.
  3. Read a loop as a cycle; a long straight run as a sustained move.
  1. Callout 1: The start of the path.
  2. Callout 2: A sharp excursion: find the dates.
  3. Callout 3: Labelled points anchor the timeline.

Watch out

  • Time isn't an axis here. Readers can misjudge direction unless arrows or labels are on.

Defaults

Colour by time
On
Fade the path from early to late so you can follow its direction.
Direction arrows
On
Add arrows along the path.
Label every k points
5
Label every k-th point along the path.
Range 0 to 20, step 1

Pinned in the code

  • Rows are sorted by the order variable (ties keep row order); rows missing x, y or order are dropped.
  • Segments are coloured along a sequential ramp from the first to the last point; arrows sit at segment midpoints.
  • Labels are placed on the outside of the bend (away from the neighbouring points).
# Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")
# controls: gradient=true, arrows=true, labelEvery=5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import LinearSegmentedColormap

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("connected-scatter-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")

d = df.dropna(subset=["unemployment_pct", "inflation_pct", "year"]).sort_values("year", kind="stable")  # ties keep row order
xv, yv = d["unemployment_pct"].to_numpy(dtype=float), d["inflation_pct"].to_numpy(dtype=float)
ramp = LinearSegmentedColormap.from_list("time", [SEQ[0], SEQ[-1]])
t = np.linspace(0.3, 1, len(d) - 1)  # early → late (skip the palest end of the ramp)

fig, ax = plt.subplots(figsize=(7, 4.5))
segments = np.stack([np.c_[xv[:-1], yv[:-1]], np.c_[xv[1:], yv[1:]]], axis=1)
ax.add_collection(LineCollection(segments, colors=ramp(t), linewidths=2))
ax.scatter(xv, yv, s=18, color=ramp(np.linspace(0.3, 1, len(d))), zorder=3)
for (x0, y0), (x1, y1) in zip(segments[:, 0], segments[:, 1]):  # arrows at segment midpoints
    mx, my = (x0 + x1) / 2, (y0 + y1) / 2
    ax.annotate("", xy=(mx + (x1 - x0) * 0.01, my + (y1 - y0) * 0.01), xytext=(mx, my), arrowprops=dict(arrowstyle="-|>", color=REF, lw=1))
labels = d["year"].astype(str).to_numpy()
keep = set([0, len(d) - 1] + (list(range(0, len(d), 5)) if 5 > 0 else []))
for i in sorted(keep):
    ax.annotate(labels[i], (xv[i], yv[i]), textcoords="offset points", xytext=(4, 4), fontsize=8)
ax.autoscale()
ax.set_xlabel("unemployment_pct")
ax.set_ylabel("inflation_pct")
plt.show()

Needs pandas, numpy, matplotlib · reads connected-scatter-demo.csv · app theme from the optional codesplash helper

Relationships

svg#pair-plot

Pair plot

How do several numeric variables relate to each other at once?

Demo data · seed 20261101 · 333 rows · default settings · 640 × 360

How to read it

  1. Read the diagonal for each variable's distribution.
  2. Read the lower triangle for pairs as scatter plots.
  3. Read the upper triangle for correlations, overall and within each group.
  1. Callout 1: Diagonal: one variable's distribution.
  2. Callout 2: Lower triangle: one pair as a scatter.
  3. Callout 3: Upper triangle: the correlation for that pair.

Watch out

  • A pair plot hides relationships among three or more variables, and many panels invite false patterns.

Defaults

Diagonal bin rule
Sturges
How the histograms on the diagonal choose their bin width.
Also: Freedman–Diaconis · Scott · Rice · Square root · Doane

Pinned in the code

  • Lower panels: var(column) on x against var(row) on y, each axis min–max scaled within the panel; rows thinned by a deterministic stride to a 4,000-point budget.
  • Upper panels: Pearson r over pairwise-complete rows (all rows, not the thinned sample), and per colour group when a colour is set (GGally `ggpairs` style); cells tinted on the diverging ramp.
  • Diagonal: equal-width histograms ([a, b), last bin closed); per-group outlines share the overall bin edges.
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")
# controls: bins=sturges
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

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("pair-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["Adelie", "Chinstrap", "Gentoo"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
    if len(frame) <= k:
        return frame
    return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]
VARS = ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"]
LEVELS = freq_levels(df["species"])
per_panel = int(np.ceil(4000 / max(1, len(VARS) * (len(VARS) - 1) // 2)))  # the app's 4,000-point budget
def lower(x, y, **kw):
    pts = stride(pd.DataFrame({"x": x, "y": y}).dropna(), per_panel)  # deterministic stride
    g = stride(df.loc[pd.DataFrame({"x": x, "y": y}).dropna().index, "species"].astype(str), per_panel)
    plt.scatter(pts["x"], pts["y"], s=8, alpha=0.7, c=[PALETTE[LEVELS.index(v) % len(PALETTE)] if v in LEVELS else PALETTE[7] for v in g], edgecolors="none")
def upper(x, y, **kw):
    ax = plt.gca()
    both = pd.DataFrame({"x": x, "y": y}).dropna()  # Pearson r over pairwise-complete rows (all rows)
    lines = [f"r = {both['x'].corr(both['y']):.2f}"]
    g = df.loc[both.index, "species"].astype(str)
    for lv in LEVELS:
        sub = both[g == lv]
        if len(sub) > 2:
            lines.append(f"{lv}: {sub['x'].corr(sub['y']):.2f}")
    ax.text(0.5, 0.5, "\n".join(lines), transform=ax.transAxes, ha="center", va="center", fontsize=9)
    ax.grid(False)
def diag(x, **kw):
    v = x.dropna().to_numpy(dtype=float)
    plt.hist(v, bins=np.histogram_bin_edges(v, bins="sturges"), color=PALETTE[0], alpha=0.8, edgecolor="white", linewidth=0.5)
grid = sns.PairGrid(df[VARS], height=1.8, diag_sharey=False)
grid.map_lower(lower)
grid.map_upper(upper)
grid.map_diag(diag)
plt.show()

Needs pandas, numpy, matplotlib, seaborn · reads pair-plot-demo.csv · app theme from the optional codesplash helper

Relationships

svg#corr-heatmap

Correlation heatmap

Which numeric variables move together, and how strongly?

Demo data · seed 20261101 · 400 rows · default settings · 640 × 360

How to read it

  1. Find the darkest cells off the diagonal: the strongest correlations.
  2. Check colour for sign: one hue for positive, the other for negative.
  3. Use clustered order to see blocks of variables that move together.
  1. Callout 1: A dark off-diagonal cell: a strong correlation.
  2. Callout 2: The other hue: a negative correlation.
  3. Callout 3: Colour bar: the scale from −1 to 1.

Watch out

  • Pearson's r measures straight-line association only, so a U-shape can give r near zero.
  • Scanning many cells finds large values by chance. Adjust for multiplicity before claiming one.

Defaults

Coefficient
Pearson r
Pearson measures straight-line association; Spearman measures any steadily rising or falling trend.
Also: Spearman ρ
Cluster order
On
Reorder rows and columns so similar variables sit together.
Cells
Full matrix
Show the whole matrix or only its lower triangle.
Also: Lower triangle
Values in cells
On
Print the number in each cell.

Pinned in the code

  • Pearson r or Spearman ρ (Pearson on average ranks) over pairwise-complete rows; n per pair is in each cell's tooltip.
  • Diverging ramp centred at 0 (negative → warm, positive → cool), saturating at ±1.
  • Cluster order: average-linkage hierarchical clustering on 1 − |r| (R `hclust(as.dist(1 - abs(r)), "average")` leaf grouping), so related variables sit together.
  • Values are printed APA-style without the leading zero (.42, −.08).
# Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")
# controls: method=pearson, cluster=true, triangle=full, values=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap

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("corr-heatmap-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 cluster_order(m):
    """Leaf order of average-linkage clustering on 1 − |r| (the app's ordering; scipy's leaves differ)."""
    d = 1 - np.abs(np.nan_to_num(np.asarray(m, dtype=float)))
    clusters = [[i] for i in range(len(d))]
    while len(clusters) > 1:
        best, best_d = (0, 1), np.inf
        for a in range(len(clusters)):
            for b in range(a + 1, len(clusters)):
                dist = d[np.ix_(clusters[a], clusters[b])].mean()
                if dist < best_d:
                    best, best_d = (a, b), dist
        a, b = best
        merged = clusters[a] + clusters[b]
        clusters = [cl for i, cl in enumerate(clusters) if i not in (a, b)] + [merged]
    return clusters[0]
def apa_r(v):
    return "" if np.isnan(v) else f"{v:.2f}".replace("0.", ".", 1).replace("-", "\u2212")

VARS = ["income_k", "monthly_spend", "tenure_months", "site_visits", "churn_risk", "support_tickets", "age"]
r = df[VARS].corr(method="pearson", min_periods=3)  # pairwise-complete rows
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(VARS), 0.8 + 0.5 * len(VARS)))
sns.heatmap(r, ax=ax, mask=mask, vmin=-1, vmax=1, center=0, cmap=LinearSegmentedColormap.from_list("div", DIV), square=True, linewidths=0.5,
            annot=r.map(apa_r), fmt="", annot_kws={"fontsize": 8}, cbar_kws={"label": "Pearson r", "shrink": 0.7})
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib, seaborn · reads corr-heatmap-demo.csv · app theme from the optional codesplash helper

Relationships

svg#assoc-matrix

Association matrix

Which variables of any type are related, and how strongly?

Demo data · seed 20261101 · 500 rows · default settings · 640 × 360

How to read it

  1. Each cell is a strength between 0 and 1; the scale ignores direction.
  2. Check the note at the bottom: the measure depends on the column types.
  3. Use it to shortlist pairs, then look at each pair with a suited chart.
  1. Callout 1: A dark cell: a strong association.
  2. Callout 2: Which measure each kind of pair uses.
  3. Callout 3: Colour bar: from 0 to 1.

Watch out

  • Different measures aren't strictly comparable: a V of 0.3 and an r of 0.3 don't mean the same thing.

Defaults

Numeric pairs
|Pearson r|
Whether numeric pairs use Pearson or Spearman.
Also: |Spearman ρ|
Cluster order
Off
Reorder rows and columns so similar variables sit together.
Cells
Full matrix
Show the whole matrix or only its lower triangle.
Also: Lower triangle
Values in cells
On
Print the number in each cell.

Pinned in the code

  • Numeric × numeric: |Pearson r| (or |Spearman ρ|); categorical × categorical: Cramér's V with the Bergsma (2013) bias correction; numeric × categorical: correlation ratio η = √(SS_between / SS_total).
  • All over pairwise-complete rows (n in each tooltip); booleans count as categorical; every measure lies in [0, 1] so one sequential ramp fits.
  • The measures are not on a common scale of “effect”: compare within a measure, and treat this as a screening view (the profiler's association matrix).
# Association matrix — Codesplash Chart Lab (recipe "assoc-matrix")
# controls: numeric=pearson, cluster=false, triangle=full, values=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap

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("assoc-matrix-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])

_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 cluster_order(m):
    """Leaf order of average-linkage clustering on 1 − |r| (the app's ordering; scipy's leaves differ)."""
    d = 1 - np.abs(np.nan_to_num(np.asarray(m, dtype=float)))
    clusters = [[i] for i in range(len(d))]
    while len(clusters) > 1:
        best, best_d = (0, 1), np.inf
        for a in range(len(clusters)):
            for b in range(a + 1, len(clusters)):
                dist = d[np.ix_(clusters[a], clusters[b])].mean()
                if dist < best_d:
                    best, best_d = (a, b), dist
        a, b = best
        merged = clusters[a] + clusters[b]
        clusters = [cl for i, cl in enumerate(clusters) if i not in (a, b)] + [merged]
    return clusters[0]
def cramers_v(a, b):
    """Bias-corrected Cramér's V (Bergsma 2013) over rows with both values."""
    t = pd.crosstab(a, b)
    n = t.to_numpy().sum()
    r, k = t.shape
    if n == 0 or r < 2 or k < 2:
        return np.nan
    chi2 = stats.chi2_contingency(t, correction=False)[0]
    phi2 = max(0.0, chi2 / n - (r - 1) * (k - 1) / (n - 1))
    rc, kc = r - (r - 1) ** 2 / (n - 1), k - (k - 1) ** 2 / (n - 1)
    den = min(rc - 1, kc - 1)
    return np.sqrt(phi2 / den) if den > 0 else np.nan

def eta(y, g):
    """Correlation ratio η = √(SS_between / SS_total)."""
    d = pd.DataFrame({"y": y, "g": g}).dropna()
    if len(d) < 3 or d["g"].nunique() < 2:
        return np.nan
    m = d["y"].mean()
    ssb = d.groupby("g", observed=True)["y"].agg(lambda s: len(s) * (s.mean() - m) ** 2).sum()
    sst = ((d["y"] - m) ** 2).sum()
    return np.sqrt(ssb / sst) if sst > 0 else np.nan

def association(a, b, numeric_method):
    both = pd.DataFrame({"a": a, "b": b}).dropna()  # pairwise-complete rows
    na, nb = a.name in NUMERIC, b.name in NUMERIC
    if na and nb:
        return abs(both["a"].corr(both["b"], method=numeric_method)) if len(both) > 2 else np.nan
    if na:
        return eta(both["a"], both["b"].astype(str))
    if nb:
        return eta(both["b"], both["a"].astype(str))
    return cramers_v(both["a"].astype(str), both["b"].astype(str))

VARS = ["income_k", "monthly_spend", "tenure_months", "age", "segment", "plan", "region", "churned"]
NUMERIC = set(["income_k", "monthly_spend", "tenure_months", "age"])  # booleans count as categorical
m = pd.DataFrame([[1.0 if a == b else association(df[a], df[b], "pearson") for b in VARS] for a in VARS], index=VARS, columns=VARS)
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(VARS), 0.8 + 0.5 * len(VARS)))
sns.heatmap(m, ax=ax, mask=mask, vmin=0, vmax=1, cmap=LinearSegmentedColormap.from_list("seq", SEQ), square=True, linewidths=0.5,
            annot=True, fmt=".2f", annot_kws={"fontsize": 8}, cbar_kws={"label": "|r|, Cramér's V or η", "shrink": 0.7})
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib, scipy, seaborn · reads assoc-matrix-demo.csv · app theme from the optional codesplash helper

  • Geometry SQL is not emitted for the mixed-type matrix (Cramér's V and η need per-pair contingency tables); the numeric pairs match the correlation-heatmap SQL.

Relationships

svgbrushable#parallel-coords

Parallel coordinates

How do rows compare across many numeric variables at once?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Each line is one row, crossing every axis at its value.
  2. Lines running parallel between two axes: those variables move together; lines crossing in an X: they move oppositely.
  3. Drag on an axis to select a range and see those rows light up.
  1. Callout 1: Each axis is scaled to its own minimum and maximum.
  2. Callout 2: Lines crossing in an X: the two variables move oppositely.
  3. Callout 3: Colour marks the group.

Watch out

  • Axis order changes which patterns you can see, and many rows turn into a solid mass.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Each axis is min–max scaled to its own observed range (labels show min and max); a missing value breaks that row's line.
  • Line opacity ≈ 6/√n (clamped to [0.08, 0.5]) so dense regions read as density.
  • Brushing an axis selects rows whose value lies in the brushed range; brushes on several axes combine with AND.
# Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")
# 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("parallel-coords-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["origin"] = pd.Categorical(df["origin"].astype("string"), categories=["USA", "Europe", "Japan"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def stride(frame, k):
    if len(frame) <= k:
        return frame
    return frame.iloc[np.floor(np.arange(k) * len(frame) / k).astype(int)]

VARS = ["mpg", "cylinders", "displacement", "horsepower", "weight", "acceleration"]
d = stride(df, 1500)  # at most 1,500 lines (deterministic stride)
lo, hi = df[VARS].min(), df[VARS].max()
scaled = (d[VARS] - lo) / (hi - lo).replace(0, 1)  # each axis min–max scaled to its own range
alpha = float(np.clip(6 / np.sqrt(len(d)), 0.08, 0.5))
fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(VARS))
colours = {lv: PALETTE[i % len(PALETTE)] for i, lv in enumerate(freq_levels(df["origin"]))}
for row, g in zip(scaled.to_numpy(), d["origin"].astype(str)):
    ax.plot(xs, row, color=colours.get(g, PALETTE[7]), alpha=alpha, linewidth=0.8)  # a missing value breaks the line
for lv, col in colours.items():
    ax.plot([], [], color=col, label=lv)
ax.legend(title="origin", fontsize=8, loc="upper right")
for i, v in enumerate(VARS):
    ax.axvline(i, color="#6c727b", linewidth=0.8)
    ax.text(i, -0.04, f"{lo[v]:.4g}", ha="center", va="top", fontsize=7)
    ax.text(i, 1.04, f"{hi[v]:.4g}", ha="center", va="bottom", fontsize=7)
ax.set_xticks(xs, VARS)
ax.set_yticks([])
ax.set_ylim(-0.12, 1.12)
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads parallel-coords-demo.csv · app theme from the optional codesplash helper

Relationships

canvasbrushable#scatter-large

Large-n scatter (canvas)

What does the relationship look like across hundreds of thousands of rows?

Demo data · seed 20261101 · 200,000 rows · default settings · 640 × 360

How to read it

  1. Read the overall shape: too many points for individuals, so density is what you see.
  2. Use the colours to compare where groups sit.
  3. Look for sharp edges, which often mark caps or rounding in the data.
  1. Callout 1: Solid mass: lowering the opacity shows the density inside it.
  2. Callout 2: Sparse outer points: tails and possible errors.

Watch out

  • Groups drawn last cover earlier ones, so a colour's area can mislead. Check with a hexbin.

Defaults

Renderer
Auto (canvas > 5,000)
Draw as vector shapes or to a canvas; canvas stays fast with many points.
Also: Canvas · SVG (capped at 20,000)
Point size (px)
1.5
The size of each point.
Range 0.5 to 4, step 0.5
Opacity
0.3
How see-through points are; lower reveals density in crowded areas.
Range 0.05 to 1, step 0.05

Pinned in the code

  • Every row is drawn (no sampling) on canvas at 2× pixel density; overlapping marks build up density through the opacity.
  • Colours come from the same theme tokens as the SVG renderer, resolved to rgb() for the canvas and repainted on theme change.
  • Hover finds the nearest point within 8 px through a uniform-grid index over projected pixels (O(1) average).
  • Static renders (exports, golden tests) omit the paint time from the caption so they stay deterministic.
# Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")
# controls: renderer=auto, size=1.5, opacity=0.3
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("scatter-large-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["service"] = pd.Categorical(df["service"].astype("string"), categories=["Economy", "Comfort", "XL"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

d = df.dropna(subset=["distance_km", "fare_usd"])
fig, ax = plt.subplots(figsize=(7, 4.5))
# every row is drawn; rasterized=True keeps vector exports small (the app paints to canvas)
for i, lv in enumerate(freq_levels(d["service"])):
    m = d["service"].astype(str) == lv
    ax.scatter(d["distance_km"][m], d["fare_usd"][m], s=2.25, alpha=0.3, color=PALETTE[i % len(PALETTE)], edgecolors="none", rasterized=True, label=lv)
ax.legend(title="service", fontsize=8, markerscale=4)
ax.set_xlabel("distance_km")
ax.set_ylabel("fare_usd")
ax.set_title(f"{len(d):,} points", fontsize=9, loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads scatter-large-demo.csv · app theme from the optional codesplash helper

Composition

Parts of a whole and how totals build up.

7

Composition

svgbrushable#area-stacked

Stacked area

How does the mix of a total change over time?

Demo data · seed 20261101 · 210 rows · default settings · 640 × 360

How to read it

  1. Read the top edge for the total.
  2. Read the band thickness for each series; the bottom band shares a flat baseline.
  3. Switch to 100% to see the mix change without the total's growth.
  1. Callout 1: Top edge: the total.
  2. Callout 2: Bottom band: the easiest series to read, because its baseline is flat.
  3. Callout 3: Upper bands ride on the ones below; read their thickness.

Watch out

  • Upper bands look like they grow whenever the bands below grow. Compare thickness, not height.

Defaults

100 % stacked
Off
Show each series as a share of the total, so you compare the mix rather than the size.
Series shown
6
How many series to show; the rest are grouped.
Range 2 to 8, step 1

Pinned in the code

  • Value per (time, series) = sum of the value column (row count when none); times are the distinct x values.
  • Series ordered by total, largest at the bottom; beyond the limit they are pooled as “Other” (grey).
  • 100 %: each series divided by the time point's total.
  • Only the bottom series has a common baseline: compare upper layers with care, or use small multiples.
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")
# controls: percent=false, series=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("area-stacked-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

OTHER = "#9aa0a6"  # pooled levels
d = df[df["month"].notna()].copy()
d["_s"] = d["product_line"].astype(object).where(d["product_line"].notna(), "(missing)").astype(str)
d["_v"] = d["revenue_k"].where(np.isfinite(d["revenue_k"]), 0).fillna(0)  # value summed per time and series
totals = d.groupby("_s")["_v"].sum()
if isinstance(df["product_line"].dtype, pd.CategoricalDtype):  # declared order, else largest total first
    declared = [str(l) for l in df["product_line"].cat.categories]
    ranked = [l for l in declared if l in totals.index] + [s for s in totals.index if s not in declared]
else:
    ranked = sorted(totals.index, key=lambda s: (-totals[s], s))
keep = ranked[: 6 - 1] if len(ranked) > 6 else ranked  # beyond the limit → "Other"
series = keep + (["Other"] if len(ranked) > len(keep) else [])
d["_s"] = d["_s"].where(d["_s"].isin(keep), "Other")
wide = d.pivot_table(index="month", columns="_s", values="_v", aggfunc="sum", fill_value=0).reindex(columns=series, fill_value=0).sort_index()
colors = [OTHER if s == "Other" else PALETTE[i % len(PALETTE)] for i, s in enumerate(series)]
hatches = [SERIES_HATCHES[7 if s == "Other" else i % 8] for i, s in enumerate(series)]  # texture per layer, as in the app

fig, ax = plt.subplots(figsize=(8, 4.5))
ax.stackplot(wide.index, wide.T.to_numpy(), labels=series, colors=colors, alpha=0.9, hatch=hatches, hatchcolor=HATCH_INK, linewidth=0)  # first series at the bottom
ax.set_xlabel("month")
ax.set_ylabel("revenue_k")
ax.legend(title="product_line", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads area-stacked-demo.csv · app theme from the optional codesplash helper

Composition

svg#treemap

Treemap

How is a total split across a hierarchy of categories?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Read rectangle area as value.
  2. Read colour as the top-level group.
  3. Compare large blocks; use labels for the small ones.
  1. Callout 1: A big rectangle: a large share of the total.
  2. Callout 2: Heading: the top-level group and its share.

Watch out

  • People compare areas poorly. Use a sorted bar chart when exact differences matter.

Defaults

Children per node
10
How many sub-levels to show under each parent; the rest are grouped.
Range 3 to 20, step 1

Pinned in the code

  • Area ∝ sum of the size column (row count when none); node order by value.
  • Layout: squarified tiling (Bruls, Huizing & van Wijk 2000) with d3-hierarchy's golden-ratio target aspect.
  • Beyond the per-node limit, the smallest children are pooled into “Other” (grey).
  • Labels are drawn only where they fit; tooltips carry the full path, value and share of total.
# Treemap — Codesplash Chart Lab (recipe "treemap")
# controls: maxChildren=10
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("treemap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

def tree_nodes(frame, levels, size=None, max_children=10):
    """Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
    children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
    missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
    w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
    w = w.where(np.isfinite(w), 0).fillna(0)
    keep = w > 0
    sub = frame.loc[keep, levels].astype(object)
    paths = sub.where(sub.notna(), "(missing)").astype(str)
    w = w[keep]
    nodes = []

    def walk(index, depth, parent, top):
        if depth == len(levels):
            return
        key = paths.loc[index, levels[depth]]
        sums = w.loc[index].groupby(key).sum()
        kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
        shown = kids[: max_children - 1] if len(kids) > max_children else kids
        entries = [(name, value, False) for name, value in shown]
        if len(kids) > len(shown):
            entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
        entries.sort(key=lambda e: (-e[1], e[2]))  # d3 re-sorts siblings by value; "Other" last among ties
        for name, value, pooled in entries:
            nid = f"{parent} › {name}"
            nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
            if not pooled:
                walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)

    walk(paths.index, 0, "All", None)
    return pd.DataFrame(nodes)

PHI = (1 + 5 ** 0.5) / 2


def squarify(values, x0, y0, x1, y1, ratio=PHI):
    """d3.treemapSquarify: rows grow while their worst aspect ratio improves (Bruls et al. 2000)."""
    out, i0, n, value = [], 0, len(values), float(sum(values))
    while i0 < n:
        dx, dy = max(x1 - x0, 1e-9), max(y1 - y0, 1e-9)
        s = lo = hi = values[i0]
        i1 = i0 + 1
        alpha = max(dy / dx, dx / dy) / (value * ratio)
        best = max(hi / (s * s * alpha), s * s * alpha / lo)
        while i1 < n:
            v = values[i1]
            beta = (s + v) ** 2 * alpha
            r = max(max(hi, v) / beta, beta / min(lo, v))
            if r > best:
                break
            s, lo, hi, best, i1 = s + v, min(lo, v), max(hi, v), r, i1 + 1
        if dx < dy:  # a strip across the top, nodes side by side
            yb, x = y0 + dy * s / value, x0
            for v in values[i0:i1]:
                out.append((x, y0, x + dx * v / s, yb))
                x += dx * v / s
            y0 = yb
        else:  # a strip down the left, nodes stacked
            xb, y = x0 + dx * s / value, y0
            for v in values[i0:i1]:
                out.append((x0, y, xb, y + dy * v / s))
                y += dy * v / s
            x0 = xb
        value -= s
        i0 = i1
    return out


def layout_treemap(nodes, W=960, H=540, pad=2, header=17):
    """Nested squarified rectangles in a W × H canvas (y down), with the app's 2 px padding and a
    17 px header strip on top-level groups."""
    parents = set(nodes["parent"])
    rects = {}

    def place(parent, x0, y0, x1, y1):
        kids = nodes[nodes["parent"] == parent]
        for nd, (a, b, c, d) in zip(kids.itertuples(), squarify(kids["value"].tolist(), x0, y0, x1, y1)):
            a, b, c, d = a + pad / 2, b + pad / 2, c - pad / 2, d - pad / 2
            rects[nd.id] = (a, b, c, d)
            if nd.id in parents:
                top = header if nd.depth == 1 and c - a > 40 else pad
                place(nd.id, a + pad, b + top, c - pad, d - pad)

    place("All", 0, 0, W, H)
    return nodes.assign(**{k: [rects[i][j] for i in nodes["id"]] for j, k in enumerate(["x0", "y0", "x1", "y1"])})

OTHER = "#9aa0a6"  # pooled levels
nodes = tree_nodes(df, ["category", "subcategory"], "revenue", max_children=10)
rects = layout_treemap(nodes)
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
parents = set(nodes["parent"])
total = nodes.loc[nodes["depth"] == 1, "value"].sum()

from matplotlib.patches import Rectangle
fig, ax = plt.subplots(figsize=(9.6, 5.4))
for nd in rects.itertuples():
    w, h = nd.x1 - nd.x0, nd.y1 - nd.y0
    leaf = nd.id not in parents
    color = top_color[nd.top]
    ax.add_patch(Rectangle((nd.x0, nd.y0), w, h, facecolor=color, alpha=0.88 if leaf else 0.18, edgecolor="none"))
    if leaf and w > 60 and h > 22:  # labels only where they fit
        ax.text(nd.x0 + 4, nd.y0 + 4, f"{nd.label}\n{nd.value / total:.1%}", ha="left", va="top", fontsize=7, color="white")
    elif not leaf and nd.depth == 1 and w > 40:
        ax.text(nd.x0 + 4, nd.y0 + 3, nd.label, ha="left", va="top", fontsize=8, fontweight="bold")
ax.set_xlim(0, 960)
ax.set_ylim(540, 0)  # y down, like the SVG
ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads treemap-demo.csv · app theme from the optional codesplash helper

  • Layout: the d3 squarify algorithm (golden-ratio target) re-implemented inline in Python and R; padding approximates the app's.

Composition

svg#sunburst

Sunburst

How is a total split across two or three levels of categories?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Start at the centre: the inner ring is the top level.
  2. Move outward: each outer ring splits the slice inside it.
  3. Read arc length as share; the legend lists the top-level shares.
  1. Callout 1: The centre shows the total.
  2. Callout 2: Outer rings split the segment inside them.
  3. Callout 3: Legend: top-level shares.

Watch out

  • Outer arcs look bigger than inner arcs of the same share. Use an icicle for accurate comparison.

Defaults

Children per node
8
How many sub-levels to show under each parent; the rest are grouped.
Range 3 to 20, step 1

Pinned in the code

  • Angle ∝ sum of the size column (row count when none); rings are equal width, one per level; the centre shows the total.
  • Children sorted by value; beyond the limit pooled as “Other”.
  • Colour follows the top-level ancestor, lighter for deeper rings; labels only on arcs wide enough to hold them.
  • Angles are harder to compare than lengths — prefer an icicle or treemap for precise comparison.

Use with care

Outer-ring angles are hard to compare; use the icicle for precise reading.

# Sunburst — Codesplash Chart Lab (recipe "sunburst")
# controls: maxChildren=8
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("sunburst-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["channel"] = pd.Categorical(df["channel"].astype("string"), categories=["Web", "App", "Store"])

def tree_nodes(frame, levels, size=None, max_children=10):
    """Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
    children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
    missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
    w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
    w = w.where(np.isfinite(w), 0).fillna(0)
    keep = w > 0
    sub = frame.loc[keep, levels].astype(object)
    paths = sub.where(sub.notna(), "(missing)").astype(str)
    w = w[keep]
    nodes = []

    def walk(index, depth, parent, top):
        if depth == len(levels):
            return
        key = paths.loc[index, levels[depth]]
        sums = w.loc[index].groupby(key).sum()
        kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
        shown = kids[: max_children - 1] if len(kids) > max_children else kids
        entries = [(name, value, False) for name, value in shown]
        if len(kids) > len(shown):
            entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
        entries.sort(key=lambda e: (-e[1], e[2]))  # d3 re-sorts siblings by value; "Other" last among ties
        for name, value, pooled in entries:
            nid = f"{parent} › {name}"
            nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
            if not pooled:
                walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)

    walk(paths.index, 0, "All", None)
    return pd.DataFrame(nodes)

def partition(nodes):
    """Each node's span [x0, x1) as a share of the total; children split the parent's span by value."""
    span = {"All": (0.0, 1.0)}
    pvalue = {"All": nodes.loc[nodes["depth"] == 1, "value"].sum()}
    cursor = {"All": 0.0}
    x0s, x1s = [], []
    for nd in nodes.itertuples():  # depth-first: parents come before their children
        p0, p1 = span[nd.parent]
        width = (p1 - p0) * nd.value / pvalue[nd.parent]
        x0 = p0 + cursor[nd.parent]
        cursor[nd.parent] += width
        span[nd.id], pvalue[nd.id], cursor[nd.id] = (x0, x0 + width), nd.value, 0.0
        x0s.append(x0)
        x1s.append(x0 + width)
    return nodes.assign(x0=x0s, x1=x1s)

OTHER = "#9aa0a6"  # pooled levels
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
nodes = partition(nodes)
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
D = 3  # rings: equal width, the hole is one ring wide

from matplotlib.patches import Wedge
fig, ax = plt.subplots(figsize=(6.5, 6.5))
for nd in nodes.itertuples():
    r_out = (nd.depth + 1) / (D + 1)
    # clockwise from 12 o'clock: matplotlib angles run counter-clockwise from 3 o'clock
    ax.add_patch(Wedge((0, 0), r_out, 90 - 360 * nd.x1, 90 - 360 * nd.x0, width=1 / (D + 1),
                       facecolor=top_color[nd.top], alpha=ALPHA.get(nd.depth, 0.36), edgecolor=plt.rcParams["axes.facecolor"], linewidth=0.8))
    span = (nd.x1 - nd.x0) * 2 * np.pi * (r_out - 0.5 / (D + 1))
    if span > 0.18:  # labels only on arcs wide enough
        a = np.pi / 2 - np.pi * (nd.x0 + nd.x1)
        r = r_out - 0.5 / (D + 1)
        ax.text(r * np.cos(a), r * np.sin(a), nd.label, ha="center", va="center", fontsize=6.5)
total = nodes.loc[nodes["depth"] == 1, "value"].sum()
ax.text(0, 0, f"{total:,.0f}", ha="center", va="center", fontsize=11, fontweight="bold")  # the centre shows the total
ax.set_xlim(-1.02, 1.02)
ax.set_ylim(-1.02, 1.02)
ax.set_aspect("equal")
ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads sunburst-demo.csv · app theme from the optional codesplash helper

  • plotly's sunburst lays slices out counter-clockwise; the app (and the matplotlib/ggplot2 versions) go clockwise from 12 o'clock.

Composition

svg#icicle

Icicle

How is a total split across levels, read precisely along one axis?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360

How to read it

  1. Read columns left to right: each column is one level deeper.
  2. Read a rectangle's height as its share.
  3. Follow one colour rightward to see how that group breaks down.
  1. Callout 1: Leftmost column: the top level.
  2. Callout 2: Next column: the split inside it.
  3. Callout 3: Thin rows: small leaves, labelled only when they fit.

Watch out

  • Small rectangles lose their labels; hover or filter to read them.

Defaults

Children per node
8
How many sub-levels to show under each parent; the rest are grouped.
Range 3 to 20, step 1

Pinned in the code

  • Height ∝ sum of the size column (row count when none); columns are the levels, outer first.
  • Children sorted by value; beyond the limit pooled as “Other”.
  • Same partition as the sunburst, drawn on a linear axis so values can be compared by length.
# Icicle — Codesplash Chart Lab (recipe "icicle")
# controls: maxChildren=8
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("icicle-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["channel"] = pd.Categorical(df["channel"].astype("string"), categories=["Web", "App", "Store"])

def tree_nodes(frame, levels, size=None, max_children=10):
    """Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
    children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
    missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
    w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
    w = w.where(np.isfinite(w), 0).fillna(0)
    keep = w > 0
    sub = frame.loc[keep, levels].astype(object)
    paths = sub.where(sub.notna(), "(missing)").astype(str)
    w = w[keep]
    nodes = []

    def walk(index, depth, parent, top):
        if depth == len(levels):
            return
        key = paths.loc[index, levels[depth]]
        sums = w.loc[index].groupby(key).sum()
        kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
        shown = kids[: max_children - 1] if len(kids) > max_children else kids
        entries = [(name, value, False) for name, value in shown]
        if len(kids) > len(shown):
            entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
        entries.sort(key=lambda e: (-e[1], e[2]))  # d3 re-sorts siblings by value; "Other" last among ties
        for name, value, pooled in entries:
            nid = f"{parent} › {name}"
            nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
            if not pooled:
                walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)

    walk(paths.index, 0, "All", None)
    return pd.DataFrame(nodes)

def partition(nodes):
    """Each node's span [x0, x1) as a share of the total; children split the parent's span by value."""
    span = {"All": (0.0, 1.0)}
    pvalue = {"All": nodes.loc[nodes["depth"] == 1, "value"].sum()}
    cursor = {"All": 0.0}
    x0s, x1s = [], []
    for nd in nodes.itertuples():  # depth-first: parents come before their children
        p0, p1 = span[nd.parent]
        width = (p1 - p0) * nd.value / pvalue[nd.parent]
        x0 = p0 + cursor[nd.parent]
        cursor[nd.parent] += width
        span[nd.id], pvalue[nd.id], cursor[nd.id] = (x0, x0 + width), nd.value, 0.0
        x0s.append(x0)
        x1s.append(x0 + width)
    return nodes.assign(x0=x0s, x1=x1s)

OTHER = "#9aa0a6"  # pooled levels
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
nodes = partition(nodes)
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
LEVELS = ["category", "subcategory", "channel"]
D = len(LEVELS)

from matplotlib.patches import Rectangle
fig, ax = plt.subplots(figsize=(9, 5.4))
for nd in nodes.itertuples():
    x0, h = (nd.depth - 1) / D, nd.x1 - nd.x0  # one column per level, height ∝ value
    ax.add_patch(Rectangle((x0, nd.x0), 1 / D, h, facecolor=top_color[nd.top], alpha=ALPHA.get(nd.depth, 0.36),
                           edgecolor=plt.rcParams["axes.facecolor"], linewidth=1))
    if h > 0.035:
        ax.text(x0 + 0.01, nd.x0 + h / 2, f"{nd.label}  {nd.value:,.0f}", va="center", fontsize=7)
for d, name in enumerate(LEVELS):
    ax.text((d + 0.02) / D, -0.015, name, va="bottom", fontsize=8, color="0.45")  # level names as column headers
ax.set_xlim(0, 1)
ax.set_ylim(1, -0.06)  # outer level first, largest at the top
ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads icicle-demo.csv · app theme from the optional codesplash helper

Composition

svg#waterfall

Waterfall

Which drivers explain the change from a starting total to an ending total?

Demo data · seed 20261101 · 29 rows · default settings · 640 × 360

How to read it

  1. Start at the first solid bar: the opening total.
  2. Follow the floating bars: each adds or subtracts from where the last ended.
  3. End at the closing total, and check the subtotals along the way.
  1. Callout 1: The opening total.
  2. Callout 2: A floating bar: an increase or a decrease.
  3. Callout 3: The closing total.

Watch out

  • The order of drivers changes how each looks; keep a meaningful order, such as the one used in your accounts.

Defaults

Closing total
On
Add a final bar with the ending total.
Value labels
On
Print each value on the chart.

Pinned in the code

  • Steps keep their order (declared levels, else first appearance); values are summed per step.
  • Totals with a value set the running level (bar from 0); totals without a value are subtotals at the running level; other steps add their change.
  • The closing total equals the opening total plus all changes.
  • Increases use the pass colour, decreases the fail colour; dashed connectors carry the running level.
# Waterfall — Codesplash Chart Lab (recipe "waterfall")
# controls: end=true, labels=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("waterfall-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["driver"] = pd.Categorical(df["driver"].astype("string"), categories=["FY2025 revenue", "Price", "Volume", "Mix", "Gross", "FX", "Churn", "New logos"])

d = df.copy()
d["_step"] = d["driver"].astype(object).where(d["driver"].notna(), "(missing)").astype(str)
v = pd.to_numeric(d["change_m"], errors="coerce")
d["_v"] = v.where(np.isfinite(v))
d["_total"] = d["is_total"].astype(object) == True  # noqa: E712
seen = list(pd.unique(d["_step"]))  # first appearance
if isinstance(df["driver"].dtype, pd.CategoricalDtype):  # declared order first
    declared = [str(l) for l in df["driver"].cat.categories]
    seen = [l for l in declared if l in seen] + [s for s in seen if s not in declared]
g = d.groupby("_step", sort=False)
steps = pd.DataFrame({"value": g["_v"].sum(min_count=1), "total": g["_total"].any()}).reindex(seen)  # summed per step

rows, running = [], 0.0
for name, st in steps.iterrows():
    if st["total"]:  # totals with a value set the level; without one they are subtotals
        if pd.notna(st["value"]):
            running = st["value"]
        rows.append((name, "total" if pd.notna(st["value"]) else "subtotal", running, 0.0, running))
    else:
        delta = 0.0 if pd.isna(st["value"]) else st["value"]
        rows.append((name, "increase" if delta >= 0 else "decrease", delta, running, running + delta))
        running += delta
rows.append(("End", "total", running, 0.0, running))  # closing total
bars = pd.DataFrame(rows, columns=["step", "kind", "value", "start", "end"])
KIND_COLOR = {"increase": "#187c49", "decrease": "#c9302d", "total": PALETTE[0], "subtotal": PALETTE[0] + "8c"}

fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(bars))
lo = bars[["start", "end"]].min(axis=1)
hi = bars[["start", "end"]].max(axis=1)
ax.bar(xs, hi - lo, bottom=lo, width=0.72, color=[KIND_COLOR[k] for k in bars["kind"]])
for i in range(len(bars) - 1):  # dashed connectors carry the running level
    ax.plot([i + 0.36, i + 0.64], [bars["end"][i]] * 2, color=plt.rcParams["axes.edgecolor"], linestyle="--", linewidth=0.8)
for i, b in bars.iterrows():
    text = f"{b.value:+,.4g}" if b.kind in ("increase", "decrease") else f"{b.value:,.4g}"
    ax.annotate(text, (i, max(b.start, b.end)), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=7)
ax.axhline(0, color=plt.rcParams["axes.edgecolor"], linewidth=0.8)
ax.set_xticks(xs, bars["step"], rotation=30, ha="right")
ax.set_ylabel("change_m")
plt.show()

Needs pandas, numpy, matplotlib · reads waterfall-demo.csv · app theme from the optional codesplash helper

Composition

svg#funnel

Funnel

Where do people drop out of a multi-step process?

Demo data · seed 20261101 · 4,322 rows · default settings · 640 × 360

How to read it

  1. Read top to bottom: each row is a stage.
  2. Read the share on the right against the first stage.
  3. Read the step conversion for the biggest drop between neighbours.
  1. Callout 1: The first stage: everyone who started.
  2. Callout 2: The biggest narrowing: the step to investigate.
  3. Callout 3: Overall share, and share of the previous stage.

Watch out

  • It compares counts at one time. Users still in progress can look like drop-off unless you fix a window.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Stages in declared level order (else first appearance); value = sum of the count column or rows per stage.
  • Overall conversion = stage / first stage; step conversion = stage / previous stage.
  • Bar width ∝ value on a linear scale (not area); connectors show the step loss.
  • A funnel assumes each stage is a subset of the previous one; check that the counts never increase.
# Funnel — Codesplash Chart Lab (recipe "funnel")
# 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("funnel-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["stage"] = pd.Categorical(df["stage"].astype("string"), categories=["Visited", "Viewed product", "Added to cart", "Checkout", "Purchased"])

d = df[df["stage"].notna()].copy()
d["_k"] = d["stage"].astype(str)
d["_v"] = 1.0  # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum()  # first-appearance order
if isinstance(df["stage"].dtype, pd.CategoricalDtype):  # declared order first
    declared = [str(l) for l in df["stage"].cat.categories]
    sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
f = sums.rename("value").rename_axis("stage").reset_index()
f["overall"] = f["value"] / f["value"].iloc[0]  # conversion from the first stage
f["step"] = (f["value"] / f["value"].shift(1)).fillna(1.0)  # conversion from the previous stage

fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(f))[::-1]  # first stage on top
ax.barh(y, f["value"], left=-f["value"] / 2, color=PALETTE[0], height=0.72)  # width ∝ value, centred
for yi, r in zip(y, f.itertuples()):
    ax.text(0, yi, f"{r.value:,.0f}", ha="center", va="center", color="white", fontsize=8, fontweight="bold")
    ax.text(f["value"].max() / 2 * 1.04, yi, f"{r.overall:.1%} of first · {r.step:.1%} of previous", va="center", fontsize=7.5)
ax.set_yticks(y, f["stage"])
ax.set_xticks([])
ax.set_xlim(-f["value"].max() / 2 * 1.05, f["value"].max() * 1.15)
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads funnel-demo.csv · app theme from the optional codesplash helper

Composition

svg#pie

Pie / donut

What share of the whole does each of a few categories hold?

Demo data · seed 20261101 · 2,000 rows · default settings · 640 × 360

How to read it

  1. Read the slices as shares of a whole.
  2. Compare with 25% and 50%: those angles are the easiest to judge.
  3. Use the legend for exact percentages.
  1. Callout 1: Largest first, starting at twelve o'clock.
  2. Callout 2: The centre shows the total.
  3. Callout 3: Legend: the exact share per slice.

Watch out

  • People compare angles poorly: with more than a few slices, a bar chart is clearer.

Defaults

Donut
On
Cut a hole in the middle, with the total shown there.
Percent labels (≥ 6 %)
On
Print the share on slices large enough to hold a label.
Slices (incl. Other)
6
How many slices to draw, with Other as the last.
Range 2 to 8, step 1

Pinned in the code

  • Share = value / total over non-missing categories; slices sorted by value, clockwise from 12 o'clock.
  • At most 6 slices: the top 5 levels plus “Other” (grey) when there are more.
  • Percent labels are drawn on slices of at least 6 %; every share is in the legend.

Use with care

Consider a bar chart: angles are harder to compare than lengths.

# Pie / donut — Codesplash Chart Lab (recipe "pie")
# controls: donut=true, labels=true, top=6
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("pie-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

OTHER = "#9aa0a6"  # pooled levels
d = df[df["browser"].notna()].copy()
d["_k"] = d["browser"].astype(str)
d["_v"] = 1.0  # no value column: count rows
sums = d.groupby("_k", sort=False)["_v"].sum()  # first-appearance order
if isinstance(df["browser"].dtype, pd.CategoricalDtype):  # declared order first
    declared = [str(l) for l in df["browser"].cat.categories]
    sums = sums.reindex([l for l in declared if l in sums.index] + [s for s in sums.index if s not in declared])
s = sums[sums > 0].rename("value").rename_axis("label").reset_index()
s = s.sort_values(["value", "label"], ascending=[False, True])  # largest first, ties alphabetical
if len(s) > 6:  # top 6 − 1 levels plus "Other"
    s = pd.concat([s.iloc[: 6 - 1], pd.DataFrame({"label": ["Other"], "value": [s["value"].iloc[6 - 1:].sum()]})], ignore_index=True)
s["share"] = s["value"] / s["value"].sum()
colors = [OTHER if l == "Other" else PALETTE[i % len(PALETTE)] for i, l in enumerate(s["label"])]

fig, ax = plt.subplots(figsize=(7, 4.5))
wedges, *_ = ax.pie(
    s["value"], colors=colors, startangle=90, counterclock=False,  # clockwise from 12 o'clock
    wedgeprops=dict(width=0.42, edgecolor=plt.rcParams["axes.facecolor"], linewidth=1),
    autopct=lambda p: f"{p:.0f}%" if p >= 6 else "", pctdistance=0.79, textprops=dict(fontsize=8, color="white"),  # labels on slices ≥ 6 %
)
ax.legend(wedges, [f"{l}  {sh:.1%}" for l, sh in zip(s["label"], s["share"])], loc="center left", bbox_to_anchor=(1.0, 0.5))
ax.set_aspect("equal")
plt.show()

Needs pandas, numpy, matplotlib · reads pie-demo.csv · app theme from the optional codesplash helper

Time series

Trends, seasonality and change over time.

33

Time series

svgbrushable#line

Line chart

How does a value change over time, and how do series compare?

Demo data · seed 20261101 · 3,276 rows · default settings · 640 × 360

How to read it

  1. Read the overall direction first, then the repeating ups and downs.
  2. Compare series at the same date, and check the band for how uncertain each one is.
  3. Look at what happens around marked events, without assuming they caused it.
  1. Callout 1: A series' peak; read it against the others at the same date.
  2. Callout 2: Band: the uncertainty or range around the line.
  3. Callout 3: An event marker: a change after it isn't proof of cause.

Watch out

  • Resampling changes what you see: weekly means hide daily spikes.
  • A y axis zoomed away from zero exaggerates small changes.

Defaults

Resample
ISO week
Combine values into days, weeks or months before plotting, to reduce noise.
Also: None (raw) · Day · Month · Quarter
Band
Mean ± 95% CI
What the shaded band around the line shows.
Also: Min–max · None
Points (≤ 120 per series)
Off
Mark individual points when a series has few enough.
Event markers
On
Draw vertical lines at the events you supply.

Pinned in the code

  • Resampling groups rows by the UTC period start (day; ISO week starting Monday; calendar month or quarter) and plots the period mean at the period start.
  • Band “Mean ± 95% CI”: mean ± t(0.975, n − 1)·s/√n of the rows in each period (s with n − 1); periods with one row have no band. Band “Min–max”: the period's range.
  • Without resampling, rows that share a timestamp are averaged and no band is drawn. The first and last periods may be partial (fewer days), which shows as a step at the ends.
  • Event markers: every row whose event column is non-empty draws a dashed reference line labelled with the event and date.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Line chart — Codesplash Chart Lab (recipe "line")
# controls: period=week, band=ci, points=false, events=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("line-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
    """UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
    if period == "none":
        return t
    day = t.dt.floor("D")
    if period == "day":
        return day
    if period == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time

def resample(d, time, value, period, level=0.95):
    """Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
    d = d.dropna(subset=[time, value])
    s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
    s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
    half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
    return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)

PERIOD, BAND = "week", "ci"  # without resampling, rows sharing a timestamp are averaged and no band is drawn
series = [(lv, df[df["region"].astype(str) == lv]) for lv in freq_levels(df["region"], 8)]

fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):
    s = resample(d, "date", "sales", PERIOD)
    col = PALETTE[i % len(PALETTE)]
    if BAND == "ci":  # mean ± t(0.975, n − 1)·s/√n per period
        ax.fill_between(s["t"], s["lo"], s["hi"], color=col, alpha=0.15, linewidth=0)
    elif BAND == "minmax":
        ax.fill_between(s["t"], s["min"], s["max"], color=col, alpha=0.15, linewidth=0)
    ax.plot(s["t"], s["mean"], color=col, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if len(series) > 1 else "-", label=name)  # dash (and marker) per series, as in the app
events = df.loc[df["event"].notna() & (df["event"].astype(str) != ""), ["date", "event"]].drop_duplicates()
for _, e in events.iterrows():  # dashed reference line per event
    ax.axvline(e["date"], color=REF, linestyle="--", linewidth=1)
    ax.annotate(f"{e["event"]} · {e["date"]:%Y-%m-%d}", (e["date"], 0.98), xycoords=("data", "axes fraction"), ha="left", va="top", fontsize=8, xytext=(3, 0), textcoords="offset points")
ax.set_ylabel("sales")
ax.set_xlabel("date (UTC)")
ax.legend(title="region", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads line-demo.csv · app theme from the optional codesplash helper

Time series

svgbrushable#area

Area chart

How large is a quantity over time (and how do overlapping series compare)?

Demo data · seed 20261101 · 728 rows · default settings · 640 × 360

How to read it

  1. Read the top edge of each area as its value.
  2. Where areas overlap, follow the edges: the series aren't stacked.
  3. Check the baseline: a filled area implies a meaningful zero.
  1. Callout 1: This series' top edge is its value.
  2. Callout 2: Overlap: both series are measured from zero.
  3. Callout 3: Series cross here.

Watch out

  • If zero means nothing for this measure (temperature, an index), use a line instead.

Defaults

Resample
ISO week
Combine values into days, weeks or months before plotting, to reduce noise.
Also: None (raw) · Day · Month · Quarter
Zero baseline
On
Start the y axis at zero.
Fill opacity
0.2
How see-through the filled areas are.
Range 0.1 to 0.8, step 0.05

Pinned in the code

  • Same resampling as the line chart (UTC period start; ISO weeks; period mean).
  • Areas are filled down to zero by default, so the area is proportional to the value; turn the baseline off only for values far from zero.
  • Series overlap (they are not stacked); see the stacked-area recipe for parts of a whole.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.

Use with care

Filled areas imply magnitude from zero — keep the zero baseline unless the values are far from zero.

# Area chart — Codesplash Chart Lab (recipe "area")
# controls: period=week, zero=true, opacity=0.2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("area-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
df["platform"] = pd.Categorical(df["platform"].astype("string"), categories=["Web", "App"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
    """UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
    if period == "none":
        return t
    day = t.dt.floor("D")
    if period == "day":
        return day
    if period == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time

def resample(d, time, value, period, level=0.95):
    """Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
    d = d.dropna(subset=[time, value])
    s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
    s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
    half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
    return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)

PERIOD = "week"
series = [(lv, df[df["platform"].astype(str) == lv]) for lv in freq_levels(df["platform"], 8)]
fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):  # overlapping areas, not stacked
    s = resample(d, "day", "active_users", PERIOD)
    col = PALETTE[i % len(PALETTE)]
    ax.fill_between(s["t"], 0, s["mean"], color=col, alpha=0.2, linewidth=0)  # filled down to zero: area ∝ value
    ax.plot(s["t"], s["mean"], color=col, linewidth=1.6, label=name)
ax.set_ylabel("active_users")
ax.set_xlabel("day (UTC)")
ax.legend(title="platform", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads area-demo.csv · app theme from the optional codesplash helper

Time series

svgbrushable#step

Step chart

How does a level that changes at discrete moments evolve (stock, price, running total)?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Read a flat run as a level holding until the next change.
  2. Read a vertical jump as the moment the level changed.
  3. Compare when series change, not only how much.
  1. Callout 1: A vertical drop: the value changed at this moment.
  2. Callout 2: A flat run: no change until the next step.

Watch out

  • Don't interpolate between steps: the value held, it did not slide.

Defaults

Plot
Value (step-after)
What to plot: the values, their running sum or a running count.
Also: Cumulative sum · Cumulative rows
Change markers
Off
Mark the moments when the level changes.
Zero baseline
On
Start the y axis at zero.

Pinned in the code

  • Step-after (right-continuous): a value recorded at time t holds until the next timestamp (matplotlib `where="post"`, ggplot2 `geom_step(direction = "hv")`); the last level extends to the end of the axis.
  • Rows sharing a timestamp are averaged in value mode; cumulative modes add them in time order.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Step chart — Codesplash Chart Lab (recipe "step")
# controls: mode=value, markers=false, zero=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("step-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["timestamp"] = pd.to_datetime(df["timestamp"])
df["sku"] = pd.Categorical(df["sku"].astype("string"), categories=["A-100", "B-220"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

MODE = "value"  # "value" (step-after), "cumsum" or "count" (cumulative rows)
series = [(lv, df[df["sku"].astype(str) == lv]) for lv in freq_levels(df["sku"], 8)]
end = df["timestamp"].max()  # the last level extends to the end of the axis
fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series):
    d = d.dropna(subset=["timestamp"] + (["on_hand"] if MODE != "count" else [])).sort_values("timestamp", kind="stable")
    if MODE == "value":  # rows sharing a timestamp are averaged
        s = d.groupby("timestamp")["on_hand"].mean()
    elif MODE == "cumsum":
        s = d.groupby("timestamp")["on_hand"].sum().cumsum()
    else:
        s = d.groupby("timestamp").size().cumsum()
    t = list(s.index) + [end]
    v = list(s.to_numpy()) + [s.iloc[-1]]
    ax.step(t, v, where="post", color=PALETTE[i % len(PALETTE)], linewidth=1.6, label=name)  # right-continuous
ax.set_ylim(bottom=min(0, ax.get_ylim()[0]))  # zero baseline
ax.set_xlabel("timestamp (UTC)")
ax.set_ylabel("on_hand" if MODE == "value" else ("cumulative " + "on_hand" if MODE == "cumsum" else "cumulative rows"))
ax.legend(title="sku", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads step-demo.csv · app theme from the optional codesplash helper

Time series

svg#small-multiples

Small multiples

How do many series compare without tangling into spaghetti?

Demo data · seed 20261101 · 288 rows · default settings · 640 × 360

How to read it

  1. Compare shapes across panels, all with the same time axis.
  2. With a shared y scale, compare levels too; with free scales, compare only shapes.
  3. Read the change in each panel's corner.
  1. Callout 1: Panel title and its overall change.
  2. Callout 2: Same scale: this series sits higher than its neighbours.
  3. Callout 3: A flat panel on a shared scale: its own movement may be hidden.

Watch out

  • Free y scales make every series look equally large. Check the axes before you compare levels.

Defaults

Free y scales
Off
Each panel gets its own y range (compare shapes, not levels)
Resample
None (raw)
Combine values into days, weeks or months before plotting, to reduce noise.
Also: Day · ISO week · Month · Quarter
Colour
By panel
How bars or lines are coloured.
Also: Single

Pinned in the code

  • Panels share the x axis; the y scale is shared unless “Free y scales” is on (then compare shapes only).
  • Panel header: group name and the change from the first to the last plotted value.
  • Panels follow the group's level order (declared order, else descending frequency).
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")
# controls: free=false, period=none, color=panel
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("small-multiples-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
df["product_line"] = pd.Categorical(df["product_line"].astype("string"), categories=["Analytics", "Compute", "Storage", "Security", "Networking", "Support"])

def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
    """UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
    if period == "none":
        return t
    day = t.dt.floor("D")
    if period == "day":
        return day
    if period == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time

def resample(d, time, value, period, level=0.95):
    """Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
    d = d.dropna(subset=[time, value])
    s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
    s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
    half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
    return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
def grid_shape(k):
    """The app's panel grid: 1–3 panels in a row, 4 as 2 × 2, up to 6 in 3 columns, else 4 columns."""
    cols = max(1, k) if k <= 3 else 2 if k == 4 else 3 if k <= 6 else 4
    return int(np.ceil(k / cols)), cols

PERIOD = "none"
series = [(lv, df[df["product_line"].astype(str) == lv]) for lv in freq_levels(df["product_line"], 12)]
rows, cols = grid_shape(len(series))
fig, axes = plt.subplots(rows, cols, figsize=(3.2 * cols, 2.2 * rows), sharex=True, sharey=True, squeeze=False)  # shared y scale
for i, (ax, (name, d)) in enumerate(zip(axes.flat, series)):
    s = resample(d, "month", "revenue_k", PERIOD)
    ax.plot(s["t"], s["mean"], color=PALETTE[i % len(PALETTE)], linewidth=1.4)
    change = s["mean"].iloc[-1] - s["mean"].iloc[0]  # first → last plotted value
    ax.set_title(f"{name}  ({change:+.3g})", fontsize=9, loc="left")
    ax.tick_params(labelsize=7)
for ax in list(axes.flat)[len(series):]:
    ax.set_visible(False)
fig.supylabel("revenue_k")
fig.autofmt_xdate()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads small-multiples-demo.csv · app theme from the optional codesplash helper

Time series

svg#calendar-heatmap

Calendar heatmap

Which days are busy or quiet across a whole year — weekly rhythms, holidays, gaps?

Demo data · seed 20261101 · 1,096 rows · default settings · 640 × 360

How to read it

  1. Read a row as a weekday and a column as a week.
  2. Look for columns or rows that stand out: holidays and weekly rhythms.
  3. Blank cells mean no data, which is different from zero.
  1. Callout 1: Rows are weekdays.
  2. Callout 2: A block of darker days.
  3. Callout 3: Colour scale: the daily value.

Watch out

  • An extreme day can wash out the rest of a linear colour scale.

Defaults

Daily value
Sum
How rows combine into one number per day.
Also: Mean · Row count
Colour scale
Linear (0 → max)
Linear shows the dense cells; log or square root reveals the sparse ones too.
Also: Quantile (rank)
Years shown (latest)
3
How many of the latest years to show.
Range 1 to 5, step 1

Pinned in the code

  • Rows are aggregated per UTC calendar day (sum, mean or count).
  • Columns are weeks counted from the Monday on or before 1 January; rows are ISO weekdays (Monday first).
  • Linear colour maps 0 → the maximum day; quantile colour maps each day's rank among days with data (robust to outliers).
  • Days inside the data range without rows are drawn as empty cells; days outside it are omitted.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")
# controls: agg=sum, scale=linear, years=3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("calendar-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

_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 daily_values(d, time, value, agg):
    """Daily sum / mean / row count per UTC calendar day."""
    day = d[time].dt.floor("D")
    if value is None or agg == "count":
        return d.groupby(day).size().astype(float)
    return d.groupby(day)[value].agg(agg)

def calendar_grid(daily, year):
    """7 × 54 grid: columns are weeks from the Monday on or before 1 January, rows ISO weekdays."""
    jan1 = pd.Timestamp(year=year, month=1, day=1)
    origin = jan1 - pd.Timedelta(days=jan1.day_of_week)
    grid = np.full((7, 54), np.nan)
    inside = np.zeros((7, 54), bool)
    for day in pd.date_range(max(daily.index.min(), jan1), min(daily.index.max(), pd.Timestamp(year=year, month=12, day=31)), freq="D"):
        w, dow = (day - origin).days // 7, day.day_of_week
        inside[dow, w] = True  # days inside the data range without rows stay empty
        if day in daily.index:
            grid[dow, w] = daily[day]
    return grid, inside

AGG, SCALE, YEARS = "sum", "linear", 3
d = df.dropna(subset=["date", "commits"])
daily = daily_values(d, "date", "commits", AGG)
if SCALE == "quantile":  # each day's rank among days with data (robust to outliers)
    daily = daily.rank(pct=True)
years = sorted(daily.index.year.unique())[-YEARS:]
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
vmax = 1 if SCALE == "quantile" else daily.max()  # linear: 0 → the maximum day
fig, axes = plt.subplots(len(years), 1, figsize=(11, 1.7 * len(years)), squeeze=False)
for ax, year in zip(axes[:, 0], years):
    grid, inside = calendar_grid(daily, year)
    ax.imshow(np.where(inside, 0.0, np.nan), cmap=LinearSegmentedColormap.from_list("e", [GREY, GREY]), aspect="equal", alpha=0.35)
    im = ax.imshow(grid, cmap=cmap, vmin=0, vmax=vmax, aspect="equal")
    ax.set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], fontsize=7)
    jan1 = pd.Timestamp(year=year, month=1, day=1)
    origin = jan1 - pd.Timedelta(days=jan1.day_of_week)
    starts = [pd.Timestamp(year=year, month=m, day=1) for m in range(1, 13)]
    ax.set_xticks([(s - origin).days // 7 for s in starts], [s.strftime("%b") for s in starts], fontsize=7)
    ax.set_title(str(year), fontsize=9, loc="left")
    ax.grid(False)
fig.colorbar(im, ax=axes[:, 0].tolist(), shrink=0.6, label=AGG + " of " + "commits" if AGG != "count" else "rows")
plt.show()

Needs pandas, numpy, matplotlib · reads calendar-heatmap-demo.csv · app theme from the optional codesplash helper

Time series

svg#dow-hour

Weekday × hour heatmap

When in the week does activity happen?

Demo data · seed 20261101 · 4,000 rows · default settings · 640 × 360

How to read it

  1. Read rows as weekdays and columns as hours.
  2. Find the darkest block: when activity peaks.
  3. Compare weekdays with the weekend rows.
  1. Callout 1: Darkest block: the busiest hours.
  2. Callout 2: Weekend rows: a different pattern?
  3. Callout 3: Hours run along the bottom, in UTC.

Watch out

  • Hours are in UTC here. Check that the time zone matches how you read the pattern.

Defaults

Cell value
Row count
What each cell's colour shows, such as a count, a sum or a mean.
Also: Mean of value

Pinned in the code

  • Weekday and hour are taken in UTC; rows are ISO weekdays (Monday first), columns hours 00–23.
  • Counts map 0 → max on a sequential ramp; means map min → max of the cell means. Empty cells (no rows for a mean) are grey.
  • Convert timestamps to local time before charting if local rhythms matter.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Weekday × hour heatmap — Codesplash Chart Lab (recipe "dow-hour")
# controls: agg=count
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("dow-hour-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["started_at"] = pd.to_datetime(df["started_at"])

_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")

AGG = "count"  # "count" rows, or "mean" of the value
d = df.dropna(subset=["started_at"])
dow, hour = d["started_at"].dt.day_of_week, d["started_at"].dt.hour  # UTC; Monday = 0
cells = d.groupby([dow, hour])["session_minutes"].mean() if AGG == "mean" else d.groupby([dow, hour]).size()
grid = cells.unstack().reindex(index=range(7), columns=range(24))
if AGG != "mean":
    grid = grid.fillna(0)  # empty cells count 0; empty means stay blank (grey)
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
cmap.set_bad(GREY)
fig, ax = plt.subplots(figsize=(9, 3.2))
im = ax.imshow(grid.to_numpy(dtype=float), cmap=cmap, aspect="auto", vmin=0 if AGG != "mean" else None)
ax.set_yticks(range(7), ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
ax.set_xticks(range(24), [f"{h:02d}" for h in range(24)], fontsize=7)
ax.set_xlabel("hour (UTC)")
ax.grid(False)
fig.colorbar(im, ax=ax, label="mean " + "session_minutes" if AGG == "mean" else "rows")
plt.show()

Needs pandas, numpy, matplotlib · reads dow-hour-demo.csv · app theme from the optional codesplash helper

Time series

svg#seasonal-subseries

Seasonal subseries (cycle plot)

What is the seasonal pattern, and is each month changing across years?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Each mini line is one month across the years.
  2. Compare the horizontal segments, the monthly means: they show the seasonal shape.
  3. Compare the slopes: a steeper month is changing faster across years.
  1. Callout 1: One month's values, year by year.
  2. Callout 2: The segment: this month's mean. Peaks here show the season.

Watch out

  • With only a few years, a month's mean rests on a few values.

Defaults

Year points
On
Mark each year's value on the mini lines.

Pinned in the code

  • Rows are averaged per UTC calendar month; each month's panel plots those monthly means in year order.
  • The horizontal segment is the mean of the plotted monthly means (R `monthplot`, `feasts::gg_subseries`).
  • Rising mini-lines within a month show trend; differences between segments show seasonality.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")
# controls: points=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("seasonal-subseries-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

X, Y = "month", "passengers_k"
d = df.dropna(subset=[X, Y])
monthly = d.groupby(d[X].dt.to_period("M"))[Y].mean()  # mean per UTC calendar month
sub = pd.DataFrame({"year": monthly.index.year, "month": monthly.index.month, "value": monthly.to_numpy()})
month_mean = sub.groupby("month")["value"].mean()  # the horizontal segment: mean of the monthly means
MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

fig, ax = plt.subplots(figsize=(9, 4))
for m in range(1, 13):
    pts = sub[sub["month"] == m].sort_values("year")
    if pts.empty:
        continue
    xs = m + np.linspace(-0.35, 0.35, len(pts)) if len(pts) > 1 else np.array([m])  # years in order within the month
    ax.plot(xs, pts["value"], color=PALETTE[0], linewidth=1.3, marker="o", markersize=3)
    ax.hlines(month_mean[m], m - 0.38, m + 0.38, color=PALETTE[1], linewidth=2)
ax.set_xticks(range(1, 13), MONTHS)
ax.set_ylabel("passengers_k" + " (monthly mean)")
plt.show()

Needs pandas, numpy, matplotlib · reads seasonal-subseries-demo.csv · app theme from the optional codesplash helper

Time series

svg#lag-plot

Lag plot

Does today's value depend on the value k steps earlier (autocorrelation, randomness)?

Demo data · seed 20261101 · 731 rows · default settings · 640 × 360

How to read it

  1. Each point is one value against the value k steps earlier.
  2. A tight diagonal: today's value is close to the earlier one (strong autocorrelation).
  3. A shapeless cloud: the series looks random at that lag.
  1. Callout 1: A tight diagonal: strong dependence at this lag.
  2. Callout 2: The lag, the correlation and the row count.

Watch out

  • A trend alone produces a tight diagonal. Remove the trend before reading it as memory.

Defaults

Lag k (observations)
1
How many steps back to compare each value with.
Range 1 to 60, step 1
Colour by time
On
Fade the path from early to late so you can follow its direction.

Pinned in the code

  • Rows are sorted by the time column; the lag counts observations, not calendar time (resample irregular series first).
  • Points are (y[t − k], y[t]); the dashed line is y[t] = y[t − k]; r is the Pearson correlation of the plotted pairs (close to, but not identical to, the ACF at lag k, which uses the full-series mean and denominator n).
  • Structure along the diagonal means autocorrelation; a shapeless cloud suggests randomness.
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")
# controls: lag=1, colorTime=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("lag-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

_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")
d = df.dropna(subset=["date", "temp_c"]).sort_values("date", kind="stable")  # lags count observations, not calendar time
v = d["temp_c"].to_numpy(dtype=float)
k = max(1, min(1, max(1, len(v) - 2)))
prev, cur = v[:-k], v[k:]  # pairs (y[t − k], y[t])
r = np.corrcoef(prev, cur)[0, 1]  # Pearson r of the plotted pairs (close to, not equal to, the ACF at lag k)
fig, ax = plt.subplots(figsize=(5.5, 5))
ax.scatter(prev, cur, c=np.arange(len(cur)), cmap=LinearSegmentedColormap.from_list("time", [SEQ[0], SEQ[-1]]), s=14, alpha=0.8, edgecolors="none")  # early → late
lo, hi = min(prev.min(), cur.min()), max(prev.max(), cur.max())
ax.plot([lo, hi], [lo, hi], color=REF, linestyle="--", linewidth=1)  # y[t] = y[t − k]
ax.set_xlabel(f"temp_c[t − {k}]")
ax.set_ylabel("temp_c[t]")
ax.set_title(f"lag {k}: r = {r:.3f}", fontsize=10, loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads lag-plot-demo.csv · app theme from the optional codesplash helper

Time series

svg#acf

ACF & PACF

Is the series autocorrelated, and at which lags (seasonality, AR order)?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360

How to read it

  1. Read each bar as the correlation between the series and itself at that lag.
  2. Bars outside the dashed band are larger than noise would usually give.
  3. Slowly fading ACF suggests a trend; a spike at the seasonal lag suggests a season; PACF cut-offs suggest an AR order.
  1. Callout 1: Lag 1: the correlation with the previous value.
  2. Callout 2: Dashed band: the range for white noise.
  3. Callout 3: PACF: the correlation left after shorter lags are accounted for.

Watch out

  • With many lags, about 1 in 20 bars pokes out by chance.

Defaults

Panels
ACF and PACF
Which panels to show.
Also: ACF only · PACF only
Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 120, step 1

Pinned in the code

  • ACF (R `acf`): r_k = Σ(x_t − x̄)(x_{t+k} − x̄) / Σ(x_t − x̄)², denominator n at every lag (biased, positive-definite estimator); lag 0 = 1 is drawn in grey.
  • PACF (R `pacf`): Durbin–Levinson recursion on the ACF; starts at lag 1.
  • Bounds: ±qnorm(0.975)/√n — approximate 95% limits under white noise (not for MA-model identification beyond lag 1).
  • Default max lag: min(n − 1, ⌊10·log₁₀ n⌋) (R). Missing values are dropped; rows are sorted by the time column; lags count observations.
# ACF & PACF — Codesplash Chart Lab (recipe "acf")
# controls: show=both, lagMax=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm

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("acf-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 acf(v, max_lag):
    """R acf: r_k = Σ(x_t − x̄)(x_{t+k} − x̄) / Σ(x_t − x̄)², denominator n at every lag."""
    d = v - v.mean()
    c0 = (d * d).sum()
    return np.array([(d[: len(d) - k] * d[k:]).sum() / c0 for k in range(max_lag + 1)])

def pacf(v, max_lag):
    """R pacf: Durbin–Levinson recursion on the ACF (lags 1…max_lag)."""
    r = acf(v, max_lag)
    out, phi = [], np.array([])
    for k in range(1, max_lag + 1):
        num = r[k] - (phi * r[k - 1:0:-1]).sum() if k > 1 else r[1]
        den = 1 - (phi * r[1:k]).sum() if k > 1 else 1.0
        pkk = num / den
        phi = np.r_[phi - pkk * phi[::-1], pkk]
        out.append(pkk)
    return np.array(out)

d = df.dropna(subset=["month", "demand"]).sort_values("month", kind="stable")  # lags count observations, not calendar time
v = d["demand"].to_numpy(dtype=float)
L = max(1, min(len(v) - 1, int(np.floor(10 * np.log10(len(v))))))  # R default
bound = norm.ppf(0.975) / np.sqrt(len(v))  # ±qnorm(0.975)/√n white-noise limits
panels = []
panels.append(("ACF", np.arange(L + 1), acf(v, L)))
panels.append(("PACF", np.arange(1, L + 1), pacf(v, L)))
fig, axes = plt.subplots(len(panels), 1, figsize=(8, 2.6 * len(panels)), squeeze=False, sharex=True)
for ax, (name, lags, vals) in zip(axes[:, 0], panels):
    colours = [GREY if k == 0 else PALETTE[0] for k in lags]  # lag 0 = 1 in grey
    ax.vlines(lags, 0, vals, colors=colours, linewidth=2)
    ax.axhline(0, color=REF, linewidth=0.8)
    ax.axhline(bound, color=REF, linestyle="--", linewidth=0.8)
    ax.axhline(-bound, color=REF, linestyle="--", linewidth=0.8)
    ax.set_ylabel(name)
axes[-1, 0].set_xlabel("lag (observations)")
fig.suptitle(f"Autocorrelation of demand (n = {len(v)})", fontsize=10)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads acf-demo.csv · app theme from the optional codesplash helper

Time series

svgbrushable#rolling

Rolling statistics

Is the level or volatility of a series shifting, and which points break from recent behaviour?

Demo data · seed 20261101 · 365 rows · default settings · 640 × 360

How to read it

  1. Read the darker line as the local level.
  2. Read the band as recent variability: a wider band means a more volatile period.
  3. Check the flagged points: they break from recent behaviour.
  1. Callout 1: The rolling mean: the local level.
  2. Callout 2: Band: a wider band means higher recent variability.
  3. Callout 3: A flagged point: unusual given the recent window.

Watch out

  • The rolling mean lags behind turning points, and window length changes what gets flagged.

Defaults

Window (observations)
30
How many recent observations go into each rolling value: larger is smoother but slower to react.
Range 2 to 365, step 1
Band ± k·SD
2
How many rolling standard deviations the band spans around the rolling mean.
Range 1 to 4, step 0.5
Flag points outside the band
On
Mark points that break from their recent behaviour.

Pinned in the code

  • Trailing (right-aligned) windows of w observations including the current one: pandas `rolling(w).mean()/.std()`, zoo `rollapply(align = "right")`. The first w − 1 points have no value.
  • SD uses n − 1 within the window. The window counts observations, not calendar time; resample irregular series first.
  • Flagged points lie more than k rolling SDs from the rolling mean that includes them (a screening aid, not a test).
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")
# controls: window=30, k=2, outliers=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("rolling-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])

_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")
d = df.dropna(subset=["day", "p95_ms"]).sort_values("day", kind="stable")  # lags count observations, not calendar time
v = d["p95_ms"].to_numpy(dtype=float)
w, k = max(2, min(30, len(v))), 2
s = pd.Series(v)
mean, sd = s.rolling(w).mean(), s.rolling(w).std()  # trailing windows of w observations, SD on n − 1
t = d["day"].to_numpy()
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, v, color=GREY, linewidth=1, label="p95_ms")
ax.fill_between(t, mean - k * sd, mean + k * sd, color=PALETTE[0], alpha=0.15, linewidth=0, label=f"± {k}·SD")
ax.plot(t, mean, color=PALETTE[0], linewidth=1.8, label=f"rolling mean ({w})")
out = (np.abs(v - mean) > k * sd).to_numpy()  # outside the band that includes the point
ax.scatter(t[out], v[out], color=PALETTE[3], s=16, zorder=3, label="outside band")
ax.set_ylabel("p95_ms")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads rolling-demo.csv · app theme from the optional codesplash helper

Time series

svgbrushable#zoom-overview

Zoom with overview

How do I explore a long series in detail without losing the big picture?

Demo data · seed 20261101 · 3,653 rows · default settings · 640 × 360

How to read it

  1. Use the strip at the bottom to see the whole series.
  2. Drag the window on the strip to choose the detail above.
  3. Check the date range and point count in the corner.
  1. Callout 1: Detail: the selected window.
  2. Callout 2: The draggable window on the overview.
  3. Callout 3: The selected range and its point count.

Watch out

  • The detail's y axis rescales to the window, so moves look larger than they are.

Defaults

Initial window (days)
180
How much of the series the detail view shows when it opens.
Range 7 to 3,650, step 1
Fill under the line
On
Shade the area under the line.

Pinned in the code

  • Drag on the overview to choose the detail window, drag the window to pan, click outside it to recentre, double-click to show everything.
  • The detail y axis rescales to the visible points; the overview always shows the full range (thinned to ≈ 2 points per pixel).
  • The window starts at the last N days of the series (control). Exports show the chart in its current window.
  • All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
# Zoom with overview — Codesplash Chart Lab (recipe "zoom-overview")
# controls: initialDays=180, area=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("zoom-overview-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

_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")
d = df.dropna(subset=["date", "close"]).sort_values("date")
end = d["date"].max()
start = end - pd.Timedelta(days=180)  # the detail window starts at the last N days
win = d[d["date"] >= start]
fig, (ax, ov) = plt.subplots(2, 1, figsize=(8, 5), gridspec_kw={"height_ratios": [3, 1]})
ax.plot(win["date"], win["close"], color=PALETTE[0], linewidth=1.4)  # detail y rescales to the window
ax.fill_between(win["date"], win["close"].min(), win["close"], color=PALETTE[0], alpha=0.15, linewidth=0)
ov.plot(d["date"], d["close"], color=REF, linewidth=0.8)  # overview: the full range
ov.axvspan(start, end, color=PALETTE[0], alpha=0.2)
ax.set_ylabel("close")
ov.set_yticks([])
plt.show()

Needs pandas, numpy, matplotlib · reads zoom-overview-demo.csv · app theme from the optional codesplash helper

Time series

svg#series-line

Series with break marker

How does the series move over time, and where is an estimated break?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read the level and any drift in the series.
  2. Look for a marked break after an estimated date.
  3. Compare the level before and after that mark.
  1. Callout 1: The level shifts around here.
  2. Callout 2: After the shift, the series varies around a higher level.

Watch out

  • A break found by searching all dates isn't an independent test of that date.

Defaults

Break after observation (0 = none)
0
1-based position in time order of the last observation before the break.
Range 0 to 100,000, step 1
Show points
Off
Mark the individual observations on the line.

Pinned in the code

  • Rows are sorted by the time column (row order when absent); missing values break the line.
  • Time may be dates or numbers (years, hours, positions): the axis follows the column's kind.
  • The break marker sits on the last observation before the break, as Zivot–Andrews reports it.
# Series with break marker — Codesplash Chart Lab (recipe "series-line")
# controls: marker=0, points=false
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("series-line-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
Y = "index"
G = None
MARKER, POINTS = 0, False  # break after this position (0 = none)
d = ordered(df, X, [Y, G])
groups = levels_of(d[G]) if G else [None]
fig, ax = plt.subplots(figsize=(8, 4))
for i, g in enumerate(groups):
    s = d if g is None else d[d[G].astype(str) == str(g)]
    ax.plot(time_of(s, X), s[Y], color=PALETTE[i % len(PALETTE)], linewidth=1.6, label=None if g is None else str(g))
    if POINTS and i == 0:
        ax.scatter(time_of(s, X), s[Y], s=6, color=PALETTE[0])
first = d if G is None else d[d[G].astype(str) == str(groups[0])]
if 0 < MARKER <= len(first):
    ax.axvline(time_of(first, X).iloc[MARKER - 1], color=REF, linestyle="--", linewidth=1.2, label="estimated break")
ax.set_xlabel("month")
ax.set_ylabel(Y)
if G or MARKER:
    ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads series-line-demo.csv · app theme from the optional codesplash helper

Time series

svg#stl-decomposition

Seasonal decomposition

How much of the series is trend, how much a repeating season, and what is left?

Demo data · seed 20261101 · 96 rows · default settings · 640 × 360

How to read it

  1. Read the top panel for the raw series.
  2. Read Trend for the long-run direction and Seasonal for the repeating shape.
  3. Read Remainder last: structure left there means the decomposition missed something.
  1. Callout 1: Observed: the series as measured.
  2. Callout 2: Trend: the long-run path.
  3. Callout 3: Seasonal: the repeating shape.
  4. Callout 4: Remainder: what's left; it should look like noise.

Watch out

  • Compare panel scales: a seasonal panel can look strong while being small relative to the trend.

Defaults

Multiplicative (remainder around 1)
Off
Treat seasonal and remainder parts as ratios around 1, not differences around 0.

Pinned in the code

  • Components are drawn as the engine returned them (statsmodels STL ≡ R stl, or R decompose); nothing is re-estimated here.
  • Each panel has its own y scale: compare shapes across panels, and sizes by reading the axes.
  • The remainder is drawn as spikes from 0 (additive) or 1 (multiplicative); gaps are the classical trend's missing ends.
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")
# controls: multiplicative=false
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("stl-decomposition-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
OBS = "sales"
TR = "trend"
SE = "seasonal"
RE = "remainder"
MULT = False  # remainder around 1 for a multiplicative decomposition
d = ordered(df, X, [OBS, TR, SE, RE])
t = time_of(d, X)
fig, axes = plt.subplots(4, 1, figsize=(8, 7), sharex=True)
for ax, col, name in zip(axes, [OBS, TR, SE, RE], ["Observed", "Trend", "Seasonal", "Remainder"]):
    if name == "Remainder":
        base = 1.0 if MULT else 0.0
        ax.vlines(t, base, d[col], color=PALETTE[0], alpha=0.7, linewidth=1)
        ax.axhline(base, color="grey", linewidth=0.8)
    else:
        ax.plot(t, d[col], color="black" if name == "Observed" else PALETTE[0], linewidth=1.2 if name == "Observed" else 1.6)
    ax.set_ylabel(name, fontsize=9)
axes[-1].set_xlabel("month")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads stl-decomposition-demo.csv · app theme from the optional codesplash helper

Time series

svg#periodogram

Periodogram

Which cycle lengths carry the most variation in the series?

Demo data · seed 20261101 · 240 rows · default settings · 640 × 360

How to read it

  1. Read each peak as a cycle: higher means more variance at that frequency.
  2. Convert: period = 1 / frequency, so a peak at 0.083 is a 12-step cycle.
  3. Look for harmonics: peaks at multiples of the main frequency.
  1. Callout 1: The strongest cycle, labelled with its period.
  2. Callout 2: A harmonic of the main cycle.
  3. Callout 3: Lower peaks in the rest of the spectrum are mostly noise.

Watch out

  • A raw periodogram is noisy: isolated tall spikes occur by chance, so confirm a cycle with a test or more data.

Defaults

Season length to mark (0 = none)
0
Mark the frequency of this season and its multiples.
Range 0 to 10,000, step 1
Log scale
On
Space the axis by ratios, which suits values spanning orders of magnitude.

Pinned in the code

  • I(f_j) = |Σ (x_t − x̄) e^{−2πi f_j t}|² / n at f_j = j/n, j = 1…⌊n/2⌋ — unsmoothed and untapered (R spec.pgram with taper = 0, detrend = FALSE, demean = TRUE, times n).
  • A season of length m shows as a peak at 1/m and its harmonics k/m; a trend piles power near frequency 0.
  • Raw periodogram ordinates are noisy (each has two degrees of freedom); smooth before reading fine detail.
# Periodogram — Codesplash Chart Lab (recipe "periodogram")
# controls: period=0, log=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("periodogram-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = None
Y = "value"
PERIOD, LOG = 0, True  # season length to mark (0 = none)
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
j = np.arange(1, n // 2 + 1)
spec = np.abs(np.fft.fft(v - v.mean())[j]) ** 2 / n  # raw periodogram at Fourier frequencies j/n
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(j / n, spec, color=PALETTE[0], linewidth=1.4)
if PERIOD > 0:
    ax.axvline(1 / PERIOD, color=REF, linestyle="--", label=f"period {PERIOD:g}")
    ax.legend(frameon=False)
if LOG:
    ax.set_yscale("log")
ax.set_xlabel("frequency (cycles per observation)")
ax.set_ylabel("spectral density")
plt.show()

Needs pandas, numpy, matplotlib · reads periodogram-demo.csv · app theme from the optional codesplash helper

Time series

svg#ljung-box-p

Ljung–Box p-values by lag

Up to which lag is the series (or a model's residuals) indistinguishable from white noise?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Read each point as the test of all autocorrelations up to that lag.
  2. Points below the 5% line: some autocorrelation remains.
  3. For a model's residuals, you want points above the line.
  1. Callout 1: Below the line: not white noise up to this lag.
  2. Callout 2: The 5% reference line.

Watch out

  • The points overlap in the lags they test, so they aren't independent results.
  • A high p doesn't prove the residuals are white noise, only that this test didn't detect otherwise.

Defaults

Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 200, step 1
Model degrees of freedom (p + q)
0
For ARMA residuals: the χ² df become lag − fitdf.
Range 0 to 20, step 1

Pinned in the code

  • Q(L) = n(n + 2) Σ_{k=1…L} r_k²/(n − k), referred to χ²(L − fitdf) (R Box.test type = 'Ljung-Box'); r_k uses denominator n.
  • Lags with df < 1 are not tested. Default max lag: max(⌊10 log₁₀ n⌋, fitdf + 5), capped at n − 2.
  • Each point is a separate test of all lags up to L; they are strongly dependent, not independent evidence.
# Ljung–Box p-values by lag — Codesplash Chart Lab (recipe "ljung-box-p")
# controls: lagMax=0, fitdf=0
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("ljung-box-p-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def ljung_box_by_lag(v, L, fitdf=0):
    """Q(k) = n(n+2) Σ_{j≤k} r_j²/(n−j) with r_j on denominator n; p from χ²(k − fitdf)."""
    n = len(v)
    x = v - v.mean()
    den = (x * x).sum()
    r = np.array([(x[j:] * x[:n - j]).sum() / den for j in range(1, L + 1)])
    q = n * (n + 2) * np.cumsum(r * r / (n - np.arange(1, L + 1)))
    df_ = np.arange(1, L + 1) - fitdf
    p = np.where(df_ >= 1, stats.chi2.sf(q, np.maximum(df_, 1)), np.nan)
    return np.arange(1, L + 1), q, p
X = None
Y = "residual"
LAG_MAX, FITDF = 0, 0  # 0 = max(⌊10 log₁₀ n⌋, fitdf + 5)
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(max(1, min(n - 1, int(np.floor(10 * np.log10(n))))), FITDF + 5)
lags, q, p = ljung_box_by_lag(v, max(1, L), FITDF)
fig, ax = plt.subplots(figsize=(7, 4))
ax.axhspan(0, 0.05, color="#ce5342", alpha=0.08, lw=0)
ax.axhline(0.05, color=REF, linestyle="--", linewidth=1)
ax.scatter(lags, p, c=np.where(p < 0.05, "#ce5342", PALETTE[0]), s=18, zorder=3)
ax.set_ylim(0, 1)
ax.set_xlabel("lags included")
ax.set_ylabel("Ljung–Box p-value")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads ljung-box-p-demo.csv · app theme from the optional codesplash helper

Time series

svg#cross-correlation

Cross-correlation

Does one series lead or lag the other, and by how many steps?

Demo data · seed 20261101 · 160 rows · default settings · 640 × 360

How to read it

  1. Find the tallest bar: that lag aligns the two series best.
  2. A negative lag means the first series moves first.
  3. Bars inside the band are compatible with no correlation.
  1. Callout 1: The tallest bar: the best alignment.
  2. Callout 2: Dashed band: the range for white noise.
  3. Callout 3: The lag axis says which series leads.

Watch out

  • Shared trends inflate cross-correlations. Difference the series first, or prewhiten them.
  • Leading does not mean causing.

Defaults

Max lag (0 = R default)
0
How many lags to show; 0 uses R's rule based on the series length.
Range 0 to 200, step 1

Pinned in the code

  • r_k = Σ (a_{t+k} − ā)(b_t − b̄) / (n s_a s_b), as R's ccf(a, b) (denominator n at every lag).
  • Bounds ±1.96/√n assume at least one series is white noise; autocorrelated series produce spurious peaks — prewhiten first.
  • Default max lag ⌊10 log₁₀ n⌋.
# Cross-correlation — Codesplash Chart Lab (recipe "cross-correlation")
# controls: lagMax=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("cross-correlation-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def ccf(a, b, L):
    """R's ccf(a, b): r_k = Σ (a_{t+k} − ā)(b_t − b̄) / √(Σ(a − ā)² Σ(b − b̄)²), k = −L…L."""
    n = len(a)
    a, b = a - a.mean(), b - b.mean()
    den = np.sqrt((a * a).sum() * (b * b).sum())
    ks = np.arange(-L, L + 1)
    r = [sum(a[t + k] * b[t] for t in range(max(0, -k), min(n, n - k))) / den for k in ks]
    return ks, np.array(r)
X = None
A = "leading"
B = "following"
LAG_MAX = 0  # 0 = ⌊10 log₁₀ n⌋
d = ordered(df, X, [A, B])
a, b = d[A].to_numpy(dtype=float), d[B].to_numpy(dtype=float)
n = len(a)
L = min(LAG_MAX, n - 2) if LAG_MAX > 0 else max(1, min(n - 1, int(np.floor(10 * np.log10(n)))))
ks, r = ccf(a, b, L)
bound = 1.959963984540054 / np.sqrt(n)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(-bound, bound, color=GREY, alpha=0.4, lw=0)
ax.vlines(ks, 0, r, colors=np.where(np.abs(r) > bound, PALETTE[0], GREY), linewidth=3)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xlabel(f"lag k: cor({A}[t + k], {B}[t]) — negative k: {A} leads")
ax.set_ylabel("correlation")
plt.show()

Needs pandas, numpy, matplotlib · reads cross-correlation-demo.csv · app theme from the optional codesplash helper

Time series

svg#coint-spread

Cointegration spread

Does the gap between series that should move together keep returning to its mean?

Demo data · seed 20261101 · 160 rows · default settings · 640 × 360

How to read it

  1. Read the line as the gap between the series after removing their long-run link.
  2. A cointegrated spread keeps crossing its mean.
  3. A spread that drifts away for long stretches suggests no stable link.
  1. Callout 1: The mean: the spread should keep coming back here.
  2. Callout 2: Excursions beyond the band.
  3. Callout 3: Crossing the mean often: a good sign.

Watch out

  • Looking mean-reverting by eye isn't the test. Use the cointegration result on the same regression.

Defaults

Band (SD)
2
How many standard deviations the band spans around the mean.
Range 0.5 to 4, step 0.5

Pinned in the code

  • The spread is y₀ − fitted from the Engle–Granger regression of the first series on the others (with its deterministic terms).
  • Band: mean ± k × sample SD (n − 1). A spread that wanders off and stays away suggests no cointegration.
# Cointegration spread — Codesplash Chart Lab (recipe "coint-spread")
# controls: k=2
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("coint-spread-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["quarter"] = pd.to_datetime(df["quarter"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "quarter"
Y = "spread"
K = 2  # band = mean ± K·sd
d = ordered(df, X, [Y])
t, v = time_of(d, X), d[Y].to_numpy(dtype=float)
m, sd = v.mean(), v.std(ddof=1)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(m - K * sd, m + K * sd, color=GREY, alpha=0.35, lw=0)
ax.axhline(m, color=REF, linewidth=1)
ax.plot(t, v, color=PALETTE[0], linewidth=1.4)
out = np.abs(v - m) > K * sd
ax.scatter(np.asarray(t)[out], v[out], color="#ce5342", s=14, zorder=3)
ax.set_xlabel("quarter")
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads coint-spread-demo.csv · app theme from the optional codesplash helper

Time series

svg#dm-matrix

Diebold–Mariano matrix

Which forecasts are significantly more accurate than which?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read the diagonal as each forecast's mean loss.
  2. Read an off-diagonal cell as a comparison of its row with its column.
  3. Blue: the row is more accurate. Red: the column is. Pale: too close to separate.
  1. Callout 1: Diagonal: this forecast's mean loss.
  2. Callout 2: Strong colour: a clear difference between this pair.
  3. Callout 3: Pale cell: compatible with equal accuracy.

Watch out

  • Each cell is one test: with many forecasts, adjust for multiple comparisons.

Defaults

Horizon h
1
How many steps ahead the forecasts were made.
Range 1 to 52, step 1
Loss
Squared error
How forecast errors are scored: squared error punishes large misses more than absolute error.
Also: Absolute error

Pinned in the code

  • d_t = L(e_row) − L(e_col); DM = d̄ / √(Σ_{|k|<h} γ_k / n) × √((n + 1 − 2h + h(h − 1)/n)/n), two-sided p from t(n − 1) (forecast::dm.test).
  • Rows with any missing forecast are dropped so every pair uses the same origins.
  • With many forecasts, adjust for multiple comparisons (or use the Model Confidence Set).
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")
# controls: horizon=1, loss=squared
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("dm-matrix-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 dm_hln(y, a, b, h=1, loss="squared"):
    """Diebold–Mariano with the Harvey–Leybourne–Newbold factor; two-sided p from t(n − 1)."""
    ea, eb = y - a, y - b
    d = ea * ea - eb * eb if loss == "squared" else np.abs(ea) - np.abs(eb)
    n = len(d)
    dc = d - d.mean()
    v = sum((1 if k == 0 else 2) * (dc[k:] * dc[:n - k]).sum() / n for k in range(h)) / n
    if not v > 0:
        return 0.0, 1.0
    stat = d.mean() / np.sqrt(v) * np.sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
    return stat, 2 * stats.t.sf(abs(stat), n - 1)
ACTUAL = "actual"
FORECASTS = ["model A","model B","model C"]
H, LOSS = 1, "squared"
d = df.dropna(subset=[ACTUAL] + FORECASTS)
y = d[ACTUAL].to_numpy(dtype=float)
k = len(FORECASTS)
M = np.full((k, k), np.nan)
for i, fa in enumerate(FORECASTS):
    for j, fb in enumerate(FORECASTS):
        if i != j:
            M[i, j] = dm_hln(y, d[fa].to_numpy(dtype=float), d[fb].to_numpy(dtype=float), H, LOSS)[0]
fig, ax = plt.subplots(figsize=(1.4 * k + 2, 1.2 * k + 1.5))
lim = np.nanmax(np.abs(M)) if np.isfinite(M).any() else 1
im = ax.imshow(M, cmap="RdBu", vmin=-lim, vmax=lim)  # negative: the row forecast is more accurate
for i in range(k):
    for j in range(k):
        if i != j:
            ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center", fontsize=9)
ax.set_xticks(range(k), FORECASTS, rotation=30, ha="right")
ax.set_yticks(range(k), FORECASTS)
fig.colorbar(im, ax=ax, label="DM statistic (row vs column)")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads dm-matrix-demo.csv · app theme from the optional codesplash helper

Time series

svg#mann-kendall-sen

Trend with Sen's slope

Is the series drifting up or down, and by how much per period?

Demo data · seed 20261101 · 96 rows · default settings · 640 × 360

How to read it

  1. Read the bold line as Sen's slope: the median change per period.
  2. Read the dashed lines as its interval.
  3. Read the title for Mann–Kendall's τ and p.
  1. Callout 1: Sen's slope: the rate of change.
  2. Callout 2: Dashed lines: the slope's interval.
  3. Callout 3: The rate per observation.

Watch out

  • Autocorrelation inflates the plain test. Use the corrected variants when the series has memory.

Defaults

Interval level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.5 to 0.999, step 0.01

Pinned in the code

  • Slope = median of (x_j − x_i)/(t_j − t_i) over all pairs; t is the position for dates or row order, the value for a numeric time.
  • Interval: Gilbert (1987) — ranks (N ∓ z√Var(S))/2 of the sorted pairwise slopes (rounded half to even, as trend::sens.slope).
  • Intercept: median of x − slope·t. Mann–Kendall z is continuity-corrected; Var(S) carries the tie correction.
  • Dashed lines share the median point and use the interval's slopes, showing how steep the trend could plausibly be.
# Trend with Sen's slope — Codesplash Chart Lab (recipe "mann-kendall-sen")
# controls: confLevel=0.95
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("mann-kendall-sen-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
def sen_fit(t, v, conf=0.95):
    """Sen's slope (median pairwise slope), Gilbert's interval (R round = half to even) and Mann–Kendall."""
    i, j = np.triu_indices(len(v), 1)
    dt = t[j] - t[i]
    d = np.sort(((v[j] - v[i]) / dt)[dt != 0])
    m = len(d)
    s = float(np.sign(v[j] - v[i]).sum())
    _, ties = np.unique(v, return_counts=True)
    n = len(v)
    var = (n * (n - 1) * (2 * n + 5) - (ties * (ties - 1) * (2 * ties + 5)).sum()) / 18
    c = stats.norm.ppf(1 - (1 - conf) / 2) * np.sqrt(var)
    lo, hi = int(round((m - c) / 2)), int(round((m + c) / 2 + 1))
    slope = float(np.median(d))
    z = 0.0 if s == 0 else (s - np.sign(s)) / np.sqrt(var)
    return dict(slope=slope, low=d[lo - 1] if 1 <= lo <= m else np.nan, high=d[hi - 1] if 1 <= hi <= m else np.nan,
                intercept=float(np.median(v - slope * t)), tau=s / (n * (n - 1) / 2), p=2 * stats.norm.sf(abs(z)))
X = "month"
Y = "index"
FIT = None
CONF = 0.95
d = ordered(df, X, [Y, FIT])
v = d[Y].to_numpy(dtype=float)
numeric_time = X is not None and not pd.api.types.is_datetime64_any_dtype(d[X])
tpos = d[X].to_numpy(dtype=float) if numeric_time else np.arange(1.0, len(v) + 1)  # dates → position in time order
f = sen_fit(tpos, v, CONF)
t = time_of(d, X)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, v, color=PALETTE[0], alpha=0.35, linewidth=1)
ax.scatter(t, v, color=PALETTE[0], s=10)
if FIT:
    ax.plot(t, d[FIT], color="black", linewidth=2, label="trend")
else:
    tm = np.sort(tpos)[(len(tpos) - 1) // 2]
    mid = f["intercept"] + f["slope"] * tm
    for s_ in (f["low"], f["high"]):  # the interval's slopes through the median point
        ax.plot(t, mid + s_ * (tpos - tm), color=REF, linestyle="--", linewidth=1)
    ax.plot(t, f["intercept"] + f["slope"] * tpos, color="black", linewidth=2, label=f"Sen's slope {f['slope']:.4g}")
ax.set_title(f"Mann–Kendall τ = {f['tau']:.2f}, p = {f['p']:.3g}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel(Y)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads mann-kendall-sen-demo.csv · app theme from the optional codesplash helper

Time series

svg#pettitt-u

Pettitt's change-point curve

Where does the series most likely change level, and is the change beyond chance?

Demo data · seed 20261101 · 80 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the rank-sum contrast between before and after each date.
  2. The largest absolute value marks the most probable change.
  3. Crossing the dashed line means the change is beyond chance at that level.
  1. Callout 1: The largest |U|: the most likely change point.
  2. Callout 2: The significance limit.
  3. Callout 3: The date of the change.

Watch out

  • It looks for one change. Several changes or a smooth trend can also give a large peak.

Defaults

α for the reference line
0.05
The significance level for the reference line.
Range 0.001 to 0.2, step 0.005

Pinned in the code

  • U_t = Σ_{i≤t} Σ_{j>t} sgn(x_i − x_j) = 2 Σ_{i≤t} r_i − t(n+1) with mid-ranks, t = 1…n−1.
  • K = max |U_t| at the first maximising t (the last observation before the change), p ≈ 2 exp(−6K² / (n³ + n²)) — Pettitt's approximation, as trend::pettitt.test.
  • The dashed lines solve that approximation for |U| at p = α.
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")
# controls: alpha=0.05
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("pettitt-u-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
Y = "level"
ALPHA = 0.05
d = ordered(df, X, [Y])
v = d[Y].to_numpy(dtype=float)
n = len(v)
u = 2 * np.cumsum(stats.rankdata(v))[: n - 1] - np.arange(1, n) * (n + 1)  # U_t = Σ_{i≤t} Σ_{j>t} sgn(x_i − x_j)
K, loc = np.abs(u).max(), int(np.argmax(np.abs(u)))  # loc: last observation before the change (0-based)
p = min(1.0, 2 * np.exp(-6 * K**2 / (n**3 + n**2)))
crit = np.sqrt(-np.log(ALPHA / 2) * (n**3 + n**2) / 6)  # |U| where Pettitt's approximation gives p = α
t = time_of(d, X).iloc[: n - 1]
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhspan(-crit, crit, color=GREY, alpha=0.3, lw=0)
ax.axhline(crit, color=REF, linestyle="--")
ax.axhline(-crit, color=REF, linestyle="--")
ax.plot(t, u, color=PALETTE[0], linewidth=1.6)
ax.scatter([t.iloc[loc]], [u[loc]], color="#ce5342", zorder=3)
ax.set_title(f"Pettitt K = {K:.0f}, p ≈ {p:.3g}; change after {t.iloc[loc]}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel("U_t")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads pettitt-u-demo.csv · app theme from the optional codesplash helper

Time series

svg#buishand-cusum

Buishand cumulative deviations

Does the running sum of deviations from the mean bend sharply — a shift in level?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the running sum of deviations from the overall mean.
  2. A sharp tent peaks at a level shift.
  3. A smooth arch suggests a gradual trend instead.
  1. Callout 1: The peak: the most likely point of the shift.
  2. Callout 2: It always returns to zero at the end.

Watch out

  • The curve must start and end at zero, so a hump isn't evidence on its own. Use the test's p-value.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • S_k = Σ_{i≤k} (x_i − x̄) / s for k = 1…n with the sample sd s (n − 1), as trend::br.test / bu.test; Buishand (1982) divides by n.
  • R/√n = (max S − min S)/√n over k = 0…n (S_0 = 0); U = Σ_{k<n} S_k² / (n(n+1)). The marker sits at the largest |S_k|.
  • p-values for R and U come from Monte Carlo in the analysis (normal null); the chart shows the statistics only.
# Buishand cumulative deviations — Codesplash Chart Lab (recipe "buishand-cusum")
# 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("buishand-cusum-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "month"
Y = "rainfall index"
d = ordered(df, X, [Y])
v = d[Y].to_numpy(dtype=float)
n = len(v)
s = np.cumsum(v - v.mean()) / v.std(ddof=1)  # S_k / s, sample sd as trend::br.test
rng_stat = (max(0, s.max()) - min(0, s.min())) / np.sqrt(n)
U = (s[: n - 1] ** 2).sum() / (n * (n + 1))
loc = int(np.argmax(np.abs(s[: n - 1])))
t = time_of(d, X)
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhline(0, color="grey", linewidth=0.8)
ax.plot(t, s, color=PALETTE[0], linewidth=1.6)
ax.axvline(t.iloc[loc], color=REF, linestyle=":", linewidth=1)
ax.scatter([t.iloc[loc]], [s[loc]], color="#ce5342", zorder=3)
ax.set_title(f"R/√n = {rng_stat:.3f}, U = {U:.3f}; largest deviation after {t.iloc[loc]}", fontsize=10, loc="left")
ax.set_xlabel("month")
ax.set_ylabel("Σ (x − x̄) / s")
plt.show()

Needs pandas, numpy, matplotlib · reads buishand-cusum-demo.csv · app theme from the optional codesplash helper

Time series

svg#segment-means

Series with segment means

Where does the level of the series change, and what is the level in each segment?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read the horizontal lines as each segment's mean.
  2. Read the dashed lines as the estimated change dates.
  3. Compare levels and whether variability differs across segments.
  1. Callout 1: A dashed line: an estimated change.
  2. Callout 2: This segment's mean.
  3. Callout 3: The next segment's level.

Watch out

  • Segmentation finds changes by design. The penalty setting controls how many, so try more than one.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Segments are runs of the same label in time order; each line spans its first to last observation at the segment mean.
  • Dashed lines sit on the last observation before each change, as the analyses report change points.
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")
# 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("segment-means-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["week"] = pd.to_datetime(df["week"])
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["1", "2", "3"])

_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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "week"
Y = "level"
SEG = "segment"
d = ordered(df, X, [Y, SEG])
t = time_of(d, X)
seg = d[SEG].astype(str) if SEG else pd.Series("1", index=d.index)
run = (seg != seg.shift()).cumsum()  # consecutive runs of the same label
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(t, d[Y], color=PALETTE[0], alpha=0.7, linewidth=1.2)
for r, g in d.groupby(run, sort=True):
    tt = t[g.index]
    ax.hlines(g[Y].mean(), tt.iloc[0], tt.iloc[-1], color=PALETTE[3 % len(PALETTE)], linewidth=2.6)
    if r > 1:
        ax.axvline(t[d.index[d.index.get_loc(g.index[0]) - 1]], color=REF, linestyle="--", linewidth=1)
ax.set_xlabel("week")
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads segment-means-demo.csv · app theme from the optional codesplash helper

Time series

svg#fluctuation-process

Fluctuation process with boundaries

Does the cumulative (or moving) sum of residuals wander outside what a stable regression allows?

Demo data · seed 20261101 · 101 rows · default settings · 640 × 360

How to read it

  1. Read the line as cumulative (or moving) residuals from a regression fitted in time order.
  2. Leaving the boundaries signals a change in the coefficients.
  3. Note where it first crosses: the change happened before that.
  1. Callout 1: Crossing the boundary: unstable coefficients.
  2. Callout 2: The upper 5% boundary.
  3. Callout 3: A stable regression keeps the process near zero.

Watch out

  • The crossing date isn't the break date: use the F sequence or Bai–Perron to date it.

Defaults

Process
OLS-CUSUM
Which fluctuation process to draw: cumulative or moving sums of residuals.
Also: Recursive CUSUM · OLS-MOSUM · Recursive MOSUM
5% critical value (0 = closed form)
0
The analysis sends a simulated value for the MOSUMs; the CUSUMs have closed forms.
Range 0 to 10, step 0.01

Pinned in the code

  • Recursive CUSUM: boundary ±λ(1 + 2t) with λ = 0.948 at 5% (Brown, Durbin & Evans); OLS-CUSUM: ±1.358 (Brownian-bridge supremum).
  • MOSUM boundaries have no closed form: the analysis sends a simulated 5% point (normal errors, predictors held fixed); with none, no boundary is drawn.
  • t runs from 0 to 1 across the process; processes are scaled as strucchange's efp().
# Fluctuation process with boundaries — Codesplash Chart Lab (recipe "fluctuation-process")
# controls: kind=ols-cusum, crit=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("fluctuation-process-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "observations used"
Y = "OLS-CUSUM"
KIND, CRIT = "ols-cusum", 1.358099  # 5% boundary (recursive CUSUM: ±CRIT·(1 + 2t))
d = ordered(df, X, [Y])
x, v = time_of(d, X).to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
t = (x - x[0]) / (x[-1] - x[0])  # 0 … 1 across the process
fig, ax = plt.subplots(figsize=(8, 4))
ax.axhline(0, color="grey", linewidth=0.8)
if CRIT is not None:
    b = CRIT * (1 + 2 * t) if KIND == "rec-cusum" else np.full_like(t, CRIT)
    ax.plot(x, b, color="#ce5342", linestyle="--", linewidth=1.2, label="5% boundary")
    ax.plot(x, -b, color="#ce5342", linestyle="--", linewidth=1.2)
ax.plot(x, v, color=PALETTE[0], linewidth=1.8, label=KIND)
ax.set_xlabel("observations used")
ax.set_ylabel("empirical fluctuation process")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads fluctuation-process-demo.csv · app theme from the optional codesplash helper

Time series

svg#fstat-sequence

F statistics over candidate breaks

At which date would a break in the regression be most pronounced, and is the largest F beyond chance?

Demo data · seed 20261101 · 71 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the F statistic for a break after each candidate date.
  2. The highest point (sup-F) is the most pronounced break.
  3. Compare it with the critical value of the maximum, not the usual F table.
  1. Callout 1: sup-F: the largest F, at the most pronounced break.
  2. Callout 2: Low values: no sign of a break around these dates.

Watch out

  • Searching all dates inflates F, so a usual F table overstates the evidence.

Defaults

5% critical value (0 = none)
0
The critical value of sup-F (the analysis sends a simulated one).
Range 0 to 100, step 0.1

Pinned in the code

  • F_i = (RSS − RSS₁ − RSS₂) / ((RSS₁ + RSS₂)/(n − 2k)) for a break after observation i, i = ⌊πn⌋…⌊(1−π)n⌋, as strucchange::Fstats.
  • The critical line is for the maximum over all candidates — not for any single F — so it sits well above the usual F critical value.
# F statistics over candidate breaks — Codesplash Chart Lab (recipe "fstat-sequence")
# controls: crit=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("fstat-sequence-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "break after"
Y = "F"
CRIT = 0  # 5% critical value of sup-F (0 = none)
d = ordered(df, X, [Y])
t, F = time_of(d, X), d[Y].to_numpy(dtype=float)
i = int(np.argmax(F))
fig, ax = plt.subplots(figsize=(8, 4))
if CRIT > 0:
    ax.axhline(CRIT, color="#ce5342", linestyle="--", label="5% critical value of sup-F")
ax.plot(t, F, color=PALETTE[0], linewidth=1.6)
ax.scatter([t.iloc[i]], [F[i]], color="#ce5342" if CRIT and F[i] > CRIT else PALETTE[3 % len(PALETTE)], zorder=3)
ax.set_title(f"sup-F = {F[i]:.2f} after {t.iloc[i]}", fontsize=10, loc="left")
ax.set_ylim(bottom=0)
ax.set_xlabel("break after")
ax.set_ylabel("F")
plt.show()

Needs pandas, numpy, matplotlib · reads fstat-sequence-demo.csv · app theme from the optional codesplash helper

Time series

svg#recursive-coef

Recursive coefficient estimates

Does a regression coefficient settle down as data accumulate, or drift — a sign the relationship is changing?

Demo data · seed 20261101 · 111 rows · default settings · 640 × 360

How to read it

  1. Read the line as the coefficient re-estimated as more rows arrive.
  2. The band shows how uncertain it is at each size: wide early, narrower later.
  3. A steady drift away from the dashed line suggests the relationship is changing.
  1. Callout 1: Early estimates: unstable and uncertain.
  2. Callout 2: The final estimate on all rows.
  3. Callout 3: Dashed line: the full-sample value.

Watch out

  • Row order matters: this only speaks to time-related change when rows are in time order.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Each point is the OLS estimate from rows 1…r in time order; SE = √(σ̂²_r [(X'X)⁻¹_r]_jj) with σ̂²_r = RSS_r / (r − k).
  • Early estimates are noisy by construction; read the shape after the band narrows.
# Recursive coefficient estimates — Codesplash Chart Lab (recipe "recursive-coef")
# 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("recursive-coef-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 ordered(d, x, cols):
    """Rows with the needed values, sorted by the time column (stable); row order when there is none."""
    d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
    return d.sort_values(x, kind="stable") if x else d

def time_of(d, x):
    return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = "row"
Y = "slope"
LO = "lower"
HI = "upper"
d = ordered(df, X, [Y])
t = time_of(d, X)
fig, ax = plt.subplots(figsize=(8, 4))
if LO and HI:
    ok = d[LO].notna() & d[HI].notna()
    ax.fill_between(t[ok], d.loc[ok, LO], d.loc[ok, HI], color=PALETTE[0], alpha=0.16, lw=0, label="± 1.96 SE")
ax.axhline(d[Y].iloc[-1], color=REF, linestyle="--", linewidth=1, label="full-sample estimate")
ax.plot(t, d[Y], color=PALETTE[0], linewidth=1.8, label="estimate on the first r rows")
ax.set_xlabel("row")
ax.set_ylabel(Y)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads recursive-coef-demo.csv · app theme from the optional codesplash helper

Time series

svg#impulse-response

Impulse responses

When one series gets a one-off shock, how do the others respond over the following periods?

Demo data · seed 20261101 · 117 rows · default settings · 640 × 360

How to read it

  1. Read each panel as one series' response to a one-off shock in another.
  2. Follow the path from period zero: how large, how long, which sign.
  3. Check the band: a path inside a band around zero is compatible with no response.

Watch out

  • Orthogonalized shocks depend on the order of the series, and these are model responses rather than proven causal effects.

Defaults

Rows
All, or the target above 4 series
Which responses and shocks to show.
Also: All series · Target series only

Pinned in the code

  • Orthogonalized responses Θ_i = Φ_i P with P the lower Cholesky factor of the residual covariance: the first listed series can move the others at once, the last only itself. Reordering changes the picture.
  • Bands are percentile intervals from a residual bootstrap with the lag order and rank held fixed.
  • Each row shares a y-axis so shocks can be compared for the same response; a response whose band excludes zero differs from no response at that step.

Use with care

These trace how the fitted system moves, under one assumed ordering. They support a causal reading only if that ordering reflects how the shocks really occur.

# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")
# controls: scope=auto
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("impulse-response-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["responding series"] = pd.Categorical(df["responding series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])

_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")
H = "steps"
V = "response"
R = "responding series"
S = "shock"
LO = "low"
HI = "high"
responses = df[R].astype("category").cat.categories if not hasattr(df[R], "cat") else df[R].cat.categories
shocks = df[S].astype("category").cat.categories if not hasattr(df[S], "cat") else df[S].cat.categories
fig, axes = plt.subplots(len(responses), len(shocks), figsize=(8, 6), sharex=True, sharey="row", squeeze=False)
for i, r in enumerate(responses):
    for j, s in enumerate(shocks):
        ax = axes[i][j]
        d = df[(df[R] == r) & (df[S] == s)].sort_values(H)
        if LO and HI:
            ax.fill_between(d[H], d[LO], d[HI], color=PALETTE[0], alpha=0.2, linewidth=0)
        ax.axhline(0, color=REF, linewidth=0.8)
        ax.plot(d[H], d[V], color=PALETTE[0], linewidth=1.5)
        if i == 0:
            ax.set_title(f"Shock: {s}", fontsize=9)
        if j == 0:
            ax.set_ylabel(str(r), fontsize=9)
fig.supxlabel("steps after the shock", fontsize=9)
plt.show()

Needs pandas, numpy, matplotlib · reads impulse-response-demo.csv · app theme from the optional codesplash helper

Time series

svg#fevd

Forecast error variance decomposition

How much of each series' forecast uncertainty comes from shocks to each series, at each horizon?

Demo data · seed 20261101 · 117 rows · default settings · 640 × 360

How to read it

  1. Read each panel as one series' forecast uncertainty at each horizon.
  2. Read the band widths as the share due to each shock.
  3. A series explained mostly by its own shocks at long horizons takes little from the others.

Watch out

  • The split depends on the order of the series, so try another order before reading much into small shares.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Shares of Σ_{i<h} (Θ_i)² at each horizon h, using the same Cholesky ordering as the impulse responses; the shares at each horizon sum to 100%.
  • A series explained almost entirely by its own shocks at every horizon gets little predictive help from the others.

Use with care

The shares depend on the ordering of the series, like the impulse responses.

# Forecast error variance decomposition — Codesplash Chart Lab (recipe "fevd")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("fevd-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["forecast series"] = pd.Categorical(df["forecast series"].astype("string"), categories=["sales", "ad spend", "price"])
df["shock"] = pd.Categorical(df["shock"].astype("string"), categories=["sales", "ad spend", "price"])

_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")
H = "steps ahead"
V = "share"
R = "forecast series"
S = "shock"
responses = list(pd.unique(df[R]))
shocks = list(pd.unique(df[S]))
fig, axes = plt.subplots(1, len(responses), figsize=(8, 3.6), sharey=True, squeeze=False)
for ax, r in zip(axes[0], responses):
    wide = df[df[R] == r].pivot(index=H, columns=S, values=V).reindex(columns=shocks).sort_index()
    # each shock's layer also has its own texture, as in the app
    ax.stackplot(wide.index, wide.T.to_numpy(), labels=shocks, colors=PALETTE[: len(shocks)], hatch=[SERIES_HATCHES[k % 8] for k in range(len(shocks))], hatchcolor=HATCH_INK, linewidth=0, alpha=0.8)
    ax.set_title(str(r), fontsize=9)
    ax.set_ylim(0, 1)
axes[0][0].set_ylabel("share of forecast error variance")
axes[0][0].legend(fontsize=8, loc="lower right")
fig.supxlabel("steps ahead", fontsize=9)
plt.show()

Needs pandas, numpy, matplotlib · reads fevd-demo.csv · app theme from the optional codesplash helper

Time series

svg#volatility-band

Volatility band

When was the series calm or turbulent, and how wide should the next moves be expected to be?

Demo data · seed 20261101 · 320 rows · default settings · 640 × 360

How to read it

  1. Read the line as the series and the band as its expected range at each moment.
  2. A wide band marks a turbulent period; volatility tends to cluster.
  3. Read the extension at the end as how wide the next moves should be expected to be.

Watch out

  • The band models size, not direction: it says nothing about which way the series will move.

Defaults

Band (σ)
2
How many conditional standard deviations the band spans on each side of the mean.
Range 0.5 to 4, step 0.5

Pinned in the code

  • The band is mean ± k σ_t with σ_t the model's conditional standard deviation; the forecast part continues it with the variance forecasts.
  • With k = 2 about 95% of normally distributed moves fall inside; fat-tailed returns breach it more often.

Use with care

A wider band says larger moves are likely, in either direction; it says nothing about which way the series will go.

# Volatility band — Codesplash Chart Lab (recipe "volatility-band")
# controls: k=2
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("volatility-band-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["fit", "forecast"])

_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")
X = "day"
SIGMA = "volatility"
V = "return"
M = "mean"
KIND = "kind"
K = 2  # band = mean ± K·sigma
d = df.dropna(subset=[SIGMA])
d = d.sort_values(X, kind="stable") if X else d
t = d[X] if X else np.arange(1, len(d) + 1)
mid = d[M] if M else 0.0
ahead = (d[KIND].astype(str) == "forecast").to_numpy() if KIND else np.zeros(len(d), dtype=bool)
fig, ax = plt.subplots(figsize=(8, 4))
ax.fill_between(t, mid - K * d[SIGMA], mid + K * d[SIGMA], where=~ahead, color=PALETTE[0], alpha=0.22, linewidth=0, label=f"Fitted ±{K} σ")
if ahead.any():
    ax.fill_between(t, mid - K * d[SIGMA], mid + K * d[SIGMA], where=ahead, color=PALETTE[1], alpha=0.3, linewidth=0, label=f"Forecast ±{K} σ")
if V:
    ax.plot(t, d[V], color=GREY, linewidth=0.8, label=V)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads volatility-band-demo.csv · app theme from the optional codesplash helper

Time series

svg#origin-strip

Backtest origin strip

Which values does each backtest origin train on and forecast?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each strip as one backtest origin.
  2. The first part is what it trains on, the second what it forecasts and is scored on.
  3. Check that no forecast window comes before its training data.

Watch out

  • Origins that overlap heavily give fewer independent tests than their number suggests.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Positions come from the host's BacktestPlan (cs-ml backtest.rs): offsets from the end of the longest series.
  • A model never sees values after its origin; a sliding training window shows as a strip that starts later.
  • Origins closer together than the horizon forecast overlapping windows, so their errors are not independent.
# Backtest origin strip — Codesplash Chart Lab (recipe "origin-strip")
# 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("origin-strip-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")
ORIGIN = "origin"
START = "train_start"
END = "train_end"
TEST = "test_end"
d = df.dropna(subset=[ORIGIN, END, TEST]).reset_index(drop=True)
start = d[START].fillna(0) if START else pd.Series(0, index=d.index)
y = np.arange(len(d))[::-1]
fig, ax = plt.subplots(figsize=(9, 0.5 * len(d) + 1.4))
ax.barh(y, d[END] - start, left=start, height=0.6, color=PALETTE[0], label="training")
ax.barh(y, d[TEST] - d[END], left=d[END], height=0.6, color=PALETTE[1], label="forecast and scored")
ax.set_yticks(y, d[ORIGIN])
ax.set_xlabel("position in the series")
ax.legend(fontsize=8, ncol=2, loc="upper center", bbox_to_anchor=(0.5, -0.18))
plt.show()

Needs pandas, numpy, matplotlib · reads origin-strip-demo.csv · app theme from the optional codesplash helper

Time series

svg#pit-histogram

PIT histogram

Do the actual values look like draws from the forecast distributions?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read each bar as how often actuals fell in that part of their forecast distribution.
  2. Flat means calibrated.
  3. A U means intervals are too narrow, a hump too wide, and a slope means bias.

Watch out

  • A flat histogram is necessary, not sufficient: a forecast can be calibrated and still be uninformative.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • PIT values come from the quantiles the engine reports as interval bounds, with the point forecast as the median, joined linearly (cs-ml backtest.rs). More interval levels make them closer to the true transform.
  • Actuals outside the widest interval count halfway to 0 or 1, since the engines report nothing further out.
  • Bins are equal width over 0–1; the dashed line is the share a calibrated forecast would put in each.
  • Forecasts from the same origin share errors, so bars vary more than independent draws would.
# PIT histogram — Codesplash Chart Lab (recipe "pit-histogram")
# 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("pit-histogram-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")
SHARE = "share"
share = df[SHARE].fillna(0).to_numpy()
edges = np.linspace(0, 1, len(share) + 1)
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(edges[:-1], share, width=np.diff(edges) * 0.96, align="edge", color=PALETTE[0])
ax.axhline(1 / len(share), color="#6b7280", linestyle="--", label="well calibrated")
ax.set_xlabel("where the actual fell in its forecast distribution")
ax.set_ylabel("share of forecasts")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads pit-histogram-demo.csv · app theme from the optional codesplash helper

Time series

svg#coverage-by-horizon

Coverage by horizon

Do prediction intervals keep their promise further ahead?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Read each line as an interval's actual coverage at each horizon.
  2. Compare with its dashed nominal level.
  3. Lines falling below their target mean the intervals are too narrow that far ahead.

Watch out

  • Long horizons have fewer backtest values, so their coverage is more uncertain.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Coverage is scored on the backtest's forecasts by the host (cs-ml backtest.rs).
  • Each point uses only the forecasts at that horizon, so few origins make it coarse: with 5 origins, each point moves in steps of 20%.
# Coverage by horizon — Codesplash Chart Lab (recipe "coverage-by-horizon")
# 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("coverage-by-horizon-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")
H = "h"
LEVEL = "level"
COV = "coverage"
d = df.dropna(subset=[H, LEVEL, COV])
fig, ax = plt.subplots(figsize=(8, 4.2))
for i, (level, s) in enumerate(sorted(d.groupby(LEVEL), key=lambda kv: -kv[0])):
    s = s.sort_values(H)
    colour = PALETTE[i % len(PALETTE)]
    ax.plot(s[H], s[COV], marker="o", color=colour, label=f"{level:g}%")
    ax.axhline(level / 100, color=colour, alpha=0.45, linestyle="--")
ax.set_ylim(0, 1)
ax.set_xlabel("steps ahead")
ax.set_ylabel("share of actuals inside the interval")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads coverage-by-horizon-demo.csv · app theme from the optional codesplash helper

Time series

svg#forecast-components

Forecast by part

Which parts make up a neural forecast: how much is trend, how much is season, how much is detail?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Start with the top panel: the forecast itself, the sum of the parts below it.
  2. Read the first part as the level and its slow movement; it starts from the last observed value.
  3. Read each later part as a deviation around 0 that the network adds: a season, or finer detail.

Watch out

  • Each panel has its own scale, so a part with a big-looking swing may be small: read sizes from the axis.
  • Only an interpretable N-BEATS splits trend from season by design; the parts of a generic network carry no such meaning.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Each row is one part's contribution at one forecast step; the parts add up to the forecast, which is drawn on top as their sum.
  • The first part carries the last observed value (the level the windows were centred on), so its panel reads in the series' units; later parts are deviations around 0.
  • Each panel has its own vertical scale, so compare shapes across panels and read sizes from the axis.

Use with care

Only the interpretable N-BEATS stacks mean trend and seasonality; a generic network's blocks have no such meaning.

# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")
# 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("forecast-components-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["trend", "seasonality"])

_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")
T = "month"
V = "passengers (thousands)"
P = "part"
names = list(df[P].cat.categories) if hasattr(df[P], "cat") else list(dict.fromkeys(df[P].astype(str)))
wide = df.pivot_table(index=T, columns=P, values=V, aggfunc="last", observed=False).reindex(columns=names).sort_index()
total = wide.sum(axis=1, min_count=len(names))  # the forecast: the parts add up to it
fig, axes = plt.subplots(len(names) + 1, 1, figsize=(8, 1.9 * (len(names) + 1)), sharex=True, squeeze=False)
axes[0][0].plot(total.index, total.to_numpy(), color="black", linewidth=2, marker="o", markersize=3)
axes[0][0].set_title("Forecast (sum of the parts)", fontsize=9, loc="left")
for k, name in enumerate(names):
    ax = axes[k + 1][0]
    ax.plot(wide.index, wide[name].to_numpy(), color=PALETTE[k % len(PALETTE)], linewidth=1.6, marker="o", markersize=3)
    if k > 0:
        ax.axhline(0, color=REF, linewidth=0.8)  # later parts are deviations around 0
    ax.set_title(str(name), fontsize=9, loc="left")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads forecast-components-demo.csv · app theme from the optional codesplash helper

Time series

svg#quantile-fan

Quantile fan

What range of futures does a probabilistic forecaster expect, step by step?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360

How to read it

  1. Read the dark line as the history and the coloured line as the median forecast.
  2. Read the widest band as the central 80% (10% to 90%), the narrower ones as smaller central shares.
  3. Watch how the bands widen with the horizon: that is how fast the model's uncertainty grows.

Watch out

  • A pretrained model's bands are its own beliefs, not a calibrated guarantee: check their coverage in a backtest.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Bands pair each quantile below the median with its mirror above (q and 1 − q), so the 10%–90% band covers the central 80% of the forecast distribution.
  • Bands are drawn as overlapping translucent fills, so the darker centre is where several bands overlap; the median is the point forecast.
  • The bands start at the last observed value so the hand-off from history to forecast is visible.

Use with care

Quantiles describe the model's uncertainty, not a guarantee: check how often actual values fell inside them in a backtest.

# Quantile fan — Codesplash Chart Lab (recipe "quantile-fan")
# 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("quantile-fan-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

_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")
T = "month"
V = "passengers (thousands)"
Q = "quantile"
hist = df[df[Q].isna()].sort_values(T)
fc = df[df[Q].notna()].pivot_table(index=T, columns=Q, values=V, aggfunc="last").sort_index()
levels = sorted(fc.columns)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(hist[T], hist[V], color="black", linewidth=1.4, label="history")
for q in [l for l in levels if l < 0.5]:  # central bands: q to 1 - q
    mirror = min(levels, key=lambda l: abs(l - (1 - q)))
    if abs(mirror - (1 - q)) < 1e-6:
        ax.fill_between(fc.index, fc[q], fc[mirror], color=PALETTE[0], alpha=0.14 + 0.36 / max(1, len(levels) // 2), linewidth=0)
mid = min(levels, key=lambda l: abs(l - 0.5))
ax.plot(fc.index, fc[mid], color=PALETTE[0], linewidth=2, label="median (the forecast)")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads quantile-fan-demo.csv · app theme from the optional codesplash helper

Data quality

Missingness, outliers and types — the profiler's charts.

7

Data quality

svg#column-sparkline

Column sparklines

What does each column look like at a glance?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Scan the tiles for a first look at each column: kind, missing share and distinct count.
  2. Read the mini chart for shape: a histogram for numbers, top values for categories.
  3. Look for surprises: a spike, a red missing bar, one value dominating.
  1. Callout 1: Column name and its inferred kind.
  2. Callout 2: A mini histogram: spikes and long tails stand out.
  3. Callout 3: A red bar: a large missing share.

Watch out

  • An inferred kind is a guess. An id stored as a number still gets a histogram.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Numeric and temporal columns: 18 equal-width [a, b) bins over [min, max] (fewer when there are fewer distinct values).
  • Categorical and boolean columns: the 4 most frequent levels (ties alphabetical) plus “Other”.
  • Kinds: id-like = every non-missing value distinct (n ≥ 20, integers or short strings); text = strings averaging > 30 characters or > 3 words with > 50 % distinct.
  • Missing bar: grey below 5 %, amber 5–40 %, red above 40 %.
# Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")
# 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("column-sparkline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])

KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}

def infer_kind(s, kind):
    """id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
    text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
    if kind in ("boolean", "temporal"):
        return kind
    present = s.dropna()
    distinct = present.astype(str).nunique()
    unique = len(present) >= 20 and distinct == len(present)
    if kind == "numeric":
        ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
        return "id-like" if unique and ints else "numeric"
    strs = present.astype(str)
    avg_len = strs.str.len().mean() if len(strs) else 0
    avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
    if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
        return "text"
    return "id-like" if unique else "categorical"
def tile(s, kind, bins=18, top_k=4):
    """Numeric/temporal: equal-width [a, b) bins over [min, max] (fewer when fewer distinct values);
    categorical/boolean: the top 4 levels (ties A→Z) plus Other."""
    present = s.dropna()
    if kind in ("numeric", "temporal") and len(present):
        v = present.astype("int64").to_numpy() if kind == "temporal" else present.to_numpy(dtype=float)
        k = max(1, min(bins, present.nunique()))
        counts, edges = np.histogram(v, bins=k, range=(v.min(), v.max() if v.max() > v.min() else v.min() + 1))
        return "bins", counts, edges
    if kind in ("categorical", "boolean"):
        vc = present.astype(str).value_counts()
        levels = sorted(vc.index, key=lambda l: (-vc[l], l))
        top = [(l, int(vc[l])) for l in levels[:top_k]]
        other = int(len(present) - sum(n for _, n in top))
        return "levels", top + ([("Other", other)] if other else []), None
    return "none", None, None

KINDS = {"signup_date": "temporal", "age": "numeric", "income": "numeric", "region": "categorical", "plan": "categorical", "churned": "boolean", "satisfaction": "numeric", "comments": "categorical"}  # physical kinds from the app
COLS = list(KINDS)
cols = 4
rows = int(np.ceil(len(COLS) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(3 * cols, 1.9 * rows), squeeze=False)
for ax, name in zip(axes.flat, COLS):
    s = df[name]
    kind = infer_kind(s, KINDS[name])
    share = s.isna().mean()
    miss_colour = "#6e7278" if share < 0.05 else PALETTE[1] if share <= 0.4 else PALETTE[3]  # grey < 5 %, amber ≤ 40 %, red above
    what, a, b = tile(s, kind)
    colour = PALETTE[KIND_COLOUR[kind]]
    if what == "bins":
        ax.bar(b[:-1], a, width=np.diff(b), align="edge", color=colour, edgecolor="white", linewidth=0.4)
    elif what == "levels":
        labels = [l for l, _ in a][::-1]
        ax.barh(labels, [n for _, n in a][::-1], color=[colour if l != "Other" else "#9aa0a6" for l in labels])
        ax.tick_params(axis="y", labelsize=7)
    else:
        ax.text(0.5, 0.5, f"{s.dropna().astype(str).nunique():,} distinct", ha="center", va="center", transform=ax.transAxes, fontsize=9)
    ax.set_title(f"{name} · {kind}", fontsize=9, loc="left")
    ax.text(1, 1.02, f"{share:.0%} missing", transform=ax.transAxes, ha="right", va="bottom", fontsize=8, color=miss_colour)
    ax.set_xticks([])
    if what != "levels":
        ax.set_yticks([])
    ax.grid(False)
for ax in list(axes.flat)[len(COLS):]:
    ax.set_visible(False)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads column-sparkline-demo.csv · app theme from the optional codesplash helper

Data quality

svg#missing-matrix

Missing-value matrix

Where are the gaps, and do columns go missing together?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read rows as data rows and columns as data columns; gaps are blank.
  2. Look for columns with many gaps, listed at the bottom.
  3. Blanks lining up across columns mean those values go missing together.
  1. Callout 1: A column with many gaps.
  2. Callout 2: How complete each row is.
  3. Callout 3: The missing share of each column.

Watch out

  • Row order matters: sort it by a date or group to see whether gaps cluster.

Defaults

Sort rows by completeness
Off
Move the most complete rows together, so patterns stand out.

Pinned in the code

  • Missing = SQL NULL or NaN; present cells are filled, missing cells are blank.
  • Rows keep their table order unless sorted (fewest missing first, stable).
  • n > 400 rows: ⌈n/400⌉ consecutive rows per band; a band's blank opacity is its share of missing cells.
  • Sparkline: share of non-missing columns per row (band mean), from the least to the most complete row.
# Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")
# controls: sort=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("missing-matrix-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])

_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")

COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments"]
miss = df[COLS].isna().to_numpy()  # missing = NULL or not-a-number (pandas isna() covers both)
# rows keep their table order
per = int(np.ceil(len(miss) / 400)) if len(miss) > 400 else 1  # pool rows into ≤ 400 bands
band = np.arange(len(miss)) // per
share = pd.DataFrame(miss).groupby(band).mean().to_numpy()  # missing share per band × column
completeness = 1 - share.mean(axis=1)
fig, (ax, spark) = plt.subplots(1, 2, figsize=(9, 5), gridspec_kw={"width_ratios": [8, 1], "wspace": 0.05}, sharey=True)
ax.imshow(1 - share, aspect="auto", cmap=LinearSegmentedColormap.from_list("present", ["white", PALETTE[0]]), vmin=0, vmax=1, interpolation="nearest")  # present filled, missing blank
ax.set_xticks(range(len(COLS)), [f"{n}\n{s:.0%}" for n, s in zip(COLS, miss.mean(axis=0))], rotation=60, ha="right", fontsize=7)
ax.set_ylabel(f"rows{f' (bands of {per})' if per > 1 else ''}")
ax.grid(False)
spark.plot(completeness, np.arange(len(completeness)), color=REF, linewidth=1)  # share of non-missing columns per row
spark.set_xlim(0, 1)
spark.set_xlabel("complete", fontsize=8)
spark.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads missing-matrix-demo.csv · app theme from the optional codesplash helper

Data quality

svg#nullity-corr

Nullity correlation

Which columns tend to be missing together?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Each cell is the correlation between two columns' missing-value indicators.
  2. A dark cell: these two columns go missing together.
  3. Read clusters as groups of fields collected or lost together.
  1. Callout 1: A dark cell: the two columns go missing together.
  2. Callout 2: Colour legend: from −1 to 1.

Watch out

  • Columns that are never or always missing have no correlation, so a blank cell doesn't mean unrelated.

Defaults

Clustered order
On
Reorder rows and columns so columns missing together sit next to each other.
Show r
On
Print the correlation in each cell.
Lower triangle only
Off
Hide the mirror-image half of the matrix.

Pinned in the code

  • Indicator I = 1 when a cell is missing (NULL/NaN); r is the Pearson correlation of indicators over all rows (= φ coefficient).
  • Columns that are complete or entirely missing are left out (their indicator has no variance).
  • Order: average-linkage clustering on 1 − |r| when clustered; otherwise column order.
  • Diverging ramp centred at 0: +1 = always missing together, −1 = never missing together.
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")
# controls: cluster=true, values=true, lower=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import LinearSegmentedColormap

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("nullity-corr-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])

_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 cluster_order(m):
    """Leaf order of average-linkage clustering on 1 − |r| (the app's ordering; scipy's leaves differ)."""
    d = 1 - np.abs(np.nan_to_num(np.asarray(m, dtype=float)))
    clusters = [[i] for i in range(len(d))]
    while len(clusters) > 1:
        best, best_d = (0, 1), np.inf
        for a in range(len(clusters)):
            for b in range(a + 1, len(clusters)):
                dist = d[np.ix_(clusters[a], clusters[b])].mean()
                if dist < best_d:
                    best, best_d = (a, b), dist
        a, b = best
        merged = clusters[a] + clusters[b]
        clusters = [cl for i, cl in enumerate(clusters) if i not in (a, b)] + [merged]
    return clusters[0]
def apa_r(v):
    return "" if np.isnan(v) else f"{v:.2f}".replace("0.", ".", 1).replace("-", "\u2212")

COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments", "churned"]
ind = df[COLS].isna().astype(float)  # missing = NULL or not-a-number (pandas isna() covers both)
ind = ind.loc[:, (ind.sum() > 0) & (ind.sum() < len(ind))]  # complete / all-missing columns have no variance
r = ind.corr()  # Pearson on 0/1 indicators = φ
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
mask = None
fig, ax = plt.subplots(figsize=(1 + 0.6 * len(r), 0.8 + 0.5 * len(r)))
sns.heatmap(r, ax=ax, mask=mask, vmin=-1, vmax=1, center=0, cmap=LinearSegmentedColormap.from_list("div", DIV), square=True, linewidths=0.5,
            annot=r.map(apa_r), fmt="", annot_kws={"fontsize": 8}, cbar_kws={"label": "nullity r", "shrink": 0.7})
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib, seaborn · reads nullity-corr-demo.csv · app theme from the optional codesplash helper

Data quality

svg#upset

UpSet of missing patterns

Which combinations of columns are missing together, and how often?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read a dot column as a combination of columns missing together.
  2. Read the bar above it as how many rows have that exact combination.
  3. Read the small bars at the left for each column's total.
  1. Callout 1: Height: rows with exactly this pattern.
  2. Callout 2: Joined dots: the columns missing together.
  3. Callout 3: Bars at the left: total missing per column.

Watch out

  • Patterns beyond the top few are collapsed; the note counts how many were left out.

Defaults

Patterns shown
12
How many missing-value patterns to show, most common first.
Range 3 to 30, step 1

Pinned in the code

  • Each incomplete row counts once, under the exact set of columns it is missing (exclusive intersections, as in naniar `gg_miss_upset`).
  • Patterns are ordered by row count (ties: fewer columns first); beyond the top k they are summarized in the footer.
  • Set sizes on the left are the total missing count per column; complete rows are reported, not drawn.
  • Bars for single-column patterns use the first palette colour, multi-column patterns the fifth.
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")
# controls: top=12
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("upset-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])

_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")
COLS = ["age", "region", "income", "last_purchase", "satisfaction", "nps", "comments"]
miss = df[COLS].isna()  # missing = NULL or not-a-number
size = miss.sum()
used = sorted([c for c in COLS if size[c] > 0], key=lambda c: (-size[c], COLS.index(c)))  # sets by missing count
key = miss[used].astype(int).astype(str).agg("".join, axis=1)
complete = int((~miss[used].any(axis=1)).sum())
counts = key[key.str.contains("1")].value_counts()  # each incomplete row once, under its exact set
# order: row count, then fewer columns, then the key descending (the app's tie-break)
patterns = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0].count("1"), tuple(-int(ch) for ch in kv[0])))
top, rest = patterns[:12], patterns[12:]

fig = plt.figure(figsize=(9, 5))
gs = fig.add_gridspec(2, 2, width_ratios=(1, 4), height_ratios=(2, 1.3), hspace=0.05, wspace=0.45)  # room for the set names
bars, matrix, sets = fig.add_subplot(gs[0, 1]), fig.add_subplot(gs[1, 1]), fig.add_subplot(gs[1, 0])
xs = np.arange(len(top))
colours = [PALETTE[0] if k.count("1") == 1 else PALETTE[4] for k, _ in top]  # single-column vs multi-column patterns
bars.bar(xs, [n for _, n in top], color=colours)
bars.bar_label(bars.containers[0], fontsize=7)
bars.set_xticks([])
bars.set_ylabel("rows")
bars.set_title(f"{complete:,} complete rows" + (f" · {len(rest)} more patterns ({sum(n for _, n in rest):,} rows)" if rest else ""), fontsize=9, loc="left")
for j, (k, _) in enumerate(top):
    on = [i for i, ch in enumerate(k) if ch == "1"]
    matrix.scatter([j] * len(used), range(len(used)), s=40, color=GREY, zorder=2)
    matrix.scatter([j] * len(on), on, s=40, color=REF, zorder=3)
    if len(on) > 1:
        matrix.plot([j, j], [min(on), max(on)], color=REF, linewidth=1.5, zorder=2)
matrix.set_yticks(range(len(used)), used, fontsize=8)
matrix.set_xticks([])
matrix.set_xlim(bars.get_xlim())
matrix.invert_yaxis()
matrix.grid(False)
sets.barh(range(len(used)), [size[c] for c in used], color=REF)
sets.set_ylim(matrix.get_ylim())
sets.invert_xaxis()
sets.set_yticks([])
sets.set_xlabel("missing", fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads upset-demo.csv · app theme from the optional codesplash helper

Data quality

svg#missing-by-group

Missing by group

Does missingness depend on a group (a hint that data are not missing completely at random)?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read a cell as the share missing in that column within that group.
  2. Compare a row across groups: differences suggest missingness depends on the group.
  3. Check the group sizes in the headers before reading small groups.
  1. Callout 1: This column's missing share in one group.
  2. Callout 2: A row that differs across groups: not missing completely at random.
  3. Callout 3: The group's size.

Watch out

  • Depending on an observed group doesn't rule out dependence on unobserved values too.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Cell = missing rows / rows in the group; a missing group value forms its own “(missing)” column.
  • Groups: declared level order, else by frequency; at most 10 (plus “(missing)”).
  • Colour scales to the largest share in the table (at least 5 %), so small differences stay visible; the printed % is exact.
  • A pattern that differs by group is evidence against MCAR — confirm with Little's MCAR test (Analyze → Missing-data patterns).
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("missing-by-group-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])

_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")

COLS = ["age", "income", "last_purchase", "satisfaction", "nps", "comments"]
g = df["plan"].astype(object).where(df["plan"].notna(), "(missing)").astype(str)  # a missing group value forms its own column
groups = [l for l in ["Basic", "Plus", "Pro"] if l in set(g)][:10]  # declared level order
groups += ["(missing)"] if (g == "(missing)").any() else []
share = df[COLS].isna().groupby(g).mean().T.reindex(columns=groups)  # missing rows / rows in the group
n = g.value_counts().reindex(groups)
vmax = max(0.05, float(share.max().max()))  # colour scales to the largest share (at least 5 %)
fig, ax = plt.subplots(figsize=(1.5 + 0.9 * len(groups), 0.8 + 0.45 * len(COLS)))
ax.imshow(share.to_numpy(), cmap=LinearSegmentedColormap.from_list("seq", SEQ), vmin=0, vmax=vmax, aspect="auto")
for i in range(share.shape[0]):
    for j in range(share.shape[1]):
        ax.text(j, i, f"{share.iat[i, j]:.0%}", ha="center", va="center", fontsize=7, color="white" if share.iat[i, j] > vmax * 0.6 else "black")
ax.set_xticks(range(len(groups)), [f"{l}\nn = {n[l]:,}" for l in groups], fontsize=8)
ax.set_yticks(range(len(COLS)), COLS, fontsize=8)
ax.set_title("Missing share by plan", fontsize=10, loc="left")
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads missing-by-group-demo.csv · app theme from the optional codesplash helper

Data quality

svgbrushable#outlier-consensus

Outlier consensus

Which values look unusual, and do the common outlier rules agree?

Demo data · seed 20261101 · 405 rows · default settings · 640 × 360

How to read it

  1. Read rows as how many of the three rules flag a value: the top row is flagged by all three.
  2. Read the vertical lines as each rule's cutoff.
  3. Investigate values flagged by all three first.
  1. Callout 1: Flagged by all three rules: look at these first.
  2. Callout 2: Bottom row: not flagged by any rule.
  3. Callout 3: Each dashed line: one rule's cutoff.

Watch out

  • Being flagged doesn't make a value wrong: check the source before removing it.

Defaults

Log x axis (positive values)
Off
Display only; the rules use the raw values.

Pinned in the code

  • Tukey: outside [Q1 − 1.5·IQR, Q3 + 1.5·IQR] with type-7 quartiles.
  • z: |x − x̄| / s > 3 with s on n − 1; not applied when n ≤ 10 (max |z| ≤ (n − 1)/√n).
  • Modified z (Iglewicz & Hoaglin): |x − median| / (1.4826·MAD) > 3.5; when MAD = 0 the scale is 1.253314·mean absolute deviation.
  • Consensus = number of rules flagging a value (0–3). Flags are screening hints, never automatic deletions.
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")
# controls: log=false
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("outlier-consensus-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")
v = df["response_ms"].dropna().to_numpy(dtype=float)
q1, q3 = np.percentile(v, [25, 75])  # type-7 quartiles (numpy's default "linear")
iqr = q3 - q1
tukey = (v < q1 - 1.5 * iqr) | (v > q3 + 1.5 * iqr)
m, s = v.mean(), v.std(ddof=1)
z = (np.abs(v - m) > 3 * s) if len(v) > 10 and s > 0 else np.zeros(len(v), bool)  # not applied when n ≤ 10
med = np.median(v)
mad = np.median(np.abs(v - med))
scale = 1.4826 * mad if mad > 0 else 1.253314 * np.mean(np.abs(v - med))  # Iglewicz & Hoaglin; meanAD when MAD = 0
modz = (np.abs(v - med) > 3.5 * scale) if scale > 0 else np.zeros(len(v), bool)
votes = tukey.astype(int) + z + modz  # consensus 0–3: screening hints, never automatic deletions

rng = np.random.default_rng(11)  # deterministic jitter within each band
y = votes + rng.uniform(-0.3, 0.3, len(v))
fig, ax = plt.subplots(figsize=(8, 3.6))
for k, colour in zip(range(4), [GREY, PALETTE[1], PALETTE[3], DIV[0]]):
    m_k = votes == k
    ax.scatter(v[m_k], y[m_k], s=12, color=colour, alpha=0.8, edgecolors="none")
for lo, hi, colour, ls, label in [(q1 - 1.5 * iqr, q3 + 1.5 * iqr, REF, "-", "Tukey 1.5×IQR"), (m - 3 * s, m + 3 * s, PALETTE[0], "--", "|z| = 3"), (med - 3.5 * scale, med + 3.5 * scale, PALETTE[2], ":", "|mod z| = 3.5")]:
    ax.axvline(lo, color=colour, linestyle=ls, linewidth=1.3, label=label)
    ax.axvline(hi, color=colour, linestyle=ls, linewidth=1.3)
ax.set_yticks(range(4), [f"{k} rule{'s' if k != 1 else ''} · {(votes == k).sum()}" for k in range(4)])
ax.set_xlabel("response_ms")
ax.legend(fontsize=8, loc="upper right")
plt.show()

Needs pandas, numpy, matplotlib · reads outlier-consensus-demo.csv · app theme from the optional codesplash helper

Data quality

svg#type-composition

Column type composition

What kinds of columns does this dataset hold?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Read the segments as how many columns are of each kind.
  2. Read the list below for which columns those are.
  1. Callout 1: Segment size: how many columns of this kind.
  2. Callout 2: The columns of each kind.

Watch out

  • Inferred kinds are guesses. Check the id-like and text groups for columns stored oddly.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Kinds: physical kind (numeric, temporal, categorical, boolean) refined to id-like (all non-missing values distinct, n ≥ 20) and text (long or multi-word strings, > 50 % distinct).
  • The profiler's semantic types (email, URL, currency, …) refine these further in Insights.
# Column type composition — Codesplash Chart Lab (recipe "type-composition")
# 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("type-composition-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["signup_date"] = pd.to_datetime(df["signup_date"])
df["last_purchase"] = pd.to_datetime(df["last_purchase"])
df["last_login"] = pd.to_datetime(df["last_login"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro"])

KIND_ORDER = ["numeric", "temporal", "categorical", "boolean", "text", "id-like"]
KIND_COLOUR = {"numeric": 0, "temporal": 2, "categorical": 1, "boolean": 4, "text": 5, "id-like": 7}

def infer_kind(s, kind):
    """id-like = every non-missing value distinct (n ≥ 20; integers or short strings);
    text = strings averaging > 30 characters, or > 3 words with > 50 % distinct."""
    if kind in ("boolean", "temporal"):
        return kind
    present = s.dropna()
    distinct = present.astype(str).nunique()
    unique = len(present) >= 20 and distinct == len(present)
    if kind == "numeric":
        ints = bool(np.all(np.mod(present.to_numpy(dtype=float), 1) == 0))
        return "id-like" if unique and ints else "numeric"
    strs = present.astype(str)
    avg_len = strs.str.len().mean() if len(strs) else 0
    avg_words = strs.str.strip().str.split().str.len().mean() if len(strs) else 0
    if avg_len > 30 or (avg_words > 3 and distinct > 0.5 * len(strs)):
        return "text"
    return "id-like" if unique else "categorical"

KINDS = {"customer_id": "categorical", "email": "categorical", "signup_date": "temporal", "last_purchase": "temporal", "last_login": "temporal", "age": "numeric", "income": "numeric", "spend_30d": "numeric", "visits_30d": "numeric", "tenure_days": "numeric", "discount_pct": "numeric", "satisfaction": "numeric", "region": "categorical", "plan": "categorical", "device": "categorical", "country": "categorical", "churned": "boolean", "newsletter": "boolean", "mobile_app": "boolean", "comments": "categorical"}  # physical kinds from the app
inferred = {n: infer_kind(df[n], k) for n, k in KINDS.items()}
groups = [(k, [n for n, v in inferred.items() if v == k]) for k in KIND_ORDER]
groups = [(k, names) for k, names in groups if names]
fig, (bar, lst) = plt.subplots(2, 1, figsize=(8, 1.2 + 0.45 * len(groups)), gridspec_kw={"height_ratios": [1, len(groups)]})
left = 0
for k, names in groups:
    bar.barh(0, len(names), left=left, color=PALETTE[KIND_COLOUR[k]], edgecolor="white")
    bar.text(left + len(names) / 2, 0, str(len(names)), ha="center", va="center", color="white", fontsize=9, fontweight="bold")
    left += len(names)
bar.set_xlim(0, len(KINDS))
bar.axis("off")
bar.set_title(f"{len(KINDS)} columns", fontsize=9, loc="left")
for i, (k, names) in enumerate(groups):
    lst.text(0, -i, f"{k} ({len(names)})", color=PALETTE[KIND_COLOUR[k]], fontsize=9, va="center")
    lst.text(0.22, -i, ", ".join(names), fontsize=8, va="center")
lst.set_ylim(-len(groups) + 0.5, 0.5)
lst.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads type-composition-demo.csv · app theme from the optional codesplash helper

Inference & models

Analysis results: estimates with intervals, survival curves, ROC, power and model diagnostics.

47

Inference & models

svg#forest

Forest plot

How large are several estimates, how precise, and which exclude the null?

Demo data · seed 20261101 · 7 rows · default settings · 640 × 360

How to read it

  1. Read each row as an estimate with its interval.
  2. Check the dashed reference line: an interval crossing it is compatible with no effect.
  3. Compare interval widths: wider means less precise.
  1. Callout 1: One estimate: the marker and its interval.
  2. Callout 2: Reference line: no effect.
  3. Callout 3: The estimate and its interval, as numbers.

Watch out

  • Crossing or not crossing the line isn't the same as large or small: read the size too.

Defaults

Reference (null) value
0
The value that means no effect, such as 0 for a difference or 1 for a ratio.
Range -1,000 to 1,000, step 0.1
Log scale (ratios)
Off
Use a log axis, the natural scale for ratios: 2 and ½ sit the same distance from 1.
Equivalence band ± (0 = none; ratio on log scale)
0
Shade the range of effects you would call practically zero.
Range 0 to 100, step 0.05

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Rows keep the engine's order, top to bottom; the right margin repeats estimate [low, high].
  • Ratios (OR, RR, HR, IRR) use a log axis with the reference at 1, so equal ratios look equally far from the null.
  • Engine-supplied controls bandLow/bandHigh draw a smallest-effect-of-interest band (TOST / practical significance).
  • Marker area ∝ weight when given (meta-analysis style); otherwise all markers are equal.
# Forest plot — Codesplash Chart Lab (recipe "forest")
# controls: reference=0, log=false, bandHalf=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("forest-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["subgroup"] = pd.Categorical(df["subgroup"].astype("string"), categories=["All patients", "Age < 65", "Age ≥ 65", "Women", "Men", "Diabetes", "No diabetes"])

_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)))
LABEL = "subgroup"
EST = "mean difference (mmHg)"
LO = "lower"
HI = "upper"
G = None
W = "n"
REFV, LOG, HALF = 0, False, 0  # null value, log axis (ratios), equivalence band ±
d = df.dropna(subset=[LABEL, EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1]  # first row at the top
groups = levels_of(d[G]) if G else [None]
fig, ax = plt.subplots(figsize=(8, 0.42 * len(d) + 1.4))
if HALF > 0:
    band = (REFV / max(HALF, 1 + 1e-9), REFV * max(HALF, 1 + 1e-9)) if LOG else (REFV - HALF, REFV + HALF)
    ax.axvspan(*band, color="#19966e", alpha=0.08, lw=0)
ax.axvline(REFV, color=REF, linestyle="--", linewidth=1)
wmax = d[W].max() if W else 1
for i, row in d.iterrows():
    col = PALETTE[groups.index(str(row[G])) % len(PALETTE)] if G else PALETTE[0]
    ax.plot([row[LO], row[HI]], [y[i], y[i]], color=col, linewidth=1.6)
    size = 24 + 110 * (row[W] / wmax) if W and wmax > 0 else 48  # marker area ∝ weight
    ax.scatter(row[EST], y[i], marker="s", s=size, color=col, zorder=3)
ax.set_yticks(y, d[LABEL].astype(str))
if LOG:
    ax.set_xscale("log")
ax.set_xlabel(EST)
if G:
    for j, g in enumerate(groups):
        ax.scatter([], [], marker="s", color=PALETTE[j % len(PALETTE)], label=g)
    ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads forest-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#emm-plot

Estimated marginal means

What does the model predict for each group (and does the effect of one factor depend on another)?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Read each point as the model's estimated mean at that level, adjusted for other terms.
  2. Read the bars as their intervals.
  3. With a second factor, compare the lines: non-parallel lines suggest an interaction.
  1. Callout 1: An adjusted mean and its interval.
  2. Callout 2: The gap between lines changes across levels.
  3. Callout 3: At this dose the lines meet.

Watch out

  • These are model estimates, not raw means: they depend on the model and which levels it averages over.

Defaults

Connect levels
On
Join the levels of the factor with lines, which makes interactions easier to see.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Means are estimated marginal means from the fitted model (balanced reference grid, emmeans semantics), not raw cell means.
  • Levels of the second factor are dodged horizontally so intervals do not overlap; non-parallel lines suggest an interaction.
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")
# controls: lines=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("emm-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["dose"] = pd.Categorical(df["dose"].astype("string"), categories=["0.5 mg", "1 mg", "2 mg"])
df["supplement"] = pd.Categorical(df["supplement"].astype("string"), categories=["orange juice", "ascorbic acid"])

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 = "dose"
M = "tooth length (EMM)"
LO = "lower"
HI = "upper"
TR = "supplement"
LINES = True  # join the means of each trace level
d = df.dropna(subset=[X, M])
xs = levels_of(d[X])
traces = levels_of(d[TR]) if TR else [None]
off = np.linspace(-0.12, 0.12, len(traces)) if len(traces) > 1 else [0.0]  # dodge
fig, ax = plt.subplots(figsize=(8, 4.5))
for j, t in enumerate(traces):
    g = d if t is None else d[d[TR].astype(str) == str(t)]
    g = g.assign(_p=[xs.index(str(v)) + off[j] for v in g[X]]).sort_values("_p")
    col = PALETTE[j % len(PALETTE)]
    if LO and HI:
        ax.errorbar(g["_p"], g[M], yerr=[g[M] - g[LO], g[HI] - g[M]], fmt="none", ecolor=col, capsize=3, linewidth=1.2)
    ax.plot(g["_p"], g[M], marker="o", color=col, linestyle="-" if LINES else "none", label=str(t) if t is not None else M)
ax.set_xticks(range(len(xs)), xs)
ax.set_xlabel(X)
ax.set_ylabel(M)
if TR:
    ax.legend(title=TR, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads emm-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#km-curve

Kaplan–Meier curve

What fraction survives (is event-free) over time, and do groups differ?

Demo data · seed 20261101 · 114 rows · default settings · 640 × 360

How to read it

  1. Read the height as the estimated share still event-free at that time.
  2. Read across at 50% to find each group's median time.
  3. Check the number at risk below: few at risk makes the right end unreliable.
  1. Callout 1: Dotted guide: the median survival time.
  2. Callout 2: A tick: a censored subject, not an event.
  3. Callout 3: Number at risk at each time.

Watch out

  • Flat tails with few at risk are not evidence that risk stopped.
  • Crossing curves break the proportional hazards idea that a single hazard ratio assumes.

Defaults

Confidence band
On
Shade the uncertainty around the curve.
Number-at-risk table
On
Show how many subjects remain at each time.
Censoring ticks
On
Mark subjects who left the study without the event.
Median guides
On
Draw guides down to each group's median time.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • One row per event or censoring time per group (R `summary(survfit, censored = TRUE)`), plus a start row at t = 0; the curve is right-continuous.
  • Number at risk at a tick t is the at-risk count of the first row at or after t (R `summary(fit, times = t, extend = TRUE)`); 0 beyond the last row.
  • The demo uses Greenwood variance with log-log intervals (R `conf.type = "log-log"`, the survival package's recommended transform).
  • Median guides drop from S = 0.5 at the first time the curve reaches 0.5 (the engine reports the exact median and its CI).
# Kaplan–Meier curve — Codesplash Chart Lab (recipe "km-curve")
# controls: ci=true, riskTable=true, censorTicks=true, median=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("km-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["standard", "new therapy"])

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)))
T = "months"
SV = "survival"
LO = "lower"
HI = "upper"
S = "arm"
NR = "n.risk"
NC = "n.censor"
CI, RISK, TICKS, MEDIAN = True, True, True, True
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
show_risk = RISK and NR is not None
if show_risk:
    fig, (ax, axr) = plt.subplots(2, 1, figsize=(8, 5.6), sharex=True, gridspec_kw={"height_ratios": [4, 1]})
else:
    fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if CI and LO and HI:
        ax.fill_between(d[T], d[LO], d[HI], step="post", color=col, alpha=0.15, lw=0)
    ax.step(d[T], d[SV], where="post", color=col, linewidth=2, label=name or SV)
    if TICKS and NC:
        cz = d[d[NC] > 0]
        ax.scatter(cz[T], cz[SV], marker="|", s=70, color=col, zorder=3)  # censored
    below = d[d[SV] <= 0.5]
    if MEDIAN and len(below):
        tm = below[T].iloc[0]  # median survival: first time S(t) ≤ 0.5
        ax.plot([0, tm, tm], [0.5, 0.5, 0], color=col, linestyle=":", linewidth=1)
ax.set_ylim(0, 1.02)
ax.set_ylabel(SV)
if S:
    ax.legend(fontsize=8)
if show_risk:
    tmax = max(float(d[T].max()) for _, d in series)
    ticks = [t for t in ax.get_xticks() if 0 <= t <= tmax]
    for i, (name, d) in enumerate(series):
        for t in ticks:
            nxt = d[(d[T] >= t) & d[NR].notna()]  # at risk at t: the risk set of the next time ≥ t
            axr.text(t, i, str(int(nxt[NR].iloc[0])) if len(nxt) else "0", ha="center", va="center", fontsize=8, color=PALETTE[i % len(PALETTE)])
    axr.set_yticks(range(len(series)), [n or "at risk" for n, _ in series])
    axr.set_ylim(len(series) - 0.5, -0.5)
    axr.set_xlim(ax.get_xlim())
    axr.tick_params(left=False)
    for side in axr.spines.values():
        side.set_visible(False)
    axr.set_xlabel(T)
else:
    ax.set_xlabel(T)
plt.show()

Needs pandas, numpy, matplotlib · reads km-curve-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#cif-curve

Cumulative incidence (competing risks)

How likely is each type of event by a given time when other events compete?

Demo data · seed 20261101 · 172 rows · default settings · 640 × 360

How to read it

  1. Read the height as the chance this event has happened by that time.
  2. Compare causes: when other events compete, each curve stays below what a one-minus-survival curve would give.
  3. Read the two curves' sum as the chance of any event.
  1. Callout 1: The cumulative chance of this event.
  2. Callout 2: A competing event.
  3. Callout 3: Time from the start.

Watch out

  • 1 − Kaplan–Meier overstates risk when other events compete. Use this chart instead.

Defaults

Confidence band
On
Shade the uncertainty around the curve.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Cumulative incidence, not 1 − Kaplan–Meier: with competing risks 1 − KM overstates the probability of the event of interest.
  • Demo: Aalen–Johansen CIFₖ(t) = Σ S(tⱼ−) dₖⱼ / nⱼ with S the all-cause Kaplan–Meier (R multi-state `survfit`).
# Cumulative incidence (competing risks) — Codesplash Chart Lab (recipe "cif-curve")
# controls: ci=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("cif-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cause"] = pd.Categorical(df["cause"].astype("string"), categories=["relapse", "death without relapse"])

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 = "months"
Y = "cumulative incidence"
LO = None
HI = None
G = "cause"
CI = True
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if CI and LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], step="post", color=col, alpha=0.15, lw=0)
    ax.step(d[X], d[Y], where="post", color=col, linewidth=2, label=name or Y)
ax.set_ylim(0, None)
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads cif-curve-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#roc-curve

ROC curve

How well does a score separate positives from negatives at every cutoff?

Demo data · seed 20261101 · 322 rows · default settings · 640 × 360

How to read it

  1. Read each point as a cutoff's false-positive rate and true-positive rate.
  2. Closer to the top-left corner is better; the diagonal is no better than chance.
  3. Read AUC in the legend, then mark the cutoff you would really use.
  1. Callout 1: The chosen cutoff: its sensitivity and specificity.
  2. Callout 2: Diagonal: a score with no ability to separate.
  3. Callout 3: AUC: the chance a positive outscores a negative.

Watch out

  • AUC ignores prevalence and the costs of errors. With rare positives, check the precision–recall curve too.

Defaults

Chance diagonal
On
Draw the line a score with no skill would follow.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Points are sorted by FPR then TPR and closed at (0, 0) and (1, 1); the legend AUC is the trapezoid area under the drawn points (equal to the engine's empirical AUC when every threshold is supplied). Inference (DeLong CI, tests) comes from the engine.
  • The chosen cutoff (Youden, closest-to-(0,1) or cost-based, as the analysis says) is ringed and labelled with its sensitivity and specificity.
# ROC curve — Codesplash Chart Lab (recipe "roc-curve")
# controls: diagonal=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("roc-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["marker"] = pd.Categorical(df["marker"].astype("string"), categories=["troponin", "CRP"])

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 truthy(s):
    return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
def trapezoid(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    return float(np.sum(np.diff(x) * (y[1:] + y[:-1]) / 2))
FPR = "fpr"
TPR = "tpr"
CURVE = "marker"
OPT = "cutoff"
DIAGONAL = True
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
    d = df if name is None else df[df[CURVE].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[FPR]).sort_values([FPR, TPR], kind="mergesort")))
fig, ax = plt.subplots(figsize=(6, 6))
if DIAGONAL:
    ax.plot([0, 1], [0, 1], color="grey", linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    auc = trapezoid(d[FPR], d[TPR])
    ax.plot(d[FPR], d[TPR], color=col, linewidth=2, label=f"{name + ' ' if name else ''}AUC {auc:.3f}")
    if OPT:
        o = d[truthy(d[OPT])]
        ax.scatter(o[FPR], o[TPR], s=60, facecolors="white", edgecolors=col, linewidths=2, zorder=3)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xlabel(FPR + " (1 − specificity)")
ax.set_ylabel(TPR + " (sensitivity)")
ax.legend(fontsize=8, loc="lower right")
plt.show()

Needs pandas, numpy, matplotlib · reads roc-curve-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#power-curve

Power curve

How does power grow with sample size (or effect size), and where does it reach the target?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read each curve as power at each sample size or effect size.
  2. Find where a curve crosses the target line.
  3. Read the dropped line for the sample size needed.
  1. Callout 1: Where this curve crosses the target.
  2. Callout 2: A smaller effect needs far more data.
  3. Callout 3: The target power.

Watch out

  • Power from the effect you observed (“observed power”) adds nothing beyond the p-value. Choose an effect worth detecting.

Defaults

Target power
0.8
The chance of detecting the effect that you want the study to have, often 0.8 or 0.9.
Range 0.5 to 0.99, step 0.05
Log x axis
Off
Space the x axis by ratios, which suits values spanning orders of magnitude.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • The crossing is interpolated linearly between the supplied points; the engine's solved n (rounded up) is the number to report.
  • Demo: two-sample, two-sided z approximation Φ(d√(n/2) − z₁₋α/₂) + Φ(−d√(n/2) − z₁₋α/₂); the power module uses exact noncentral t.
# Power curve — Codesplash Chart Lab (recipe "power-curve")
# controls: target=0.8, xLog=false
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("power-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["effect"] = pd.Categorical(df["effect"].astype("string"), categories=["d = 0.3", "d = 0.5", "d = 0.8"])

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 = "n per group"
P = "power"
S = "effect"
TARGET, XLOG = 0.8, False
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(TARGET, color="grey", linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    ax.plot(d[X], d[P], color=col, linewidth=2, label=name or P)
    hit = d[d[P] >= TARGET]
    if len(hit):  # first x reaching the target
        x0 = hit[X].iloc[0]
        ax.plot([x0, x0], [0, TARGET], color=col, linestyle=":", linewidth=1)
        ax.scatter([x0], [TARGET], color=col, zorder=3)
        ax.annotate(f"{x0:g}", (x0, 0), textcoords="offset points", xytext=(3, 4), fontsize=8, color=col)
if XLOG:
    ax.set_xscale("log")
ax.set_ylim(0, 1)
ax.set_xlabel(X)
ax.set_ylabel(P)
if S:
    ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads power-curve-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#bland-altman

Bland–Altman plot

Do two measurement methods agree, is there a bias, and does it change with the level measured?

Demo data · seed 20261101 · 85 rows · default settings · 640 × 360

How to read it

  1. Read the middle line as the average difference (bias).
  2. Read the outer lines as the limits within which most differences fall.
  3. Look for a slope or a funnel: the disagreement may change with the level.
  1. Callout 1: Bias: the mean difference.
  2. Callout 2: Upper limit of agreement.
  3. Callout 3: Lower limit of agreement.

Watch out

  • Small limits don't prove agreement: compare them with what is clinically or practically acceptable.

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.
  • Engine-supplied controls: bias, lower, upper (lines), biasLow/biasHigh, lowerLow/lowerHigh, upperLow/upperHigh (confidence bands), slope/intercept (proportional-bias regression).
  • Without engine lines the chart shows bias = mean difference and limits bias ± 1.96·SD (SD with n − 1), as in Bland & Altman (1986).
# Bland–Altman plot — Codesplash Chart Lab (recipe "bland-altman")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("bland-altman-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")
MEAN = "mean of methods (L/min)"
DIFF = "Wright − mini (L/min)"
d = df.dropna(subset=[MEAN, DIFF])
n, bias, sd = len(d), d[DIFF].mean(), d[DIFF].std(ddof=1)
loa = (bias - 1.96 * sd, bias + 1.96 * sd)  # 95% limits of agreement
t = stats.t.ppf(0.975, n - 1)
se_bias, se_loa = sd / np.sqrt(n), sd * np.sqrt(3 / n)  # Bland & Altman (1999) approximate SEs
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhspan(bias - t * se_bias, bias + t * se_bias, color=PALETTE[0], alpha=0.12, lw=0)
for lim in loa:
    ax.axhspan(lim - t * se_loa, lim + t * se_loa, color=GREY, alpha=0.35, lw=0)
    ax.axhline(lim, color=REF, linestyle="--", linewidth=1)
ax.axhline(bias, color=PALETTE[0], linewidth=1.5)
ax.axhline(0, color="grey", linewidth=0.6)
ax.scatter(d[MEAN], d[DIFF], s=22, color=PALETTE[0], alpha=0.8)
for v, txt in [(bias, f"bias {bias:.3g}"), (loa[0], f"−1.96 SD {loa[0]:.3g}"), (loa[1], f"+1.96 SD {loa[1]:.3g}")]:
    ax.annotate(txt, (1, v), xycoords=("axes fraction", "data"), xytext=(-4, 3), textcoords="offset points", ha="right", fontsize=8)
ax.set_xlabel(MEAN)
ax.set_ylabel(DIFF)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads bland-altman-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#residual-panel

Regression diagnostics panel

Do a model's residuals show non-linearity, non-normality, unequal spread or influential points?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Top left: residuals should scatter evenly around zero with no curve.
  2. Top right: points should follow the line if residuals are near normal.
  3. Bottom left: a flat smooth means equal spread. Bottom right: look for high leverage plus a large residual.
  1. Callout 1: A curved smooth: the model may miss non-linearity.
  2. Callout 2: Departures from the line at the ends: heavy tails.
  3. Callout 3: A rising smooth: spread grows with the fit.
  4. Callout 4: Far right, beyond the Cook's lines: an influential point.

Watch out

  • Don't read plots of residuals against the outcome: they always trend, by construction.

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.
  • Layout and reference lines follow R `plot.lm` (which = 1, 2, 3, 5); smooths are LOESS (span 2/3, degree 1) instead of lowess.
  • Cook's contours at D = 0.5 and 1: |r| = √(D·p·(1 − h)/h), with p (number of coefficients) recovered from the engine's Cook's D, leverage and standardized residuals.
  • Without standardized residuals the chart uses residual / SD; without leverage the fourth panel shows residuals in data order (independence).
  • The three largest |standardized residuals| are labelled (row number unless a label column is given).
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("residual-panel-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 ppoints(n):
    a = 3 / 8 if n <= 10 else 0.5
    return (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)
FIT = "fitted"
RES = "residual"
STD = "standardized residual"
LEV = "leverage"
COOK = "Cook's D"
LAB = None
d = df.dropna(subset=[FIT, RES]).reset_index(drop=True)
std = d[STD] if STD else (d[RES] - d[RES].mean()) / d[RES].std(ddof=1)  # standardized residuals
fig, axes = plt.subplots(2, 2, figsize=(9, 7))
a = axes[0, 0]
a.scatter(d[FIT], d[RES], s=14, color=PALETTE[0], alpha=0.75)
a.axhline(0, color=REF, linestyle="--", linewidth=1)
a.set(title="Residuals vs fitted", xlabel=FIT, ylabel=RES)
a = axes[0, 1]
qs = np.sort(std.to_numpy())
th = stats.norm.ppf(ppoints(len(qs)))
a.scatter(th, qs, s=14, color=PALETTE[0], alpha=0.75)
q1, q3 = np.quantile(qs, [0.25, 0.75]), stats.norm.ppf([0.25, 0.75])  # qqline through the quartiles
slope = (q1[1] - q1[0]) / (q3[1] - q3[0])
a.plot(th, q1[0] + slope * (th - q3[0]), color=REF, linestyle="--", linewidth=1)
a.set(title="Normal Q–Q", xlabel="theoretical quantiles", ylabel="standardized residuals")
a = axes[1, 0]
a.scatter(d[FIT], np.sqrt(np.abs(std)), s=14, color=PALETTE[0], alpha=0.75)
a.set(title="Scale–location", xlabel=FIT, ylabel="√|standardized residuals|")
a = axes[1, 1]
if LEV:
    a.scatter(d[LEV], std, s=14, color=PALETTE[0], alpha=0.75)
    a.axhline(0, color=REF, linestyle="--", linewidth=1)
    p = d[LEV].sum()  # trace of the hat matrix = number of coefficients
    h = np.linspace(max(d[LEV].min(), 1e-3), d[LEV].max(), 100)
    for D in (0.5, 1):  # Cook's distance contours
        r = np.sqrt(D * p * (1 - h) / h)
        a.plot(h, r, color="#ce5342", linestyle=":", linewidth=1)
        a.plot(h, -r, color="#ce5342", linestyle=":", linewidth=1)
    a.set_ylim(min(std.min(), -3) * 1.1, max(std.max(), 3) * 1.1)
    if COOK or LAB:
        top = d.assign(_c=d[COOK] if COOK else np.abs(std)).nlargest(3, "_c")
        for i, row in top.iterrows():
            a.annotate(str(row[LAB]) if LAB else str(i + 1), (row[LEV], std[i]), fontsize=7, xytext=(3, 3), textcoords="offset points")
    a.set(title="Residuals vs leverage", xlabel=LEV, ylabel="standardized residuals")
else:
    a.axis("off")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads residual-panel-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#matrix-heatmap

Matrix heatmap

What do the values of a square or rectangular result matrix look like at a glance?

Demo data · seed 20261101 · 36 rows · default settings · 640 × 360

How to read it

  1. Read a cell's colour and its printed value together.
  2. Check the colour bar: diverging around zero or sequential.
  3. Look for blocks and for cells that break the pattern.
  1. Callout 1: A dark cell: a large value.
  2. Callout 2: The other hue: negative values.
  3. Callout 3: Colour bar: the scale.

Watch out

  • Values in a matrix aren't independent, so one cell standing out may be noise.

Defaults

Colour scale
Diverging (centred on 0)
Linear shows the dense cells; log or square root reveals the sparse ones too.
Also: Sequential

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Diverging scales are symmetric around 0 (correlations, standardized residuals); sequential scales run min → max (counts, p-values).
  • Engine-supplied controls min/max fix the colour range (e.g. −1 to 1 for correlations); cell text uses the label column when given (e.g. ".42*").
  • Row and column order follow the stored level order (the engine may cluster them).
# Matrix heatmap — Codesplash Chart Lab (recipe "matrix-heatmap")
# controls: scale=diverging
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("matrix-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["variable"] = pd.Categorical(df["variable"].astype("string"), categories=["age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"])
df["with"] = pd.Categorical(df["with"].astype("string"), categories=["age", "BMI", "systolic BP", "cholesterol", "glucose", "activity"])

_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)))
ROW = "variable"
COL = "with"
V = "r"
LAB = None
DIVERGING = True  # diverging around 0 (correlations) or sequential
d = df.dropna(subset=[ROW, COL])
rows, cols = levels_of(d[ROW]), levels_of(d[COL])
m = d.assign(_r=d[ROW].astype(str), _c=d[COL].astype(str)).pivot_table(index="_r", columns="_c", values=V, aggfunc="first").reindex(index=rows, columns=cols)
vals = m.to_numpy(float)
if DIVERGING:
    lim = np.nanmax(np.abs(vals)) or 1
    cmap, vmin, vmax = LinearSegmentedColormap.from_list("div", [DIV[0], DIV[len(DIV) // 2], DIV[-1]]), -lim, lim
else:
    cmap, vmin, vmax = LinearSegmentedColormap.from_list("seq", [SEQ[0], SEQ[-1]]), np.nanmin(vals), np.nanmax(vals)
labels = None
if LAB:
    labels = d.assign(_r=d[ROW].astype(str), _c=d[COL].astype(str)).pivot_table(index="_r", columns="_c", values=LAB, aggfunc="first").reindex(index=rows, columns=cols)
fig, ax = plt.subplots(figsize=(7, 6))
im = ax.imshow(vals, cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")
for i in range(len(rows)):
    for j in range(len(cols)):
        v = vals[i, j]
        if np.isnan(v):
            continue
        txt = str(labels.iloc[i, j]) if labels is not None else f"{v:.2f}"
        light = abs((v - vmin) / ((vmax - vmin) or 1) - (0.5 if DIVERGING else 0)) > (0.3 if DIVERGING else 0.6)
        ax.text(j, i, txt, ha="center", va="center", fontsize=8, color="white" if light else "black")
ax.set_xticks(range(len(cols)), cols, rotation=45, ha="right")
ax.set_yticks(range(len(rows)), rows)
fig.colorbar(im, ax=ax, label=V)
plt.show()

Needs pandas, numpy, matplotlib · reads matrix-heatmap-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#paired-lines

Paired lines (spaghetti plot)

How did each subject change across conditions or time points?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Follow one thin line: that subject's change across conditions.
  2. Read the bold line as the mean.
  3. Compare: do most subjects move in the mean's direction?
  1. Callout 1: The bold line: the mean at each condition.
  2. Callout 2: A thin line: one subject.
  3. Callout 3: A subject moving against the mean.

Watch out

  • A flat mean can hide large individual changes in opposite directions.

Defaults

Condition means
On
Draw the mean at each condition over the individual lines.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Long data: one row per subject × condition; conditions keep the stored level order. A subject's missing condition breaks its line.
  • Means are of the values shown (complete or not); the test's estimates come from the engine.
# Paired lines (spaghetti plot) — Codesplash Chart Lab (recipe "paired-lines")
# controls: means=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("paired-lines-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["visit"] = pd.Categorical(df["visit"].astype("string"), categories=["baseline", "week 4", "week 12"])

_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)))
SUBJ = "patient"
COND = "visit"
V = "score"
MEANS = True
d = df.dropna(subset=[SUBJ, COND, V])
conds = levels_of(d[COND])
d = d.assign(_x=[conds.index(str(v)) for v in d[COND]]).sort_values("_x")
fig, ax = plt.subplots(figsize=(7, 4.5))
for _, s in d.groupby(SUBJ, observed=True):
    ax.plot(s["_x"], s[V], color=GREY, linewidth=0.9, marker="o", ms=2.5, alpha=0.9)
if MEANS:
    mu = d.groupby("_x")[V].mean()
    ax.plot(mu.index, mu.values, color=PALETTE[0], linewidth=2.6, marker="o", ms=7, label="mean")
    ax.legend(fontsize=8)
ax.set_xticks(range(len(conds)), conds)
ax.set_xlabel(COND)
ax.set_ylabel(V)
plt.show()

Needs pandas, numpy, matplotlib · reads paired-lines-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#calibration

Calibration plot

Do predicted probabilities match observed frequencies?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read each point as a group's mean predicted risk against its observed rate.
  2. Points on the diagonal: predictions match reality.
  3. Above the diagonal: the model under-predicts there; below: over-predicts.
  1. Callout 1: A group of rows: its predicted and observed risk.
  2. Callout 2: Diagonal: perfect calibration.
  3. Callout 3: Below the diagonal: predictions are too high here.

Watch out

  • Groups depend on the binning, and a good AUC says nothing about calibration.

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.
  • Groups are the engine's (e.g. Hosmer–Lemeshow deciles of risk, g = 10); intervals are the engine's binomial CIs.
  • Probability axes are fixed to [0, 1] when every value lies in it; marker area ∝ group size.
# Calibration plot — Codesplash Chart Lab (recipe "calibration")
# 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("calibration-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")
PRED = "mean predicted risk"
OBS = "observed readmission rate"
N = "patients"
LO = "lower (Wilson)"
HI = "upper (Wilson)"
d = df.dropna(subset=[PRED, OBS])
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", linewidth=1, label="perfect calibration")
if LO and HI:
    ax.errorbar(d[PRED], d[OBS], yerr=[d[OBS] - d[LO], d[HI] - d[OBS]], fmt="none", ecolor=PALETTE[0], capsize=2, linewidth=1)
size = 20 + 160 * d[N] / d[N].max() if N else 40  # marker area ∝ n per group
ax.plot(d[PRED], d[OBS], color=PALETTE[0], linewidth=1)
ax.scatter(d[PRED], d[OBS], s=size, color=PALETTE[0], zorder=3)
lim = max(1e-9, float(max(d[PRED].max(), (d[HI] if HI else d[OBS]).max())) * 1.05)
ax.set_xlim(0, min(1, lim))
ax.set_ylim(0, min(1, lim))
ax.set_xlabel(PRED)
ax.set_ylabel(OBS)
ax.legend(fontsize=8, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib · reads calibration-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#rootogram

Hanging rootogram

Does a count model fit the distribution of counts — zeros, overdispersion, the tail?

Demo data · seed 20261101 · 16 rows · default settings · 640 × 360

How to read it

  1. Read the line as the counts the model expects, on a square-root scale.
  2. Each bar hangs from the line: its height is the observed count.
  3. A bar ending above or below zero marks a count the model under- or over-predicts.
  1. Callout 1: A bar past zero: more zeros than the model predicts.
  2. Callout 2: The line: the model's expected counts.
  3. 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

Inference & models

svg#schoenfeld

Schoenfeld residuals

Does a Cox model coefficient change over time (proportional-hazards check)?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read one panel per model term.
  2. A flat smooth means the coefficient is stable over time: proportional hazards looks fine.
  3. A clear slope means the hazard ratio changes over time.
  1. Callout 1: A flat smooth: this coefficient is stable.
  2. Callout 2: A sloping smooth: this effect changes over time.
  3. Callout 3: The dashed zero line.

Watch out

  • With many events, tiny slopes reach significance. Judge the size of the change.

Defaults

Smooth
On
Which smooth to draw through the residuals.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Residuals are the engine's scaled Schoenfeld residuals (R `cox.zph`, transform "km" by default); the test statistics come from the engine.
  • The smooth is LOESS (span 2/3, degree 1) for display; R draws a natural spline with 4 df.
  • At most six terms are drawn.
# Schoenfeld residuals — Codesplash Chart Lab (recipe "schoenfeld")
# controls: smooth=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess

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("schoenfeld-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["age", "treatment"])

_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)))
T = "KM-transformed time"
RES = "scaled Schoenfeld residual"
TERM = "term"
SMOOTH = True  # lowess (f = 2/3, as R's lowess) estimate of β(t)
d = df.dropna(subset=[T, RES])
terms = levels_of(d[TERM]) if TERM else [None]
fig, axes = plt.subplots(1, len(terms), figsize=(4 * len(terms) + 1, 4), squeeze=False)
for ax, term in zip(axes[0], terms):
    s = (d if term is None else d[d[TERM].astype(str) == str(term)]).sort_values(T)
    ax.scatter(s[T], s[RES], s=10, color=GREY, edgecolors=REF, linewidths=0.3)
    ax.axhline(0, color=REF, linestyle="--", linewidth=1)
    if SMOOTH and len(s) > 3:
        rng = float(s[T].max() - s[T].min())
        fit = lowess(s[RES], s[T], frac=2 / 3, it=3, delta=0.01 * rng)
        ax.plot(fit[:, 0], fit[:, 1], color=PALETTE[0], linewidth=2)
    ax.set_title(str(term) if term is not None else RES, fontsize=10)
    ax.set_xlabel(T)
axes[0][0].set_ylabel(RES)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, statsmodels · reads schoenfeld-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#cld-plot

Compact letter display

Which groups differ from which, at a glance?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Read each group's centre and interval.
  2. Read the letters: the post hoc test could not separate groups that share a letter.
  3. Groups with no letters in common are.
  1. Callout 1: The letter above each group.
  2. Callout 2: Sharing a letter: the test could not separate them.
  3. Callout 3: Letters are ordered by group, not by size.

Watch out

  • Sharing a letter doesn't mean equal: it means the test couldn't separate them.

Defaults

Sort by the centre (highest first)
Off
Sort groups from the highest centre to the lowest.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
  • Letters come from the post hoc comparisons (Piepho's insert-and-absorb algorithm): two groups that share any letter are not significantly different at α.
  • Intervals are each group's own t interval for its mean, not the simultaneous intervals of the comparisons — the letters, not overlapping bars, carry the test.
  • Groups keep the engine's level order unless sorted; letters are assigned from the first level, so sorting does not relabel them.
# Compact letter display — Codesplash Chart Lab (recipe "cld-plot")
# controls: sort=false
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("cld-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feed"] = pd.Categorical(df["feed"].astype("string"), categories=["horsebean", "linseed", "soybean", "meatmeal", "casein", "sunflower"])

_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 = "feed"
C = "mean weight (g)"
LO = "lower"
HI = "upper"
LET = "letters"
SORT = False  # order groups by their centre
d = df.dropna(subset=[LABEL, C]).reset_index(drop=True)
if SORT:
    d = d.sort_values(C).reset_index(drop=True)
x = np.arange(len(d))
top = d[HI] if HI else d[C]
fig, ax = plt.subplots(figsize=(8, 4.5))
if LO and HI:
    ax.errorbar(x, d[C], yerr=[d[C] - d[LO], d[HI] - d[C]], fmt="none", ecolor=PALETTE[0], capsize=3, linewidth=1.3)
ax.scatter(x, d[C], s=46, color=PALETTE[0], zorder=3)
pad = 0.04 * float(top.max() - (d[LO] if LO else d[C]).min() or 1)
for i, row in d.iterrows():  # groups sharing a letter do not differ significantly
    ax.text(i, top[i] + pad, str(row[LET]), ha="center", va="bottom", fontsize=10, fontweight="bold", color=REF)
ax.set_xticks(x, d[LABEL].astype(str))
ax.set_ylabel(C)
ax.margins(y=0.12)
plt.show()

Needs pandas, numpy, matplotlib · reads cld-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#critical-difference

Critical-difference diagram

How do the groups rank, and which rank differences are not significant?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Read the top axis as mean rank.
  2. A thick bar joins groups whose ranks the test could not separate.
  3. Groups with no bar joining them differ.
  1. Callout 1: A thick bar: ranks too close to separate.
  2. Callout 2: A group and its mean rank.
  3. Callout 3: The rank axis.

Watch out

  • It compares ranks, not sizes: a group can rank first by a tiny margin.

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.
  • Groups are placed at their mean rank from the joint ranking; the lower half is labelled on the left and the upper half on the right (Demšar 2006).
  • A bar joins every set of groups that share a compact letter — groups joined by a bar are not significantly different at α under the chosen post hoc test.
  • Bars are packed into lanes so they never overlap; their order carries no meaning.
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")
# 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("critical-difference-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["Placebo", "Low dose", "Mid dose", "High dose", "Max dose", "Active control"])

_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 letter_bars(labels, ranks, letters):
    """One bar per letter: the rank span of the groups whose letters include it."""
    bars = []
    for ch in sorted(set("".join(letters))):
        rs = [r for r, l in zip(ranks, letters) if ch in l]
        if len(rs) > 1:
            bars.append((ch, min(rs), max(rs)))
    return bars
LABEL = "arm"
R = "mean rank"
LET = "letters"
d = df.dropna(subset=[LABEL, R]).sort_values(R).reset_index(drop=True)
bars = letter_bars(d[LABEL].astype(str), d[R].tolist(), d[LET].astype(str).tolist())
fig, ax = plt.subplots(figsize=(8, 0.4 * (len(d) + len(bars)) + 1.4))
y = np.arange(len(d))[::-1] + len(bars) + 1
ax.scatter(d[R], y, s=40, color=PALETTE[0], zorder=3)
for yi, (_, row) in zip(y, d.iterrows()):
    ax.plot([row[R], row[R]], [0.5, yi], color=GREY, linewidth=0.8, zorder=1)
    ax.annotate(f"{row[LABEL]}  ({row[LET]})", (row[R], yi), xytext=(6, 0), textcoords="offset points", va="center", fontsize=9)
for k, (ch, lo, hi) in enumerate(bars):  # groups joined by a bar are not separated by the test
    ax.plot([lo, hi], [k + 0.2, k + 0.2], color=REF, linewidth=4, solid_capstyle="round")
ax.set_yticks([])
ax.set_xlabel(R)
for side in ("left", "right", "top"):
    ax.spines[side].set_visible(False)
ax.margins(x=0.15)
plt.show()

Needs pandas, numpy, matplotlib · reads critical-difference-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#null-distribution

Null distribution

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

Demo data · seed 20261101 · 161 rows · default settings · 640 × 360

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

Inference & models

svg#ecdf-two-sample

Two-sample ECDF with KS gap

Where do two distributions differ most?

Demo data · seed 20261101 · 80 rows · default settings · 640 × 360

How to read it

  1. Read each curve as a group's cumulative share.
  2. The marked vertical gap is the largest distance: the Kolmogorov–Smirnov D.
  3. Look at where it falls: location, spread and tails produce different gaps.
  1. Callout 1: The largest gap between the curves: D.
  2. Callout 2: Curves meet at 1.

Watch out

  • D is most sensitive around the centre of the distributions, less so in the tails.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • ECDFs are right-continuous steps (F(x) = share of values ≤ x) — the same definition as R's ecdf and scipy's ks_2samp.
  • D is the largest |F₁(x) − F₂(x)| over the pooled observed values; the marker sits at the first value where it occurs.
  • The test's p-value (exact or asymptotic) comes from the engine; the chart shows where the gap is.
# Two-sample ECDF with KS gap — Codesplash Chart Lab (recipe "ecdf-two-sample")
# 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("ecdf-two-sample-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["courier"] = pd.Categorical(df["courier"].astype("string"), categories=["Northside", "Express"])

_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)))
V = "minutes"
G = "courier"
d = df.dropna(subset=[V, G])
g1, g2 = levels_of(d[G])[:2]
a, b = np.sort(d.loc[d[G].astype(str) == str(g1), V].to_numpy(float)), np.sort(d.loc[d[G].astype(str) == str(g2), V].to_numpy(float))
grid = np.unique(np.concatenate([a, b]))
fa, fb = np.searchsorted(a, grid, side="right") / len(a), np.searchsorted(b, grid, side="right") / len(b)  # right-continuous ECDFs
k = int(np.argmax(np.abs(fa - fb)))  # Kolmogorov–Smirnov D: the largest vertical gap
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.step(grid, fa, where="post", color=PALETTE[0], label=f"{g1} (n = {len(a)})")
ax.step(grid, fb, where="post", color=PALETTE[1], label=f"{g2} (n = {len(b)})")
ax.vlines(grid[k], fa[k], fb[k], colors=REF, linestyles="--", linewidth=2)
ax.annotate(f"D = {abs(fa[k] - fb[k]):.3f}", (grid[k], (fa[k] + fb[k]) / 2), xytext=(6, 0), textcoords="offset points", fontsize=9)
ax.set_xlabel(V)
ax.set_ylabel("cumulative share")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads ecdf-two-sample-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#cullen-frey

Cullen–Frey graph

Which distribution families are compatible with the data's skewness and kurtosis?

Demo data · seed 20261101 · 121 rows · default settings · 640 × 360

How to read it

  1. Find the solid dot: your data's squared skewness and kurtosis.
  2. Read the shape of the bootstrap cloud for how uncertain that position is.
  3. See which family's point, line or region the cloud falls on.
  1. Callout 1: Your data.
  2. Callout 2: Bootstrap cloud: how much the position could vary.
  3. Callout 3: Named points: where exact families sit.

Watch out

  • Moments are noisy in small samples, and many families can fit. Check with a fit overlay.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Moments are the engine's unbiased sample skewness and kurtosis (kurtosis on the raw scale: normal = 3), as in fitdistrplus::descdist.
  • Theory is exact: normal (0, 3), uniform (0, 1.8), exponential (4, 9), logistic (0, 4.2); gamma on β₂ = 3 + 1.5 β₁; lognormal traced by σ; beta between β₂ = β₁ + 1 and the gamma line.
  • Kurtosis increases downward (the classical orientation). Bootstrap points show how uncertain the observed moments are.
# Cullen–Frey graph — Codesplash Chart Lab (recipe "cullen-frey")
# 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("cullen-frey-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["observed", "bootstrap"])

_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")
S = "skewness²"
K = "kurtosis"
KIND = "kind"
d = df.dropna(subset=[S, K]).rename(columns={S: "s", K: "k"})
boot = d[KIND].astype(str).str.contains("boot", case=False) if KIND else pd.Series(False, index=d.index)
obs, bs = d[~boot], d[boot]
x_max = max(4.0, np.ceil(obs["s"].max() * 1.25)) if len(obs) else 4.0
y_max = max(10.0, np.ceil(max(obs["k"].max() if len(obs) else 0, 3 + 1.5 * min(x_max, obs["s"].max() if len(obs) else 0)) * 1.15))
sig = np.arange(0.02, 3, 0.01)
w = np.exp(sig ** 2)
ln_s, ln_k = (w + 2) ** 2 * (w - 1), w ** 4 + 2 * w ** 3 + 3 * w ** 2 - 3  # lognormal (β1, β2)
keep = ln_s <= x_max
theory = {"normal": (0, 3), "uniform": (0, 1.8), "exponential": (4, 9), "logistic": (0, 4.2)}
fig, ax = plt.subplots(figsize=(8, 5))
ax.fill([0, x_max, x_max, 0], [1, x_max + 1, 3 + 1.5 * x_max, 3], color="#19966e", alpha=0.12, lw=0, label="beta")
ax.plot([0, x_max], [3, 3 + 1.5 * x_max], color=PALETTE[0], label="gamma")
ax.plot(ln_s[keep], ln_k[keep], color=PALETTE[1], linestyle="--", label="lognormal")
for name, (sx, kx) in theory.items():
    ax.scatter(sx, kx, marker="^", s=60, facecolors="none", edgecolors=REF)
    ax.annotate(name, (sx, kx), xytext=(-6 if sx > 0.8 * x_max else 6, 0), textcoords="offset points", ha="right" if sx > 0.8 * x_max else "left", va="center", fontsize=8)
ax.scatter(bs["s"], bs["k"], s=10, facecolors="none", edgecolors=GREY, label="bootstrap")
ax.scatter(obs["s"], obs["k"], s=50, color=plt.rcParams["text.color"], zorder=3, label="observed")
ax.set_xlim(0, x_max)
ax.set_ylim(y_max, 1)  # kurtosis increases downward (Cullen & Frey)
ax.set_xlabel("square of skewness")
ax.set_ylabel("kurtosis (normal = 3)")
ax.legend(fontsize=8, loc="lower left")
plt.show()

Needs pandas, numpy, matplotlib · reads cullen-frey-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#fit-overlay-grid

Fitted densities by family

Which candidate distribution follows the data's histogram most closely?

Demo data · seed 20261101 · 470 rows · default settings · 640 × 360

How to read it

  1. Each panel shows the same histogram with one family's best fit.
  2. Compare how each curve follows the bars, especially in the tails.
  3. Use the fit table's AIC to rank them, then decide with the context.
  1. Callout 1: A curve that follows the bars closely.
  2. Callout 2: A curve that misses the data's shape.

Watch out

  • The best of several fits may still be poor, so test it or use a Q–Q plot.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Rows whose family is “data” carry the sample (histogram, Freedman–Diaconis bins with type-7 quartiles, density scale); other rows carry each family's fitted density on a grid from the engine.
  • Every panel shares the x and y scales so curves are comparable; at most six families are shown, in the engine's AIC order.
# Fitted densities by family — Codesplash Chart Lab (recipe "fit-overlay-grid")
# 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("fit-overlay-grid-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["family"] = pd.Categorical(df["family"].astype("string"), categories=["data", "lognormal", "gamma", "normal", "exponential"])

_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 = "hours"
D = "density"
F = "family"
is_data = df[F].astype(str).str.lower().isin(["data", "sample", "empirical", "observed"])
sample = df.loc[is_data, X].dropna().to_numpy(float)
curves = df.loc[~is_data].dropna(subset=[X, D])
fams = [f for f in levels_of(curves[F])][:6]
iqr = np.subtract(*np.percentile(sample, [75, 25]))  # Freedman–Diaconis bins (type-7 quartiles)
bins = max(1, min(60, int(np.ceil(np.ptp(sample) / (2 * iqr * len(sample) ** (-1 / 3)))))) if iqr > 0 else "sturges"
cols = 1 if len(fams) <= 1 else 2 if len(fams) <= 4 else 3
rows = int(np.ceil(len(fams) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 2.8 * rows), sharex=True, sharey=True, squeeze=False)
for ax, (i, fam) in zip(axes.flat, enumerate(fams)):
    ax.hist(sample, bins=bins, density=True, color=GREY, alpha=0.7)
    cv = curves[curves[F].astype(str) == str(fam)].sort_values(X)
    ax.plot(cv[X], cv[D], color=PALETTE[i % len(PALETTE)], linewidth=1.8)
    ax.set_title(str(fam), fontsize=9, loc="left")
for ax in list(axes.flat)[len(fams):]:
    ax.set_visible(False)
plt.show()

Needs pandas, numpy, matplotlib · reads fit-overlay-grid-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#estimation-plot

Estimation plot (Gardner–Altman)

How big is the difference between two groups, and how precisely is it estimated?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read the left of the chart: every observation by group, with the group means.
  2. Read the floating axis at the right: the difference between groups.
  3. Read its interval: how large the difference could plausibly be.
  1. Callout 1: The observations and mean of the first group.
  2. Callout 2: The mean difference with its interval.
  3. Callout 3: The floating axis, anchored at the first group's mean.

Watch out

  • If the interval crosses zero, the data are compatible with no difference, but also with others in the interval.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Points are jittered deterministically by row; group lines are the means; the right axis is the left axis shifted so 0 sits at the first group's mean.
  • The difference and its interval come from the engine (Welch t, bootstrap or another estimator); without them the plain mean difference is shown with no interval.
  • Estimation first: read the size and the interval, not only whether it excludes 0.
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")
# 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("estimation-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["supplement"] = pd.Categorical(df["supplement"].astype("string"), categories=["VC", "OJ"])

_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 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
V = "length"
G = "supplement"
E = "difference"
EL = "diff low"
EH = "diff high"
d = df.dropna(subset=[V, G])
g1, g2 = levels_of(d[G])[:2]
a, b = d.loc[d[G].astype(str) == str(g1), V], d.loc[d[G].astype(str) == str(g2), V]
m1, m2 = a.mean(), b.mean()
eff = first(E) if first(E) is not None else m2 - m1
lo, hi = first(EL), first(EH)
rng = np.random.default_rng(1)
fig, (ax, axd) = plt.subplots(1, 2, figsize=(8, 4.5), sharey=True, gridspec_kw={"width_ratios": [2, 1]})
for i, (s, m) in enumerate([(a, m1), (b, m2)]):
    ax.scatter(i + rng.uniform(-0.15, 0.15, len(s)), s, s=14, alpha=0.6, color=PALETTE[i])
    ax.hlines(m, i - 0.3, i + 0.3, color=plt.rcParams["text.color"], linewidth=2)
ax.set_xticks([0, 1], [str(g1), str(g2)])
ax.set_ylabel(V)
# Floating difference axis: 0 sits at the first group's mean (Gardner & Altman 1986).
axd.axhline(m1, color=REF, linestyle=":", linewidth=1)
axd.errorbar(0, m1 + eff, yerr=[[eff - lo], [hi - eff]] if lo is not None and hi is not None else None, fmt="o", color=PALETTE[1], capsize=4, markersize=8)
axd.set_xticks([0], [f"{g2} − {g1}"])
axd.set_xlim(-0.6, 0.6)
sec = axd.secondary_yaxis("right", functions=(lambda v: v - m1, lambda v: v + m1))
sec.set_ylabel("difference")
plt.show()

Needs pandas, numpy, matplotlib · reads estimation-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#shift-function

Shift function

At which parts of the distribution do two groups differ?

Demo data · seed 20261101 · 9 rows · default settings · 640 × 360

How to read it

  1. Read each point as the difference between groups at one quantile.
  2. A flat line: the groups differ by a constant shift.
  3. A sloped line: the difference grows or shrinks across the distribution.
  1. Callout 1: The lower quantiles barely differ.
  2. Callout 2: The upper quantiles differ more.
  3. Callout 3: Dashed line: no difference.

Watch out

  • Quantile estimates in small samples are noisy, especially at the extremes.

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 inferential.
  • Quantiles are Harrell–Davis estimates and intervals are bootstrap intervals adjusted for the number of quantiles (Wilcox's shift function).
# Shift function — Codesplash Chart Lab (recipe "shift-function")
# 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("shift-function-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
LABEL = "quantile"
EST = "difference (ms)"
LO = "low"
HI = "high"
NOTE = None
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
zone = None
if zone is not None:
    ax.axhspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.axhline(0, color=REF, linestyle="--", linewidth=1)
ax.plot(pos, d[EST], color=GREY, linewidth=1)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(pos[i], row[EST], yerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (pos[i], hi if np.isfinite(hi) else row[EST]), textcoords="offset points", xytext=(0, 6), ha="center", fontsize=8, color=REF)
ax.set_xticks(pos, d[LABEL].astype(str))
ax.set_ylabel("quantile difference")
if LOG:
    ax.set_yscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads shift-function-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#variance-plot

Spread by group

Do the groups differ in spread?

Demo data · seed 20261101 · 3 rows · default settings · 640 × 360

How to read it

  1. Read each point as a group's standard deviation or other scale.
  2. Read the bars as their intervals.
  3. Compare them: do any intervals sit well apart?
  1. Callout 1: A group's spread with its interval.
  2. Callout 2: A group with less spread.

Watch out

  • Intervals for spread are wide in small samples, and depend heavily on normality.

Defaults

Log scale
Off
Ratios of SDs read as distances on a log axis.

Pinned in the code

  • Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
  • Intervals are the engine's χ²-based (or Bonett) intervals for each group's SD; the test across groups (Levene, Brown–Forsythe, Fligner, …) is on the result card.
# Spread by group — Codesplash Chart Lab (recipe "variance-plot")
# controls: log=false
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("variance-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["ctrl", "trt1", "trt2"])

_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
LABEL = "group"
EST = "SD"
LO = "low"
HI = "high"
NOTE = None
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
zone = None
if zone is not None:
    ax.axhspan(*zone, color="#19966e", alpha=0.1, lw=0)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(pos[i], row[EST], yerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (pos[i], hi if np.isfinite(hi) else row[EST]), textcoords="offset points", xytext=(0, 6), ha="center", fontsize=8, color=REF)
ax.set_xticks(pos, d[LABEL].astype(str))
ax.set_ylabel("standard deviation")
if LOG:
    ax.set_yscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads variance-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#trend-plot

Ordered trend

Do the groups move in the expected order (a trend or an umbrella)?

Demo data · seed 20261101 · 5 rows · default settings · 640 × 360

How to read it

  1. Read the groups in their declared order.
  2. Read the line through them: the fitted order.
  3. Compare the trend with the intervals: is the rise larger than each group's uncertainty?
  1. Callout 1: The first group in order.
  2. Callout 2: The group means follow this line.
  3. Callout 3: The last group in order.

Watch out

  • Declare the order before looking at the data. An order chosen from the data invalidates the test.

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 inferential.
  • Groups keep the order declared in the analysis (`order`), which the ordered test assumed — never re-sorted by value.
  • The dashed line is the engine's fitted trend (e.g. isotonic fit or rank-based slope); an umbrella fit peaks at the declared or estimated peak.
# Ordered trend — Codesplash Chart Lab (recipe "trend-plot")
# 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("trend-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["dose"] = pd.Categorical(df["dose"].astype("string"), categories=["0 mg", "5 mg", "10 mg", "20 mg", "40 mg"])

_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
LABEL = "dose"
EST = "median"
LO = "low"
HI = "high"
NOTE = None
FIT = "fitted trend"
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
zone = None
if zone is not None:
    ax.axhspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.plot(pos, d[EST], color=GREY, linewidth=1)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(pos[i], row[EST], yerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (pos[i], hi if np.isfinite(hi) else row[EST]), textcoords="offset points", xytext=(0, 6), ha="center", fontsize=8, color=REF)
ax.set_xticks(pos, d[LABEL].astype(str))
ax.set_ylabel("centre")
if LOG:
    ax.set_yscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads trend-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#correlation-compare

Comparing correlations

Do two correlations differ, and by how much?

Demo data · seed 20261101 · 3 rows · default settings · 640 × 360

How to read it

  1. Read the two top rows as each correlation with its interval.
  2. Read the bottom row as their difference.
  3. If that interval crosses zero, the data are compatible with equal correlations.
  1. Callout 1: One correlation and its interval.
  2. Callout 2: The difference, with Zou's interval.
  3. Callout 3: Reference at zero.

Watch out

  • Overlapping or dependent correlations need the matching test: check the method's design option.

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 inferential.
  • Correlation intervals are Fisher-z intervals back-transformed; the difference row uses Zou's (2007) interval, which is asymmetric and correct for overlapping correlations.
  • The reference line is 0 (no correlation / no difference).
# Comparing correlations — Codesplash Chart Lab (recipe "correlation-compare")
# 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("correlation-compare-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["comparison"] = pd.Categorical(df["comparison"].astype("string"), categories=["r(anxiety, exam) · women", "r(anxiety, exam) · men", "difference"])

_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
LABEL = "comparison"
EST = "r"
LO = "low"
HI = "high"
NOTE = "p"
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))[::-1]  # first row at the top
fig, ax = plt.subplots(figsize=(8, 0.45 * len(d) + 1.4))
zone = None
if zone is not None:
    ax.axvspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.axvline(0, color=REF, linestyle="--", linewidth=1)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(row[EST], pos[i], xerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (1.01, pos[i]), xycoords=("axes fraction", "data"), va="center", fontsize=8, color=REF)
ax.set_yticks(pos, d[LABEL].astype(str))
ax.set_xlabel("correlation (difference)")
if LOG:
    ax.set_xscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads correlation-compare-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#dependence-profile

Dependence profile

Is there any (possibly nonlinear) dependence between two variables, by several measures?

Demo data · seed 20261101 · 7 rows · default settings · 640 × 360

How to read it

  1. Read each row as one measure of dependence.
  2. Compare linear measures (Pearson) with general ones (ξ, distance correlation).
  3. A big general value with a small linear one suggests a nonlinear relationship.
  1. Callout 1: Pearson's r near zero: no straight-line trend.
  2. Callout 2: ξ high: a clear dependence of some other shape.
  3. Callout 3: Each measure's p-value.

Watch out

  • The measures have different scales: don't compare their sizes directly.

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 inferential.
  • Measures are on their own scales (r, ρ, τ in −1…1; ξ, D, dCor in 0…1 for large n; HSIC unbounded): compare each to 0 and read its p, not the bar lengths across measures.
  • Linear measures near 0 with ξ or dCor clearly positive is the signature of a nonlinear relationship.
# Dependence profile — Codesplash Chart Lab (recipe "dependence-profile")
# 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("dependence-profile-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["measure"] = pd.Categorical(df["measure"].astype("string"), categories=["Pearson r", "Spearman ρ", "Kendall τ", "Chatterjee ξ", "Hoeffding D", "distance correlation", "HSIC"])

_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
LABEL = "measure"
EST = "value"
LO = None
HI = None
NOTE = "p"
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))[::-1]  # first row at the top
fig, ax = plt.subplots(figsize=(8, 0.45 * len(d) + 1.4))
zone = None
if zone is not None:
    ax.axvspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.axvline(0, color=REF, linestyle="--", linewidth=1)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(row[EST], pos[i], xerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (1.01, pos[i]), xycoords=("axes fraction", "data"), va="center", fontsize=8, color=REF)
ax.set_yticks(pos, d[LABEL].astype(str))
ax.set_xlabel("value of the measure")
if LOG:
    ax.set_xscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads dependence-profile-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#margin-plot

Non-inferiority & equivalence margins

Does the interval clear the margin — non-inferior, equivalent, inferior or inconclusive?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each interval against the shaded margin.
  2. Fully inside the margin: equivalent. Above the lower bound: non-inferior.
  3. Crossing a boundary: inconclusive.
  1. Callout 1: An interval inside the margin.
  2. Callout 2: An interval crossing the boundary: inconclusive.
  3. Callout 3: The verdict for each comparison.

Watch out

  • The margin must be justified before the data are seen: moving it afterwards invalidates the conclusion.

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 inferential.
  • Differences are oriented so higher is better (treatment − control for a good outcome); a lower margin alone is a non-inferiority question, both margins an equivalence one.
  • Verdicts follow Piaggio et al. (2012, CONSORT NI): interval above max(0, −Δ) superior; above −Δ non-inferior; below −Δ inferior; otherwise inconclusive. Equivalence needs the whole interval inside ±Δ.
  • Margins must be fixed before the data are seen; the shaded band is the region of practical equivalence.
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")
# 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("margin-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["comparison"] = pd.Categorical(df["comparison"].astype("string"), categories=["Site A", "Site B", "Site C", "Pooled"])

_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
LABEL = "comparison"
EST = "difference"
LO = "low"
HI = "high"
NOTE = None
FIT = None
LOG = False
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
pos = np.arange(len(d))[::-1]  # first row at the top
fig, ax = plt.subplots(figsize=(8, 0.45 * len(d) + 1.4))
MLV = "margin"
MHV = None
ML, MH = first(MLV), first(MHV)
def verdict(lo, hi):  # Piaggio et al. (2012): CI against the margin(s)
    if ML is not None and MH is not None:
        return "equivalent" if lo > ML and hi < MH else ("not equivalent" if hi < ML or lo > MH else "inconclusive")
    m = ML if ML is not None else MH
    if m is None: return "inconclusive"
    return "superior" if lo > max(0, m) else "non-inferior" if lo > m else "inferior" if hi < m else "inconclusive"
d["_note"] = [verdict(lo, hi) for lo, hi in zip(d[LO], d[HI])]
d["_color"] = d["_note"].map({"inferior": "#c13e2e", "not equivalent": "#c13e2e", "inconclusive": "#c27c0e"}).fillna("#19966e")
zone = (ML, MH) if ML is not None and MH is not None else ((ML, float(d[HI].max())) if ML is not None else None)
if zone is not None:
    ax.axvspan(*zone, color="#19966e", alpha=0.1, lw=0)
ax.axvline(0, color=REF, linestyle="--", linewidth=1)
if FIT and d[FIT].notna().all():
    ax.plot(pos, d[FIT], color=PALETTE[1], linestyle="--", linewidth=1.8, label="fitted")
colors = d["_color"] if "_color" in d else [PALETTE[0]] * len(d)
for i, row in d.iterrows():
    lo, hi = (row[LO], row[HI]) if LO and HI else (np.nan, np.nan)
    ax.errorbar(row[EST], pos[i], xerr=[[row[EST] - lo], [hi - row[EST]]] if np.isfinite(lo) else None, fmt="o", color=colors[i], capsize=3)
    note = row.get("_note") if "_note" in d else (row[NOTE] if NOTE and pd.notna(row.get(NOTE)) else None)
    if note is not None and note == note:
        txt = note if isinstance(note, str) else ("p < .001" if note < 0.001 else f"p = {note:.3f}".replace("0.", "."))
        ax.annotate(txt, (1.01, pos[i]), xycoords=("axes fraction", "data"), va="center", fontsize=8, color=REF)
ax.set_yticks(pos, d[LABEL].astype(str))
ax.set_xlabel("difference (higher is better)")
if LOG:
    ax.set_xscale("log")
plt.show()

Needs pandas, numpy, matplotlib · reads margin-plot-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#method-comparison

Method comparison

Do two measurement methods agree, or is there constant or proportional bias?

Demo data · seed 20261101 · 50 rows · default settings · 640 × 360

How to read it

  1. Read the points as paired measurements.
  2. Compare the solid fit line with the dashed identity line.
  3. An intercept away from zero suggests constant bias; a slope away from 1, proportional bias.
  1. Callout 1: Fit line: how one method tracks the other.
  2. Callout 2: Identity line: perfect agreement.
  3. Callout 3: The fitted equation.

Watch out

  • A high correlation doesn't mean agreement: two methods can correlate perfectly and still differ.

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 inferential.
  • Both axes share one scale so the identity line is the diagonal.
  • The band joins the lines (upper slope, lower intercept) and (lower slope, upper intercept) — Passing–Bablok's slope and intercept limits move together, pivoting near the data's centre.
  • Linearity (the CUSUM test) and the fit's p-values are on the result card.
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")
# 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("method-comparison-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 = "laboratory"
Y = "meter"
B = "slope"
A = "intercept"
BL = "slope low"
BH = "slope high"
AL = "intercept low"
AH = "intercept high"
d = df.dropna(subset=[X, Y])
lim = np.array([min(d[X].min(), d[Y].min()), max(d[X].max(), d[Y].max())])
b, a, bl, bh, al, ah = (first(k) for k in (B, A, BL, BH, AL, AH))
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(lim, lim, color=REF, linestyle="--", label="identity")
if None not in (bl, bh, al, ah):  # slope limits move with the opposite intercept limits
    ax.fill_between(lim, al + bh * lim, ah + bl * lim, color=PALETTE[0], alpha=0.1, lw=0, label="slope CI limits")
ax.scatter(d[X], d[Y], s=14, color=GREY, edgecolors=REF, linewidths=0.3)
if b is not None and a is not None:
    ax.plot(lim, a + b * lim, color=PALETTE[0], linewidth=2, label=f"y = {a:.3g} + {b:.3g}·x")
ax.set_xlim(*lim)
ax.set_ylim(*lim)
ax.set_aspect("equal")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads method-comparison-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#esd-sequence

Generalized ESD sequence

How many outliers does Rosner's generalized ESD test find?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Read the points left to right as the most extreme values removed one by one.
  2. Compare each with its dashed critical value.
  3. The count of outliers is the last step above the line, even if earlier ones dip.
  1. Callout 1: The most extreme value and its studentized deviation.
  2. Callout 2: The dashed line: critical values.
  3. Callout 3: Red: flagged outliers.

Watch out

  • It assumes normal data apart from the outliers, and the count you allow affects the result.

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 inferential.
  • The number of outliers is max{i : Rᵢ > λᵢ}, not the count of steps above the line — an earlier step below its λ can still be an outlier (masking).
  • Critical values use Rosner's t-approximation at the engine's α for the declared maximum number of outliers.
# Generalized ESD sequence — Codesplash Chart Lab (recipe "esd-sequence")
# 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("esd-sequence-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")
S = "step"
R = "R"
L = "lambda"
VAL = "value"
d = df.dropna(subset=[S, R]).sort_values(S)
above = d.loc[d[R] > d[L], S]
n_out = int(above.max()) if len(above) else 0  # Rosner: max{i : R_i > λ_i}, not a count
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(d[S], d[L], color="#c13e2e", linestyle="--", label="critical λ")
ax.plot(d[S], d[R], color=plt.rcParams["text.color"], marker="o", label="R")
out = d[d[S] <= n_out]
ax.scatter(out[S], out[R], s=50, color="#c13e2e", zorder=3, label=f"outliers: {len(out)}")
if VAL:
    for _, r in d.iterrows():
        ax.annotate(f"{r[VAL]:g}", (r[S], r[R]), xytext=(0, 7), textcoords="offset points", ha="center", fontsize=8, color=REF)
ax.set_xlabel("points removed (step i)")
ax.set_ylabel("R (studentized deviation)")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads esd-sequence-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#qr-process

Quantile process

Does a predictor's effect change across the outcome's distribution?

Demo data · seed 20261101 · 38 rows · default settings · 640 × 360

How to read it

  1. Read one panel per predictor; the x axis is the quantile τ.
  2. Compare the line with the dashed OLS estimate.
  3. A rising line means the predictor's effect is stronger in the upper part of the outcome.
  1. Callout 1: The coefficient at low quantiles.
  2. Callout 2: It grows across quantiles here.
  3. Callout 3: Dashed lines: the OLS estimate and interval.

Watch out

  • Extreme quantiles have wide bands with few rows: don't over-read their ends.

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 inferential.
  • One panel per term (up to six); bands are the engine's pointwise intervals (nid / kernel SEs or the rank inversion), not simultaneous bands.
  • A flat process inside the OLS band means the predictor shifts the whole distribution; a slope means it changes the spread or shape.
# Quantile process — Codesplash Chart Lab (recipe "qr-process")
# 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("qr-process-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["income", "household size"])

_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)))
T = "tau"
E = "coefficient"
LO = "low"
HI = "high"
TERM = "term"
O = "OLS"
OL = "OLS low"
OH = "OLS high"
d = df.dropna(subset=[T, E])
terms = levels_of(d[TERM])[:6] if TERM else [None]
cols = 1 if len(terms) <= 1 else 2 if len(terms) <= 4 else 3
rows = int(np.ceil(len(terms) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4.2 * cols, 3 * rows), squeeze=False)
for ax, term in zip(axes.flat, terms):
    s = (d[d[TERM].astype(str) == str(term)] if TERM else d).sort_values(T)
    if LO and HI:
        ax.fill_between(s[T], s[LO], s[HI], color=PALETTE[0], alpha=0.18, lw=0)
    ax.plot(s[T], s[E], color=PALETTE[0], marker="o", markersize=3)
    if O and s[O].notna().any():
        ax.axhline(s[O].dropna().iloc[0], color=REF, linestyle="--")
        if OL and OH:
            ax.axhline(s[OL].dropna().iloc[0], color=REF, linestyle=":")
            ax.axhline(s[OH].dropna().iloc[0], color=REF, linestyle=":")
    ax.axhline(0, color=GREY, linewidth=0.8)
    ax.set_title(str(term) if term is not None else E, fontsize=9, loc="left")
    ax.set_xlabel("quantile τ")
for ax in list(axes.flat)[len(terms):]:
    ax.set_visible(False)
plt.show()

Needs pandas, numpy, matplotlib · reads qr-process-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#censored-fit

Censored regression (Tobit) fit

How does a Tobit model's latent mean relate to outcomes that pile up at a limit?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read each point as an outcome against its fitted latent mean.
  2. Squares mark rows censored at the limit.
  3. The latent mean extends below the limit, which is why simple regression would be biased.
  1. Callout 1: Censored rows, piled up at the limit.
  2. Callout 2: Uncensored rows follow the line.
  3. Callout 3: The line y = x.

Watch out

  • If far more than half the rows are censored, the estimates lean heavily on normality.

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 inferential.
  • Status values containing “left/lower” or “right/upper” mark censored rows; everything else is uncensored.
  • Censored points sit on the limit line by construction — their true latent value is beyond it, which is what the Tobit likelihood accounts for.
# Censored regression (Tobit) fit — Codesplash Chart Lab (recipe "censored-fit")
# 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("censored-fit-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["status"] = pd.Categorical(df["status"].astype("string"), categories=["observed", "left-censored"])

_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")
F = "x′β"
O = "hours"
ST = "status"
d = df.dropna(subset=[F, O])
status = d[ST].astype(str).str.lower() if ST else pd.Series("", index=d.index)
cens = status.str.contains("left|lower|below|right|upper|above")
lim = [min(d[F].min(), d[O].min()), max(d[F].max(), d[O].max())]
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot(lim, lim, color=REF, linestyle="--", label="y = x")
ax.scatter(d.loc[~cens, F], d.loc[~cens, O], s=14, color=PALETTE[0], alpha=0.6, label="uncensored")
ax.scatter(d.loc[cens, F], d.loc[cens, O], s=26, marker="s", facecolors="none", edgecolors="#c27c0e", label="censored (at the limit)")
ax.set_xlabel("fitted latent mean (x'b)")
ax.set_ylabel(O)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads censored-fit-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#mediation-path

Mediation path diagram

How much of an exposure's effect runs through a mediator?

Demo data · seed 20261101 · 8 rows · default settings · 640 × 360

How to read it

  1. Read the top path: exposure → mediator (a), mediator → outcome (b).
  2. Read the bottom path: the direct effect (c′).
  3. Read the indirect effect (a×b) at the bottom with its interval.
  1. Callout 1: Path a: exposure to mediator.
  2. Callout 2: Path b: mediator to outcome.
  3. Callout 3: Direct effect.
  4. Callout 4: Indirect effect and total.

Watch out

  • Calling this causal needs no unmeasured confounding on every path, which data alone cannot show.

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 inferential.
  • Paths a and b are the mediator and outcome models' coefficients; ACME, ADE (c′) and total come from the engine's bootstrap or quasi-Bayesian simulation, so ACME need not equal a × b exactly with interactions or non-linear models.
  • The diagram states a causal model: the indirect effect is causal only under sequential ignorability.
# Mediation path diagram — Codesplash Chart Lab (recipe "mediation-path")
# 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("mediation-path-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["path"] = pd.Categorical(df["path"].astype("string"), categories=["x", "m", "y", "a", "b", "c_prime", "acme", "total"])

_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")
PATH = "path"
EST = "estimate"
LO = "low"
HI = "high"
P = "p"
NAME = "name"
def norm(p):
    p = str(p).lower().replace("′", "_prime").replace("'", "_prime").replace(" ", "_")
    return {"c": "c_prime", "direct": "c_prime", "ade": "c_prime", "indirect": "acme"}.get(p, p)
key = df[PATH].map(norm)
names = {k: (str(df.loc[key == k, NAME].iloc[0]) if NAME and (key == k).any() else k.upper()) for k in ("x", "m", "y")}
def label(k):
    r = df[key == k]
    if r.empty or pd.isna(r[EST].iloc[0]):
        return "—"
    s = f"{r[EST].iloc[0]:.2f}"
    if LO and HI and pd.notna(r[LO].iloc[0]):
        s += f" [{r[LO].iloc[0]:.2f}, {r[HI].iloc[0]:.2f}]"
    if P and pd.notna(r[P].iloc[0]):
        p = r[P].iloc[0]
        s += ", p < .001" if p < 0.001 else f", p = {p:.3f}".replace("0.", ".")
    return s
pos = {"x": (0.12, 0.25), "m": (0.5, 0.82), "y": (0.88, 0.25)}
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.set_axis_off()
box = dict(boxstyle="round,pad=0.5", facecolor="none", edgecolor=plt.rcParams["text.color"])
for k, (x, y) in pos.items():
    ax.text(x, y, names[k], ha="center", va="center", fontsize=11, fontweight="bold", bbox=box)
arrow = dict(arrowstyle="-|>", color=PALETTE[0], lw=1.6)
ax.annotate("", xy=(0.43, 0.75), xytext=(0.16, 0.32), arrowprops=arrow)
ax.annotate("", xy=(0.84, 0.32), xytext=(0.57, 0.75), arrowprops=arrow)
ax.annotate("", xy=(0.78, 0.25), xytext=(0.22, 0.25), arrowprops=dict(arrowstyle="-|>", color=REF, lw=1.4))
ax.text(0.27, 0.56, "a " + label("a"), ha="right", fontsize=9)
ax.text(0.73, 0.56, "b " + label("b"), ha="left", fontsize=9)
ax.text(0.5, 0.29, "c′ (direct) " + label("c_prime"), ha="center", fontsize=9)
ax.text(0.5, 0.08, "indirect (ACME) " + label("acme") + "\ntotal " + label("total"), ha="center", fontsize=9)
plt.show()

Needs pandas, numpy, matplotlib · reads mediation-path-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#nested-compare

Nested model comparison

Does each added block of predictors improve the model enough?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read left to right as adding blocks of predictors.
  2. Lower deviance means a closer fit, and it always falls.
  3. Read the labels between points: does each drop beat its test?
  1. Callout 1: The simplest model.
  2. Callout 2: A big drop, with its test.
  3. Callout 3: A small drop that doesn't earn its complexity.

Watch out

  • The order of adding blocks changes each step's test.

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 inferential.
  • Models are in the order given (smallest first); each annotation is the test of that model against the previous one (LR χ², Wald, score or partial F).
# Nested model comparison — Codesplash Chart Lab (recipe "nested-compare")
# 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("nested-compare-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["intercept", "+ age", "+ age + sex", "+ age × sex"])

_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")
M = "model"
V = "deviance"
S = "LR chi2"
P = "p"
d = df.dropna(subset=[V]).drop_duplicates(subset=[M]).reset_index(drop=True)
x = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(x, d[V], color=GREY, marker="o", markerfacecolor=PALETTE[0], markeredgecolor=PALETTE[0])
for i in range(1, len(d)):
    bits = ([f"stat {d[S][i]:.3g}"] if S and pd.notna(d[S][i]) else []) + ([("p < .001" if d[P][i] < 0.001 else f"p = {d[P][i]:.3f}".replace("0.", "."))] if P and pd.notna(d[P][i]) else [])
    ax.annotate(", ".join(bits), ((x[i - 1] + x[i]) / 2, (d[V][i - 1] + d[V][i]) / 2), ha="center", va="top", xytext=(0, -6), textcoords="offset points", fontsize=8)
ax.set_xticks(x, d[M].astype(str))
ax.set_ylabel(V)
plt.show()

Needs pandas, numpy, matplotlib · reads nested-compare-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#recursive-residual

Recursive residuals (CUSUM)

Are a regression's coefficients stable over time, or does the fit drift?

Demo data · seed 20261101 · 77 rows · default settings · 640 × 360

How to read it

  1. Read the line as the cumulative sum of recursive residuals in time order.
  2. A stable regression keeps it near zero, inside the bounds.
  3. Touching a bound suggests the coefficients have moved.
  1. Callout 1: Reaches the bound: coefficients are unstable.
  2. Callout 2: The upper 5% bound.
  3. Callout 3: Near zero: the fit is stable early on.

Watch out

  • It's better at detecting a coefficient shift than a change in variance, and needs rows in time order.

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 inferential.
  • Bounds are ±a·√(n−k)·(1 + 2t/(n−k)) with a = 0.948 at 5% (Brown, Durbin & Evans 1975) when the engine publishes the CUSUM; points beyond them are marked.
# Recursive residuals (CUSUM) — Codesplash Chart Lab (recipe "recursive-residual")
# 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("recursive-residual-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")
I = "quarter"
V = "CUSUM"
BL = "lower"
BH = "upper"
d = df.dropna(subset=[I, V]).sort_values(I)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color=GREY, linewidth=0.8)
for b in (BL, BH):
    if b:
        ax.plot(d[I], d[b], color="#c13e2e", linestyle="--", linewidth=1)
ax.plot(d[I], d[V], color=plt.rcParams["text.color"], linewidth=1.6)
if BL and BH:
    out = d[(d[V] > d[BH]) | (d[V] < d[BL])]
    ax.scatter(out[I], out[V], s=16, color="#c13e2e", zorder=3)
ax.set_xlabel(I)
ax.set_ylabel(V)
plt.show()

Needs pandas, numpy, matplotlib · reads recursive-residual-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#prior-posterior

Prior and posterior

How did the data move belief about the effect, and how much more (or less) plausible is the null value now?

Demo data · seed 20261101 · 322 rows · default settings · 640 × 360

How to read it

  1. Compare the dashed prior with the solid posterior: the data moved belief from one to the other.
  2. Compare heights at the test value: if the posterior is lower there, the data favour an effect.
  3. Read the shaded credible interval: where the effect probably lies, given the prior.
  1. Callout 1: The prior's height at the test value.
  2. Callout 2: The posterior's height at the test value.
  3. Callout 3: The posterior: belief about the effect after the data.

Watch out

  • The result depends on the prior. Check robustness across prior widths.

Defaults

Test value (H₀)
0
The effect value to test, usually 0; the chart compares prior and posterior there.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Credible interval lower (equal bounds = none)
0
The lower bound of the credible interval to shade.
Range -1,000,000,000 to 1,000,000,000, step 0.001
Credible interval upper
0
The upper bound of the credible interval to shade.
Range -1,000,000,000 to 1,000,000,000, step 0.001
Credible level
0.95
The share of posterior probability inside the interval.
Range 0.5 to 0.999, step 0.01
Bayes factor BF₁₀ to label (0 = none)
0
Print this Bayes factor on the chart.
Range 0 to 1,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Prior dashed, posterior filled; the dots mark both heights at the test value. For a point null nested in the alternative, posterior height ÷ prior height = BF₀₁ (Savage–Dickey density ratio), the engines' identity check.
  • The credible interval is the engine's equal-tailed interval (quantiles of the posterior).
# Prior and posterior — Codesplash Chart Lab (recipe "prior-posterior")
# controls: point=0, ci_low=0, ci_high=0, cred=0.95, bf10=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("prior-posterior-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["curve"] = pd.Categorical(df["curve"].astype("string"), categories=["Prior", "Posterior"])

_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")
X = "δ (standardized effect)"
D = "density"
K = "curve"
POINT = 0  # the test value
is_prior = df[K].astype(str).str.contains("prior", case=False)
prior, post = df[is_prior].sort_values(X), df[~is_prior].sort_values(X)
fig, ax = plt.subplots(figsize=(7, 4.5))

ax.plot(prior[X], prior[D], color=REF, linestyle="--", label="prior")
ax.plot(post[X], post[D], color=PALETTE[0], linewidth=2, label="posterior")
ax.axvline(POINT, color=REF, linewidth=0.8, linestyle=":")
ax.scatter([POINT], [np.interp(POINT, prior[X], prior[D])], s=30, facecolor="white", edgecolor=REF, zorder=3)
ax.scatter([POINT], [np.interp(POINT, post[X], post[D])], s=30, color=PALETTE[0], zorder=3)
ax.set_xlabel(X)
ax.set_ylabel("density")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads prior-posterior-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#bf-robustness

Bayes factor robustness

Would a wider or narrower prior change the conclusion?

Demo data · seed 20261101 · 41 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the Bayes factor at each prior width.
  2. Find your chosen width on the curve.
  3. If the curve stays in one evidence band across widths, the conclusion doesn't depend on the prior width.
  1. Callout 1: Your chosen prior width.
  2. Callout 2: Evidence band labels.
  3. Callout 3: The BF = 1 line: no evidence either way.

Watch out

  • A range of widths isn't a range of prior shapes: results may still depend on the prior's form.

Defaults

Chosen prior width
0.707
The prior width used in your analysis, marked on the curve.
Range 0 to 100, step 0.01
Log x axis
Off
Space the x axis by ratios, which suits values spanning orders of magnitude.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Shaded bands are Lee & Wagenmakers' (2013) evidence categories after Jeffreys (1961): 1–3 anecdotal, 3–10 moderate, 10–30 strong, 30–100 very strong, above 100 extreme, mirrored below 1 for evidence for H₀.
  • Very wide priors favour H₀ (Bartlett–Lindley): a conclusion that holds across the conventional widths is robust; one that flips is prior-sensitive and should be reported as such.
# Bayes factor robustness — Codesplash Chart Lab (recipe "bf-robustness")
# controls: chosen=0.707, logX=false
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("bf-robustness-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")
CUTS = [1 / 30, 1 / 10, 1 / 3, 1, 3, 10, 30]  # Lee & Wagenmakers (2013) evidence categories
X = "prior width r"
B = "BF₁₀"
d = df[[X, B]].dropna().query(f"`{B}` > 0").sort_values(X)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.set_yscale("log")
for cut in CUTS:
    ax.axhline(cut, color=REF, linewidth=1.2 if cut == 1 else 0.4, linestyle="--" if cut == 1 else ":")
ax.plot(d[X], d[B], color=PALETTE[0], linewidth=2, label=f"BF₁₀ (last {d[B].iloc[-1]:.3g})")
ax.axvline(0.707, color=REF, linewidth=0.8)

ax.set_xlabel("prior width r")
ax.set_ylabel("BF₁₀ (log scale)")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads bf-robustness-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#bf-sequential

Sequential Bayes factor

How did the evidence grow as the observations came in?

Demo data · seed 20261101 · 29 rows · default settings · 640 × 360

How to read it

  1. Read left to right as evidence accumulates.
  2. Rising above 1 favours H₁; falling below 1 favours H₀.
  3. A steady path is reassuring; big swings mean the result rests on a few rows.
  1. Callout 1: The final Bayes factor.
  2. Callout 2: BF = 1: no evidence either way.
  3. Callout 3: Early rows: the path moves a lot.

Watch out

  • The row order is one order among many; another could tell a different story on the way.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Shaded bands are Lee & Wagenmakers' (2013) evidence categories after Jeffreys (1961): 1–3 anecdotal, 3–10 moderate, 10–30 strong, 30–100 very strong, above 100 extreme, mirrored below 1 for evidence for H₀.
  • Rows are taken in the dataset's order; Bayes factors may be monitored as data accrue (the likelihood principle), but the prior must not be tuned to the path.
# Sequential Bayes factor — Codesplash Chart Lab (recipe "bf-sequential")
# 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("bf-sequential-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")
CUTS = [1 / 30, 1 / 10, 1 / 3, 1, 3, 10, 30]  # Lee & Wagenmakers (2013) evidence categories
X = "rows"
B = "BF₁₀"
d = df[[X, B]].dropna().query(f"`{B}` > 0").sort_values(X)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.set_yscale("log")
for cut in CUTS:
    ax.axhline(cut, color=REF, linewidth=1.2 if cut == 1 else 0.4, linestyle="--" if cut == 1 else ":")
ax.plot(d[X], d[B], color=PALETTE[0], linewidth=2, label=f"BF₁₀ (last {d[B].iloc[-1]:.3g})")


ax.set_xlabel("observations so far")
ax.set_ylabel("BF₁₀ (log scale)")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads bf-sequential-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#bf-models

Model Bayes factors

Which model of the factors do the data support, and by how much?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each bar as how much more the data support that model than the intercept-only model.
  2. Longest bar: the best-supported model.
  3. Read the posterior probability to weigh models against each other.
  1. Callout 1: The best-supported model.
  2. Callout 2: Its Bayes factor and posterior probability.
  3. Callout 3: BF = 1: no better than the baseline.

Watch out

  • Posterior probabilities depend on equal prior odds across these models and on which models are listed.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Bars start at BF = 1 (no evidence); the strongest model is drawn solid. Percentages are posterior model probabilities with equal prior odds over the models shown and the intercept-only model.
# Model Bayes factors — Codesplash Chart Lab (recipe "bf-models")
# 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("bf-models-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

M = "model"
B = "BF"
PP = "posterior"
def df_models():
    d = df.dropna(subset=[M, B])
    d = d[d[B] > 0].sort_values(B, ascending=False)
    return pd.DataFrame({"model": d[M].astype(str), "bf": d[B], "posterior": d[PP] if PP else np.nan})
d = df_models()
fig, ax = plt.subplots(figsize=(7, 0.5 * len(d) + 1.2))
y = np.arange(len(d))[::-1]
ax.barh(y, d["bf"], left=1, color=PALETTE[0], alpha=0.7)
ax.set_xscale("log")
ax.set_yticks(y, d["model"])
ax.axvline(1, color="grey", linewidth=0.8)
for i, (bf, pp) in zip(y, zip(d["bf"], d["posterior"])):
    ax.text(1 + bf, i, f" {bf:.3g}" + (f" · {pp:.0%}" if pd.notna(pp) else ""), va="center", fontsize=8)
ax.set_xlabel("Bayes factor against the intercept-only model (log scale)")
plt.show()

Needs pandas, numpy, matplotlib · reads bf-models-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#added-variable

Added-variable plot

What does one predictor add once the others are accounted for, and which rows drive it?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read one panel per term: what that predictor adds after the others have explained what they can.
  2. The line's slope is the term's coefficient in the full model.
  3. Look for labelled rows far along the x axis: they have the most pull on that slope.
  1. Callout 1: The line's slope equals this term's coefficient.
  2. Callout 2: A labelled row: a strong pull on the slope.
  3. Callout 3: One panel per term; a flat line means it adds little.

Watch out

  • A strong slope isn't causal, and one row can create or hide it: refit without the labelled rows to check.

Defaults

Label influential rows
On
Name the rows with the largest pull on each slope.

Pinned in the code

  • Each panel plots the residuals of y on the other predictors against the residuals of this predictor on the other predictors.
  • The fitted line has an intercept; by the Frisch–Waugh–Lovell theorem its slope equals the term's coefficient in the full model.
  • Influential rows are those with the largest |x·y| after centring.
# Added-variable plot — Codesplash Chart Lab (recipe "added-variable")
# controls: labels=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess

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("added-variable-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")
X = "predictor residual"
Y = "sales residual"
T = "term"
d = df.dropna(subset=[X, Y])
terms = list(dict.fromkeys(d[T].astype(str))) if T else ["all rows"]
fig, axes = plt.subplots(1, len(terms), figsize=(4.5 * len(terms), 4), squeeze=False)
for ax, t in zip(axes[0], terms):
    g = d[d[T].astype(str) == t] if T else d
    x, y = g[X].to_numpy(float), g[Y].to_numpy(float)
    b, a = np.polyfit(x, y, 1)  # the least-squares line
    ax.scatter(x, y, s=10, color=PALETTE[0], alpha=0.6)
    grid = np.array([x.min(), x.max()])
    ax.plot(grid, a + b * grid, color=REF, linewidth=1.6)

    ax.set_title(f"{t}  (slope {b:.3g})", fontsize=10)
    ax.set_xlabel("predictor | others")
    ax.set_ylabel("outcome | others")
plt.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, statsmodels · reads added-variable-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#component-residual

Component-plus-residual plot

Is a predictor's effect really a straight line?

Demo data · seed 20261101 · 90 rows · default settings · 640 × 360

How to read it

  1. Read the straight line as what the model assumes for this predictor.
  2. Read the smooth as what the data suggest.
  3. Where they part, the effect is curved: try a transformation or a spline.
  1. Callout 1: The smooth bends away from the line here.
  2. Callout 2: The line: the linear term in the model.

Watch out

  • The smooth is unstable at the edges with few rows, so don't over-read its ends.

Defaults

Smooth
On
Add a LOESS curve; a gap between it and the line suggests a curved effect.

Pinned in the code

  • The partial residual is e + β̂ⱼxⱼ, so the least-squares line has the term's coefficient as its slope.
  • LOESS with span 0.75 (local linear, tricube weights), as the scatter recipe uses.
# Component-plus-residual plot — Codesplash Chart Lab (recipe "component-residual")
# controls: smooth=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.nonparametric.smoothers_lowess import lowess

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("component-residual-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")
X = "ad spend"
Y = "component + residual"
T = None
d = df.dropna(subset=[X, Y])
terms = list(dict.fromkeys(d[T].astype(str))) if T else ["all rows"]
fig, axes = plt.subplots(1, len(terms), figsize=(4.5 * len(terms), 4), squeeze=False)
for ax, t in zip(axes[0], terms):
    g = d[d[T].astype(str) == t] if T else d
    x, y = g[X].to_numpy(float), g[Y].to_numpy(float)
    b, a = np.polyfit(x, y, 1)  # the least-squares line
    ax.scatter(x, y, s=10, color=PALETTE[0], alpha=0.6)
    grid = np.array([x.min(), x.max()])
    ax.plot(grid, a + b * grid, color=REF, linewidth=1.6)
    s = lowess(y, x, frac=0.75, it=0)
    ax.plot(s[:, 0], s[:, 1], color=PALETTE[1], linewidth=1.6)
    ax.set_title(f"{t}  (slope {b:.3g})", fontsize=10)
    ax.set_xlabel("predictor")
    ax.set_ylabel("component + residual")
plt.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, statsmodels · reads component-residual-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#influence-index

Cook's distance by row

Which rows pull the fit the most?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read each stem as how much the fit changes if you leave that row out.
  2. Compare with the dashed cutoff: rows above it are named.
  3. Look at those rows and find out why they differ.
  1. Callout 1: A named row, above the cutoff.
  2. Callout 2: The dashed line: the cutoff.
  3. Callout 3: Most rows have little pull.

Watch out

  • An influential row isn't automatically wrong: don't delete it for being influential. Report the fit with and without it.

Defaults

Cutoff
4 / n
4/n flags rows worth a look; 1 flags rows that shift the whole fit.
Also: 1

Pinned in the code

  • Bars (stems) from zero at each row's Cook's distance, as R's plot.lm(which = 4).
  • A row above the cutoff is drawn in the warning colour and labelled.
# Cook's distance by row — Codesplash Chart Lab (recipe "influence-index")
# controls: rule=four
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("influence-index-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")
D = "Cook's distance"
I = None
L = "row"
d = df.dropna(subset=[D]).reset_index(drop=True)
idx = d[I].to_numpy(float) if I else np.arange(1, len(d) + 1)
cut = 4 / len(d)  # the 4/n convention
flag = d[D] > cut
fig, ax = plt.subplots(figsize=(7, 4))
ax.vlines(idx, 0, d[D], colors=[PALETTE[1] if f else PALETTE[0] for f in flag])
ax.axhline(cut, color=REF, linestyle="--", linewidth=1, label=f"cutoff {cut:.3g}")
for i in np.flatnonzero(flag)[:12]:
    ax.annotate(str(d[L].iloc[i]) if L else str(int(idx[i])), (idx[i], d[D].iloc[i]), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8)
ax.set_xlabel("row")
ax.set_ylabel("Cook's distance")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads influence-index-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#boxcox-profile

Box–Cox profile

Which power transformation would make this outcome behave best?

Demo data · seed 20261101 · 81 rows · default settings · 640 × 360

How to read it

  1. Find the peak: the λ that makes the transformed outcome fit best.
  2. Read the shaded interval: any λ in it fits about as well.
  3. Prefer a round value inside the interval: 0 (log), 0.5 (square root) or 1 (no change).
  1. Callout 1: The best λ, with its interval shaded.
  2. Callout 2: The dashed line: the interval's cutoff.
  3. Callout 3: λ = 1 means no transformation.

Watch out

  • It targets normal residuals with equal spread, not interpretation. A transformed outcome changes what the coefficients mean.

Defaults

Interval level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.5 to 0.99, step 0.01

Demo data

Skew of the demo data
0.7
The log-normal σ behind the demo: more skew moves the best λ towards the log.
Range 0.1 to 1.5, step 0.1

Pinned in the code

  • As MASS::boxcox: y is divided by its geometric mean, then log-likelihood = −n/2 · log RSS of the transformed y.
  • The interval is where the curve stays within χ²₁(level)/2 of its maximum, by linear interpolation on the λ grid.
# Box–Cox profile — Codesplash Chart Lab (recipe "boxcox-profile")
# controls: level=0.95
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("boxcox-profile-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")
L = "λ"
LL = "log-likelihood"
d = df.dropna(subset=[L, LL]).sort_values(L)
lam, ll = d[L].to_numpy(float), d[LL].to_numpy(float)
best = int(np.argmax(ll))
cut = ll[best] - stats.chi2.ppf(0.95, 1) / 2  # interval: within χ²₁/2 of the maximum
inside = np.flatnonzero(ll >= cut)
lo = np.interp(cut, ll[: inside[0] + 1], lam[: inside[0] + 1]) if inside[0] > 0 else np.nan
hi = np.interp(cut, ll[inside[-1] :][::-1], lam[inside[-1] :][::-1]) if inside[-1] < len(ll) - 1 else np.nan
fig, ax = plt.subplots(figsize=(7, 4))
if np.isfinite(lo) and np.isfinite(hi):
    ax.axvspan(lo, hi, color=PALETTE[0], alpha=0.1, label=f"interval [{lo:.2f}, {hi:.2f}]")
ax.plot(lam, ll, color=PALETTE[0], linewidth=2)
ax.scatter([lam[best]], [ll[best]], s=40, color=PALETTE[0], zorder=3, label=f"best λ {lam[best]:.2f}")
ax.axhline(cut, color=REF, linestyle="--", linewidth=1)
for v, t in ((0, "log"), (1, "no change")):
    if lam[0] <= v <= lam[-1]:
        ax.axvline(v, color=REF, linestyle=":", linewidth=0.8)
        ax.annotate(t, (v, ll.max()), fontsize=8, xytext=(3, 0), textcoords="offset points")
ax.set_xlabel("λ")
ax.set_ylabel("log-likelihood")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads boxcox-profile-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#deming-fit

Deming fit

What is the line between two noisy measurements, when both have error?

Demo data · seed 20261101 · 40 rows · default settings · 640 × 360

How to read it

  1. Read the bold line as the fit when both measurements have error.
  2. Compare it with the identity line: an offset suggests constant bias, a different slope proportional bias.
  3. Change δ to see how the assumed error ratio moves the line.
  1. Callout 1: The Deming line.
  2. Callout 2: The identity line: perfect agreement.
  3. Callout 3: Segments slant: both x and y have error.

Watch out

  • The slope depends on δ. Choose it from replicate measurements rather than from what looks good.

Defaults

Error variance ratio δ (y ÷ x)
1
How much noisier y is than x. δ = 1 is orthogonal regression; very large δ tends to ordinary least squares.
Range 0.1 to 10, step 0.1
Residual segments
On
Draw each row's path to the line.

Demo data

Proportional bias in the demo
1.08
The true slope behind the demo data.
Range 0.8 to 1.3, step 0.01

Pinned in the code

  • Slope b = (s_yy − δ·s_xx + √((s_yy − δ·s_xx)² + 4δ·s_xy²)) / (2·s_xy), intercept ȳ − b·x̄ (Linnet 1990).
  • Fitted x̂ᵢ = xᵢ + b/(b² + δ) · (yᵢ − a − b·xᵢ); each segment joins (xᵢ, yᵢ) with (x̂ᵢ, a + b·x̂ᵢ).
  • Both axes share one scale, so the identity line is the diagonal.
# Deming fit — Codesplash Chart Lab (recipe "deming-fit")
# controls: delta=1, segments=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("deming-fit-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")
X = "method A"
Y = "method B"
DELTA = 1  # ratio of y-error variance to x-error variance
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(float), d[Y].to_numpy(float)
sxx, syy, sxy = np.var(x, ddof=1), np.var(y, ddof=1), np.cov(x, y)[0, 1]
b = (syy - DELTA * sxx + np.sqrt((syy - DELTA * sxx) ** 2 + 4 * DELTA * sxy**2)) / (2 * sxy)  # Linnet (1990)
a = y.mean() - b * x.mean()
fx = x + b / (b**2 + DELTA) * (y - a - b * x)
lim = np.array([min(x.min(), y.min()), max(x.max(), y.max())])
fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.plot(lim, lim, color=REF, linestyle="--", label="identity (y = x)")
for i in range(len(x)):
    ax.plot([x[i], fx[i]], [y[i], a + b * fx[i]], color=REF, alpha=0.35, linewidth=0.8)
ax.plot(lim, a + b * lim, color=PALETTE[0], linewidth=2, label=f"y = {a:.3g} + {b:.3g}·x")
ax.scatter(x, y, s=16, color=PALETTE[0], edgecolors="white", linewidths=0.5, zorder=3)
ax.set_aspect("equal", adjustable="datalim")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads deming-fit-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#agreement-chart

Agreement chart

Where do two raters agree, and where do they part?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read each rectangle's width and height as the two raters' totals for that category.
  2. Dark squares are exact agreement: the larger the share of the rectangle, the better.
  3. Lighter areas are one step off; a rectangle far from square means the raters use that category differently.
  1. Callout 1: Exact agreement for the first category.
  2. Callout 2: A lighter band: one step off.
  3. Callout 3: Bangdiwala's B: 1 is perfect agreement.

Watch out

  • Like kappa, it depends on how common each category is. Compare with the raw table.

Defaults

One step off
On
Shade neighbouring categories, for ordered scales.

Pinned in the code

  • The square has side n. Each category's rectangle is (A's total) × (B's total), placed corner to corner along the diagonal.
  • B = Σ nᵢᵢ² / Σ nᵢ₊n₊ᵢ: the agreement squares' area over the rectangles' area. Perfect agreement gives 1.
  • Levels follow the rater columns' order, so an ordered scale runs along the diagonal.
# Agreement chart — Codesplash Chart Lab (recipe "agreement-chart")
# controls: partial=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("agreement-chart-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["rater A"] = pd.Categorical(df["rater A"].astype("string"), categories=["low", "medium", "high", "severe"])
df["rater B"] = pd.Categorical(df["rater B"].astype("string"), categories=["low", "medium", "high", "severe"])

_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)))
A = "rater A"
B = "rater B"
N = None
d = df.dropna(subset=[A, B]).assign(_n=lambda f: f[N].astype(float) if N else 1.0)
levels = list(dict.fromkeys(levels_of(d[A]) + levels_of(d[B])))
tab = d.pivot_table(index=d[A].astype(str), columns=d[B].astype(str), values="_n", aggfunc="sum", fill_value=0).reindex(index=levels, columns=levels, fill_value=0)
n, rows, cols = tab.to_numpy().sum(), tab.sum(axis=1).to_numpy(), tab.sum(axis=0).to_numpy()
agree = np.diag(tab.to_numpy())
B_stat = (agree**2).sum() / (rows * cols).sum()  # Bangdiwala's B
xs, ys = np.r_[0, np.cumsum(rows)], np.r_[0, np.cumsum(cols)]  # rectangles run corner to corner
m = tab.to_numpy()
fig, ax = plt.subplots(figsize=(5.5, 5.5))
for i, k in enumerate(levels):
    ax.add_patch(plt.Rectangle((xs[i], ys[i]), rows[i], cols[i], facecolor=GREY, alpha=0.25, edgecolor=REF))
    pw = (m[i, i - 1] if i else 0) + m[i, i] + (m[i, i + 1] if i + 1 < len(levels) else 0)
    ph = (m[i - 1, i] if i else 0) + m[i, i] + (m[i + 1, i] if i + 1 < len(levels) else 0)
    ax.add_patch(plt.Rectangle((xs[i], ys[i]), pw, ph, facecolor=PALETTE[0], alpha=0.3))
    ox, oy = (m[i, i - 1], m[i - 1, i]) if i else (0, 0)
    ax.add_patch(plt.Rectangle((xs[i] + ox, ys[i] + oy), agree[i], agree[i], facecolor=PALETTE[0]))
    ax.text(xs[i] + 0.01 * n, ys[i] + cols[i] - 0.03 * n, k, fontsize=8)
ax.set_xlim(0, n)
ax.set_ylim(0, n)
ax.set_aspect("equal")
ax.set_xlabel(A)
ax.set_ylabel(B)
ax.set_title(f"Bangdiwala's B = {B_stat:.3f}", fontsize=10)
plt.show()

Needs pandas, numpy, matplotlib · reads agreement-chart-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#roc-compare

ROC comparison

Is one score really better than the other on these rows?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Compare the two curves: higher and further left is better.
  2. Read ΔAUC and its interval: how much better one score is on these rows.
  3. Read DeLong's p-value: it uses the pairing, so it's sharper than comparing two separate intervals.
  1. Callout 1: Score A runs above score B here.
  2. Callout 2: The difference, its interval and the test.
  3. Callout 3: Each score's AUC.

Watch out

  • A small AUC gain can be useless at the threshold you would really use.
  • Testing a nested model's added predictor this way is known to be conservative.

Defaults

Interval level
0.95
How often intervals built this way contain the true value, over repeated samples.
Range 0.8 to 0.99, step 0.01
Chance diagonal
On
Draw the line a score with no skill would follow.

Demo data

Advantage of score A in the demo
0.6
How much better separated score A is than score B in the demo data.
Range 0 to 1.5, step 0.1

Pinned in the code

  • AUC is the Mann–Whitney probability a positive outscores a negative, ties counting ½.
  • DeLong, DeLong & Clarke-Pearson (1988): the paired variance of ΔAUC from the placement values, z = ΔAUC / SE, a normal two-sided p.
  • Higher scores predict positives. Values match pROC::roc.test(method = "delong", paired = TRUE).
# ROC comparison — Codesplash Chart Lab (recipe "roc-compare")
# controls: level=0.95, diagonal=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("roc-compare-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")
L = "event"
A = "new score"
B = "old score"
d = df.dropna(subset=[L, A, B])
pos = d[L].astype(str).str.lower().isin(["1", "true", "yes", "positive", "pos"]).to_numpy()
def components(s):  # DeLong placement values
    p, n = s[pos][:, None], s[~pos][None, :]
    psi = (p > n) + 0.5 * (p == n)
    return psi.mean(axis=1), psi.mean(axis=0)
def roc_points(s):
    cuts = np.unique(s)[::-1]
    return np.r_[0, [(s[~pos] >= t).mean() for t in cuts]], np.r_[0, [(s[pos] >= t).mean() for t in cuts]]
a, b = d[A].to_numpy(float), d[B].to_numpy(float)
(a10, a01), (b10, b01) = components(a), components(b)
auc_a, auc_b = a10.mean(), b10.mean()
var = np.var(a10 - b10, ddof=1) / len(a10) + np.var(a01 - b01, ddof=1) / len(a01)  # paired, DeLong et al. (1988)
diff, se = auc_a - auc_b, np.sqrt(var)
z = diff / se
p_value = 2 * stats.norm.sf(abs(z))
q = stats.norm.ppf(1 - (1 - 0.95) / 2)
note = f"ΔAUC {diff:.3f} [{diff - q * se:.3f}, {diff + q * se:.3f}], DeLong z = {z:.2f}, p = {p_value:.3f}"
fig, ax = plt.subplots(figsize=(5.5, 5.5))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", linewidth=1)
for i, (s, name, auc) in enumerate(((a, A, auc_a), (b, B, auc_b))):
    fpr, tpr = roc_points(s)
    ax.step(fpr, tpr, where="post", color=PALETTE[i], label=f"{name} (AUC {auc:.3f})")
ax.set_xlabel("1 − specificity (false-positive rate)")
ax.set_ylabel("sensitivity (true-positive rate)")
ax.set_title(note, fontsize=9)
ax.legend(fontsize=8, loc="lower right")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads roc-compare-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#loglog-survival

Log–log survival plot

Are the hazards proportional, and could the times be Weibull?

Demo data · seed 20261101 · 102 rows · default settings · 640 × 360

How to read it

  1. Read x as log time and y as log(−log S(t)), the scale on which proportional hazards plot as parallel curves.
  2. Parallel curves support proportional hazards; curves that converge or cross do not.
  3. A straight line for a group supports a Weibull lifetime for that group.
  1. Callout 1: A wide gap early on.
  2. Callout 2: The curves meet here, so the hazard ratio is changing.
  3. Callout 3: One curve per group.

Watch out

  • The far left rests on a handful of events, so give those steps little weight.
  • When the curves are not parallel, the single hazard ratio from a log-rank or Cox model is an average over time.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Points with S(t) = 0 or 1 are left out, because the transform is infinite there.
# Log–log survival plot — Codesplash Chart Lab (recipe "loglog-survival")
# 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("loglog-survival-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["control", "treated"])

_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")
T = "days"
Y = "survival"
G = "arm"
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 curves():
    groups = levels_of(df[G]) if G else [None]
    for g in groups:
        d = df if g is None else df[df[G].astype(str) == str(g)]
        d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
        t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
        keep = (t > 0) & (v > 0) & (v < 1)
        t, v = t[keep], v[keep]
        yield ("all" if g is None else str(g)), np.log(t), np.log(-np.log(v))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, y) in enumerate(curves()):
    ax.step(t, y, where="post", color=PALETTE[i % len(PALETTE)], label=name)
ax.set_xlabel(f"log {T}")
ax.set_ylabel("log(−log S(t))")
ax.set_title("Log–log survival: parallel curves mean proportional hazards", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads loglog-survival-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#cumhaz

Cumulative hazard

How has risk built up over time?

Demo data · seed 20261101 · 102 rows · default settings · 640 × 360

How to read it

  1. Read x as time and y as the accumulated hazard, H(t) = −log S(t).
  2. Read the slope as the failure rate at that time: steeper means failures are coming faster.
  3. A straight line through the origin is a constant rate, as an exponential lifetime has.
  1. Callout 1: A shallow stretch: few failures for the time at risk.
  2. Callout 2: A steep stretch: the rate is higher.
  3. Callout 3: One curve per group.

Watch out

  • The right end rests on few units at risk, so its jumps look larger than they deserve.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Computed from the plotted survival curve; points where S(t) = 0 are left out.
# Cumulative hazard — Codesplash Chart Lab (recipe "cumhaz")
# 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("cumhaz-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["control", "treated"])

_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")
T = "days"
Y = "survival"
G = "arm"
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 curves():
    groups = levels_of(df[G]) if G else [None]
    for g in groups:
        d = df if g is None else df[df[G].astype(str) == str(g)]
        d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
        t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
        keep = v > 0
        t, v = t[keep], v[keep]
        yield ("all" if g is None else str(g)), t, -np.log(v)
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, y) in enumerate(curves()):
    ax.step(t, y, where="post", color=PALETTE[i % len(PALETTE)], label=name)
ax.set_xlabel(T)
ax.set_ylabel("H(t) = −log S(t)")
ax.set_title("Cumulative hazard: a straight line means a constant hazard", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads cumhaz-demo.csv · app theme from the optional codesplash helper

Inference & models

svg#rmst-area

Restricted mean survival area

How much event-free time does each group have up to a horizon?

Demo data · seed 20261101 · 102 rows · default settings · 640 × 360

How to read it

  1. Read each curve as the share still event-free over time, and τ as the horizon marked by the dashed line.
  2. Read the area under a curve up to τ as that group's restricted mean survival time, given in the legend.
  3. Read the shaded gap between the curves as the difference in mean event-free time up to τ.
  1. Callout 1: τ: the area stops here.
  2. Callout 2: The shared area: time both groups have on average.
  3. Callout 3: The gap: extra event-free time for one group.
  4. Callout 4: Each group's restricted mean, in time units.

Watch out

  • Choose τ from the question before you see the curves. It should also stay within the follow-up of both groups.

Defaults

Horizon τ
0
Time horizon for the area (0 uses the shorter follow-up).
Range 0 to 1,000,000, step 10

Pinned in the code

  • RMST = ∫₀^τ S(t) dt under the Kaplan–Meier step curve; the default τ is the shorter of the groups' last times.
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")
# controls: tau=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("rmst-area-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["control", "treated"])

_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")
T = "days"
Y = "survival"
G = "arm"
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)))
TAU = 0
groups = levels_of(df[G]) if G else [None]
curves = []
for g in groups:
    d = df if g is None else df[df[G].astype(str) == str(g)]
    d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
    curves.append(("all" if g is None else str(g), d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)))
tau = TAU if TAU > 0 else min(t[-1] for _, t, _ in curves)  # the shorter follow-up
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, s) in enumerate(curves):
    keep = t <= tau
    tt, ss = np.append(t[keep], tau), np.append(s[keep], s[keep][-1])
    rmst = float(np.sum(np.diff(tt) * ss[:-1]))  # area under the step curve
    color = PALETTE[i % len(PALETTE)]
    ax.step(tt, ss, where="post", color=color, label=f"{name}: RMST {rmst:.4g}")
    ax.fill_between(tt, ss, step="post", color=color, alpha=0.12)
ax.axvline(tau, color=REF, linestyle="--")
ax.set_xlabel(T)
ax.set_ylabel("Survival probability")
ax.set_title(f"Restricted mean survival up to {tau:g}", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads rmst-area-demo.csv · app theme from the optional codesplash helper

Machine learning

Model evaluation and explanation: PR and gain curves, thresholds, importance, SHAP, PDP/ALE, tuning and validation splits.

32

Machine learning

svg#pr-curve

Precision–recall curve

How much precision does the model keep as it finds more of the positives?

Demo data · seed 20261101 · 202 rows · default settings · 640 × 360

How to read it

  1. Read each point as a threshold: its recall (how many positives you catch) and precision (how many flagged are right).
  2. Higher and further right is better.
  3. Compare with the no-skill line, which sits at the share of positives.
  1. Callout 1: High precision at low recall: the most confident predictions.
  2. Callout 2: As recall rises, precision falls: you flag more wrong rows.
  3. Callout 3: Average precision in the legend.

Watch out

  • Baselines change with prevalence: compare only models scored on the same positive share.

Defaults

No-skill baseline (prevalence; 0 = none)
0
Draw the precision of a model with no skill: the share of positives.
Range 0 to 1, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Points are joined in order of recall; the legend's AP is the step sum Σ (Rₙ − Rₙ₋₁)·Pₙ (scikit-learn's average precision), not the trapezoid area.
  • The no-skill baseline is the prevalence: a classifier that ranks at random has that precision at every recall.
  • Prefer this to ROC when positives are rare — ROC can look good while precision is poor.
# Precision–recall curve — Codesplash Chart Lab (recipe "pr-curve")
# controls: baseline=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("pr-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["XGBoost", "Logistic regression"])

_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 average_precision(recall, precision):
    """Step-wise AP: Σ (R_k − R_{k−1}) · P_k over increasing recall (scikit-learn's definition)."""
    r, p = np.asarray(recall, float), np.asarray(precision, float)
    return float(np.sum(np.diff(np.concatenate([[0.0], r])) * p))
REC = "recall"
PREC = "precision"
CURVE = "model"
BASELINE = 0  # prevalence: the no-skill precision (0 = none)
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
    d = df if name is None else df[df[CURVE].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[REC]).sort_values([REC], kind="mergesort")))
fig, ax = plt.subplots(figsize=(6.5, 5))
if 0 < BASELINE < 1:
    ax.axhline(BASELINE, color=REF, linestyle="--", linewidth=1, label=f"no skill ({BASELINE:.0%})")
for i, (name, d) in enumerate(series):
    ap = average_precision(d[REC], d[PREC])
    ax.step(d[REC], d[PREC], where="post", color=PALETTE[i % len(PALETTE)], linewidth=2, label=f"{name + ' ' if name else ''}AP {ap:.3f}")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1.02)
ax.set_xlabel(REC)
ax.set_ylabel(PREC)
ax.legend(fontsize=8, loc="lower left")
plt.show()

Needs pandas, numpy, matplotlib · reads pr-curve-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#lift-gain

Cumulative gain and lift

If we act on the top-scored share of cases, what share of the positives do we reach?

Demo data · seed 20261101 · 42 rows · default settings · 640 × 360

How to read it

  1. Read the x axis as how much of the list you act on, top-scored first.
  2. Read the y axis as the share of all positives reached.
  3. Compare with the diagonal: random targeting.
  1. Callout 1: Acting on the top 20% reaches this share of the positives.
  2. Callout 2: Diagonal: random targeting.
  3. Callout 3: Everything reached, eventually.

Watch out

  • It ignores cost. Choose where to stop using the value of a hit and the cost of acting.

Defaults

Show
Cumulative gain
Which view to draw.
Also: Lift

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Cases are ranked by predicted probability, highest first; gain at x is the share of all positives among the top x of cases (deciles or every case, as the run sends).
  • Lift = gain ÷ share targeted; when the run sends no lift column the chart derives it from the two.
  • The diagonal (gain) or the line at 1 (lift) is random targeting.
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")
# controls: mode=gain
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("lift-gain-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["model"] = pd.Categorical(df["model"].astype("string"), categories=["Gradient boosting", "Random forest"])

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)))
F = "share of customers contacted"
GAIN = "share of churners reached"
LIFT = None
CURVE = "model"
MODE = "gain"  # "gain" (share of positives captured) or "lift" (× random)
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
    d = df if name is None else df[df[CURVE].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values([F], kind="mergesort")))
fig, ax = plt.subplots(figsize=(7, 4.8))
if MODE == "gain":
    ax.plot([0, 1], [0, 1], color="grey", linestyle="--", linewidth=1, label="random")
else:
    ax.axhline(1, color="grey", linestyle="--", linewidth=1, label="random")
for i, (name, d) in enumerate(series):
    if MODE == "gain":
        y = d[GAIN]
    else:
        d = d[d[F] > 0]
        y = d[LIFT] if LIFT else d[GAIN] / d[F]
    ax.plot(d[F], y, color=PALETTE[i % len(PALETTE)], linewidth=2, marker="o", ms=3, label=name or GAIN)
ax.set_xlabel(F)
ax.set_ylabel(GAIN if MODE == "gain" else "lift (× random)")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads lift-gain-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#threshold-metrics

Metrics across thresholds

Where should the decision threshold sit, and what does each choice trade off?

Demo data · seed 20261101 · 196 rows · default settings · 640 × 360

How to read it

  1. Read each curve as one metric as the threshold moves.
  2. Find the marker: the threshold chosen now.
  3. Pick the threshold from your error costs, not from where the lines cross.
  1. Callout 1: The chosen threshold.
  2. Callout 2: Each metric's value at it.
  3. Callout 3: Low threshold: high recall, lower precision.

Watch out

  • The best threshold on validation data will look a little worse on new data.

Defaults

Chosen threshold
0.5
The decision threshold to mark on the chart.
Range -1,000,000 to 1,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • A case is predicted positive when its score is at or above the threshold (scikit-learn's convention).
  • The marker is the run's chosen threshold (F-β, Youden or minimum cost, as the evaluation says) — 0.5 when none was chosen.
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")
# controls: marker=0.5
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("threshold-metrics-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["precision", "recall", "F1", "specificity"])

_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)))
T = "probability threshold"
V = "value"
M = "metric"
MARKER = 0.5  # the chosen threshold
groups = levels_of(df[M]) if M else [None]
series = []
for name in groups:
    d = df if name is None else df[df[M].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axvline(MARKER, color=REF, linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    many = len(series) > 1  # several metrics: a dash and a marker shape each, as in the app
    ax.plot(d[T], d[V], color=col, linewidth=2, linestyle=SERIES_DASHES[i % 8] if many else "-", label=name or V)
    at = float(np.interp(MARKER, d[T], d[V]))  # value at the chosen threshold
    ax.scatter([MARKER], [at], color=col, marker=SERIES_MARKERS[i % 8] if many else "o", zorder=3)
    ax.annotate(f"{at:.2f}", (MARKER, at), xytext=(5, 2), textcoords="offset points", fontsize=8, color=col)
ax.set_xlabel(T)
ax.set_ylabel(V)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads threshold-metrics-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#pred-actual

Predicted vs actual

How close are a regression model's predictions to the true values, and where does it miss?

Demo data · seed 20261101 · 420 rows · default settings · 640 × 360

How to read it

  1. Read each point as one row's prediction and true value.
  2. Points on the diagonal: right on target.
  3. Look for bends and funnels: bias at high values or errors that grow.
  1. Callout 1: Diagonal: perfect prediction.
  2. Callout 2: Low values above the line: under-predicted.
  3. Callout 3: Colour: validation or test rows.

Watch out

  • Only held-out rows tell you how the model will do on new data.

Defaults

Identity line (equal axes)
On
Draw y = x with equal axes, so distance from the line is the error.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Prediction on x and actual on y (scikit-learn's PredictionErrorDisplay); points above the line are under-predicted.
  • With the identity line on, both axes share one range so the 45° line means equality.
  • Validation points are out-of-fold predictions; test points come from the final model, scored once.
# Predicted vs actual — Codesplash Chart Lab (recipe "pred-actual")
# controls: identity=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("pred-actual-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["split"] = pd.Categorical(df["split"].astype("string"), categories=["validation", "test"])

_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)))
ACT = "sale price (k€)"
PRED = "predicted price (k€)"
SET = "split"
IDENTITY = True
d = df.dropna(subset=[ACT, PRED])
sets = levels_of(d[SET]) if SET else [None]
fig, ax = plt.subplots(figsize=(6, 6))
for i, s in enumerate(sets):
    g = d if s is None else d[d[SET].astype(str) == str(s)]
    ax.scatter(g[PRED], g[ACT], s=12, alpha=0.6, color=PALETTE[i % len(PALETTE)], label=str(s) if s is not None else None)
lo, hi = float(min(d[ACT].min(), d[PRED].min())), float(max(d[ACT].max(), d[PRED].max()))
if IDENTITY:
    ax.plot([lo, hi], [lo, hi], color=REF, linestyle="--", linewidth=1, label="perfect prediction (y = x)")
ax.set_xlabel(PRED)
ax.set_ylabel(ACT)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads pred-actual-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#importance-bar

Feature importance

Which features does the model rely on most?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Read bar length as how much the model relies on that feature.
  2. Check the whiskers: overlapping features may not really differ.
  3. Check which kind of importance is on the axis.
  1. Callout 1: The top feature.
  2. Callout 2: Whisker: how much it varies across repeats.
  3. Callout 3: Near zero: the model barely uses these.

Watch out

  • Importance doesn't mean causal, and correlated features share or swap importance.

Defaults

Features shown
20
How many features to show, largest first.
Range 3 to 60, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Ranked by |importance|; negative permutation importance (the model did better with the feature shuffled) is drawn left of zero in a second colour.
  • Importance kinds are not comparable across methods: gain counts splits, permutation measures the metric drop, SHAP the mean absolute contribution — the axis label names the kind.
  • Correlated features share importance; a low value does not mean the feature carries no information.
# Feature importance — Codesplash Chart Lab (recipe "importance-bar")
# controls: top=20
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("importance-bar-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["tenure (months)", "monthly charges", "contract=month-to-month", "support calls", "total charges", "payment=electronic check", "age", "internet=fiber", "streaming TV", "paperless billing", "dependents", "region=north"])

FEAT = "feature"
IMP = "drop in ROC AUC"
LO = "lower"
HI = "upper"
TOP = 20
d = df.dropna(subset=[FEAT, IMP]).sort_values(IMP, ascending=False).head(TOP).iloc[::-1]  # largest at the top
fig, ax = plt.subplots(figsize=(8, 0.32 * len(d) + 1.2))
err = [d[IMP] - d[LO], d[HI] - d[IMP]] if LO and HI else None
ax.barh(d[FEAT].astype(str), d[IMP], xerr=err, color=PALETTE[0], ecolor="grey", capsize=2)
ax.axvline(0, color="grey", linewidth=0.8)
ax.set_xlabel(IMP)
plt.show()

Needs pandas, numpy, matplotlib · reads importance-bar-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#shap-beeswarm

SHAP beeswarm

How does each feature push individual predictions up or down, and for which values?

Demo data · seed 20261101 · 1,560 rows · default settings · 640 × 360

How to read it

  1. Read each row as a feature, ranked by average impact.
  2. Read a dot's position: to the right pushes the prediction up.
  3. Read colour as the feature's value: red right and blue left means high values raise predictions.
  1. Callout 1: Top row: the feature with the largest average impact.
  2. Callout 2: Red on the right: high values push predictions up.
  3. Callout 3: Colour scale: the feature's value.

Watch out

  • SHAP explains the model, not the world: it says what the model does, not what would happen if you changed the feature.

Defaults

Features shown
20
How many features to show, largest first.
Range 3 to 40, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Features are ordered by mean |SHAP| (global importance); within a feature, dots stack outward from the centre line in bins of one dot width so dense regions show their mass.
  • Colour is the feature value scaled to [0, 1] by the engine (blue = low, red = high, as in the shap library); missing values are grey. Categorical features arrive one-hot, so 1 = that category.
  • SHAP values explain the model's output scale (log-odds for boosted classifiers unless the run says probability).
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")
# controls: top=20
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("shap-beeswarm-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure"])

_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")
FEAT = "feature"
SHAP = "SHAP value (log-odds)"
V = "feature value (rank-scaled)"
TOP = 20
d = df.dropna(subset=[FEAT, SHAP]).copy()
d[FEAT] = d[FEAT].astype(str)
order = d.assign(a=d[SHAP].abs()).groupby(FEAT)["a"].mean().sort_values(ascending=False).head(TOP).index.tolist()  # by mean |SHAP|
ypos = {f: len(order) - 1 - i for i, f in enumerate(order)}
d = d[d[FEAT].isin(order)]
rng = np.random.default_rng(1)  # vertical jitter stands in for the beeswarm layout
y = d[FEAT].map(ypos) + rng.uniform(-0.32, 0.32, len(d))
cmap = LinearSegmentedColormap.from_list("shap", [DIV[-1], DIV[0]])  # low value blue → high red
fig, ax = plt.subplots(figsize=(8, 0.42 * len(order) + 1.4))
ax.axvline(0, color="grey", linewidth=0.8)
sc = ax.scatter(d[SHAP], y, c=d[V] if V else None, cmap=cmap, s=7, alpha=0.8)
ax.set_yticks([ypos[f] for f in order], order)
ax.set_xlabel(SHAP)
if V:
    fig.colorbar(sc, ax=ax, label=V)
plt.show()

Needs pandas, numpy, matplotlib · reads shap-beeswarm-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#shap-dependence

SHAP dependence

How does one feature's value change its contribution, and does another feature modify it?

Demo data · seed 20261101 · 400 rows · default settings · 640 × 360

How to read it

  1. Read the shape: how a feature's value changes its contribution.
  2. Read the vertical spread at one value: another feature is modifying it.
  3. Read the colour to see which one.
  1. Callout 1: Crossing zero: the feature's effect flips sign here.
  2. Callout 2: Rising with age.
  3. Callout 3: Colour scale: the interacting feature.

Watch out

  • Few rows at the extremes make those shapes unreliable.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • The engine picks the colour feature (the strongest SHAP interaction, as the shap library does) or the user does; numeric colours run on a sequential ramp, categories on the categorical palette.
  • Vertical spread at a fixed x is the effect of other features — colour separating that spread suggests an interaction.
# SHAP dependence — Codesplash Chart Lab (recipe "shap-dependence")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("shap-dependence-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")
V = "age (years)"
SHAP = "SHAP value (log-odds)"
COL = "BMI"
d = df.dropna(subset=[V, SHAP])
fig, ax = plt.subplots(figsize=(7, 4.8))
ax.axhline(0, color="grey", linewidth=0.8)
cmap = LinearSegmentedColormap.from_list("shap", [DIV[-1], DIV[0]])
sc = ax.scatter(d[V], d[SHAP], c=d[COL] if COL else PALETTE[0], cmap=cmap if COL else None, s=14, alpha=0.8)
if COL:
    fig.colorbar(sc, ax=ax, label=COL)
ax.set_xlabel(V)
ax.set_ylabel(SHAP)
plt.show()

Needs pandas, numpy, matplotlib · reads shap-dependence-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#shap-waterfall

SHAP waterfall

Why did the model make this particular prediction?

Demo data · seed 20261101 · 7 rows · default settings · 640 × 360

How to read it

  1. Start at the left marker: the average prediction.
  2. Each bar pushes the prediction up or down, largest first.
  3. End at the final value: this row's prediction.
  1. Callout 1: Baseline: the model's average output.
  2. Callout 2: This feature pushes the prediction up most.
  3. Callout 3: This row's prediction.

Watch out

  • It explains one row. Don't generalize one row's story to the whole model.

Defaults

Base value E[f(x)]
0
Where the waterfall starts: the model's average output.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Prediction f(x) (0 = base + Σ contributions)
0
Where the waterfall ends: the model's output for this row.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Steps keep the engine's order (usually |SHAP| descending with the remaining features summed into one row); the last bar ends at base + Σ contributions, which equals f(x) by SHAP's additivity.
  • The run supplies the base value (expected model output over the background data) and, optionally, the prediction for the label.
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")
# controls: base=0, prediction=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("shap-waterfall-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure", "4 other features"])

_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")
FEAT = "feature"
CON = "SHAP value (log-odds)"
V = "value"
BASE, PRED_SET = 0, 0  # E[f(x)]; f(x) when given (0 = base + Σ SHAP)
d = df.dropna(subset=[FEAT, CON]).reset_index(drop=True)
end = BASE + d[CON].cumsum()
start = end - d[CON]
pred = PRED_SET if PRED_SET != 0 else float(end.iloc[-1])
labels = [f"{f} = {v:g}" if isinstance(v, float) and pd.notna(v) else (f"{f} = {v}" if V and pd.notna(v) else str(f)) for f, v in zip(d[FEAT], d[V] if V else [None] * len(d))]
y = np.arange(len(d))[::-1]  # first feature at the top
fig, ax = plt.subplots(figsize=(8, 0.42 * len(d) + 1.6))
cols = [DIV[0] if v > 0 else DIV[-1] for v in d[CON]]  # raises the prediction: red; lowers it: blue
ax.barh(y, d[CON], left=start, color=cols, height=0.6)
for yi, s, e, v in zip(y, start, end, d[CON]):
    ax.annotate(f"{v:+.3g}", (max(s, e), yi), xytext=(4, 0), textcoords="offset points", va="center", fontsize=8)
ax.axvline(BASE, color="grey", linestyle="--", linewidth=1)
ax.axvline(pred, color=REF, linewidth=1.2)
ax.set_yticks(y, labels)
ax.margins(x=0.1)  # room for the value labels
ax.set_xlabel(f"E[f(x)] = {BASE:.3g},  f(x) = {pred:.3g}")
plt.show()

Needs pandas, numpy, matplotlib · reads shap-waterfall-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#pdp-ice

Partial dependence with ICE

How does the prediction change as one feature changes, on average and for individual rows?

Demo data · seed 20261101 · 1,281 rows · default settings · 640 × 360

How to read it

  1. Read the bold line as the average prediction at each feature value.
  2. Read the thin lines as individual rows.
  3. If thin lines cross or fan out, the effect differs across rows: look for an interaction.
  1. Callout 1: The bold line: the average effect.
  2. Callout 2: Thin lines: one row each.
  3. Callout 3: A jump in the average: a threshold in the model.

Watch out

  • With correlated features, PDP asks about impossible rows. Use ALE instead.

Defaults

Centre each line at its first value (c-ICE)
Off
Start every line at zero so differences in shape stand out from differences in level.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • The grid is the engine's (training quantiles of the feature); the PDP is the mean of the ICE curves over the explained rows.
  • Beyond 200 ICE lines the chart draws every k-th line (deterministic) and says so in the legend.
  • PDPs extrapolate into impossible combinations when features are correlated — prefer ALE then.
# Partial dependence with ICE — Codesplash Chart Lab (recipe "pdp-ice")
# controls: centered=false
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("pdp-ice-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["pdp", "ice"])

_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")
X = "BMI"
YH = "predicted probability"
LINE = "line"
KIND = "kind"
CENTERED = False  # c-ICE: each curve minus its value at the smallest x
d = df.dropna(subset=[X, YH, LINE]).sort_values(X)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("ice", index=d.index)
ice, pdp = d[kind == "ice"], d[kind == "pdp"]
if pdp.empty:  # no PDP rows: the PDP is the mean of the ICE curves
    pdp = ice.groupby(X, as_index=False)[YH].mean().assign(**{LINE: "PDP"})
def centre(frame):
    return frame.assign(_y=frame[YH] - frame.groupby(LINE, observed=True)[YH].transform("first")) if CENTERED else frame.assign(_y=frame[YH])
ice, pdp = centre(ice), centre(pdp)
fig, ax = plt.subplots(figsize=(8, 4.5))
for _, s in ice.groupby(LINE, observed=True):
    ax.plot(s[X], s["_y"], color=GREY, linewidth=0.6, alpha=0.7)
ax.plot(pdp[X], pdp["_y"], color=PALETTE[0], linewidth=2.8, label="partial dependence")
ax.set_xlabel(X)
ax.set_ylabel(("centred " if CENTERED else "") + YH)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads pdp-ice-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#ale-plot

Accumulated local effects

What is a feature's effect on predictions when features are correlated?

Demo data · seed 20261101 · 21 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the feature's effect, relative to the average prediction.
  2. Read its slope: how predictions change locally.
  3. Check the band for uncertainty, and the rug for where data exists.
  1. Callout 1: Crosses zero: predictions here equal the average.
  2. Callout 2: Higher values lift predictions.
  3. Callout 3: Low values lower them.

Watch out

  • ALE is about the model, not a causal effect.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • ALE averages prediction differences within each quantile interval (so it never evaluates impossible feature combinations) and centres the accumulated curve to mean zero over the data.
  • Intervals, when present, are the engine's (bootstrap over rows).
# Accumulated local effects — Codesplash Chart Lab (recipe "ale-plot")
# 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("ale-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

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 = "daylight (minutes)"
Y = "effect on daily rentals"
LO = "lower"
HI = "upper"
G = None
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0)
    ax.plot(d[X], d[Y], color=col, linewidth=2, label=name or Y)
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads ale-plot-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#learning-curve

Learning curve

Would more data help, or is the model limited by bias or variance?

Demo data · seed 20261101 · 14 rows · default settings · 640 × 360

How to read it

  1. Compare the training and validation lines as rows grow.
  2. A persistent gap suggests overfitting; more data may help.
  3. Both low and close together suggests a model too simple; more data won't help much.
  1. Callout 1: Training score.
  2. Callout 2: Validation score: rises with more rows.
  3. Callout 3: The gap at the end: what more data could still close.

Watch out

  • Splits vary: read the bands before concluding the curves have flattened.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Bands are the engine's (mean ± 1 SD across folds unless the run says otherwise); every size uses the same folds.
# Learning curve — Codesplash Chart Lab (recipe "learning-curve")
# 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("learning-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["set"] = pd.Categorical(df["set"].astype("string"), categories=["train", "validation"])

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 = "training rows"
Y = "accuracy"
LO = "lower"
HI = "upper"
G = "set"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0)
    ax.plot(d[X], d[Y], color=col, linewidth=2, label=name or Y)
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads learning-curve-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#trial-history

Tuning history

Is the hyperparameter search still improving, and which trials were pruned?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read each dot as a trial's score, in order.
  2. Read the step line as the best so far.
  3. If the best line is flat for many trials, the search has probably run its course.
  1. Callout 1: The running best.
  2. Callout 2: A completed trial.
  3. Callout 3: A pruned or failed trial.

Watch out

  • The best trial's score is optimistic: it was chosen for being highest. Test it on untouched data.

Defaults

Lower is better
Off
Say whether a lower score is better, for the running best line.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • The running best is the engine's when sent; otherwise the chart takes the best completed trial so far (pruned and failed trials never count).
  • Pruned trials stopped after their first folds (racing / median pruner), so their score covers fewer folds.
# Tuning history — Codesplash Chart Lab (recipe "trial-history")
# controls: minimize=false
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("trial-history-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["status"] = pd.Categorical(df["status"].astype("string"), categories=["complete", "pruned", "failed"])

_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")
TRIAL = "trial"
SCORE = "ROC AUC"
BEST = None
STATUS = "status"
MINIMIZE = False  # lower scores are better
d = df.dropna(subset=[TRIAL]).sort_values(TRIAL)
status = d[STATUS].astype(str).str.lower() if STATUS else pd.Series("complete", index=d.index)
done = d[status == "complete"]
best = d[BEST] if BEST else (done[SCORE].cummin() if MINIMIZE else done[SCORE].cummax()).reindex(d.index).ffill()  # running best
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.scatter(done[TRIAL], done[SCORE], s=22, color=PALETTE[0], label="complete")
pruned = d[status == "pruned"]
ax.scatter(pruned[TRIAL], pruned[SCORE], s=22, facecolors="none", edgecolors="grey", label="pruned")
failed = d[status == "failed"]
if len(failed):
    ax.scatter(failed[TRIAL], np.full(len(failed), np.nanmin(d[SCORE]) if len(done) else 0), marker="x", color="#ce5342", label="failed")
ax.step(d[TRIAL], best, where="post", color=REF, linewidth=1.6, label="best so far")
ax.set_xlabel(TRIAL)
ax.set_ylabel(SCORE)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads trial-history-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#split-strip

Validation fold strip

Which rows train, validate and test in each fold — and is anything leaking across time or groups?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Read each row as one fold of the plan, rows binned in order.
  2. Colours mark training, validation and test.
  3. Check for leaks: no validation or test bin should come before training in a time-ordered plan.
  1. Callout 1: The final fit.
  2. Callout 2: One fold's training rows.
  3. Callout 3: Test rows are held out of every fold.

Watch out

  • A plan that looks tidy can still leak through duplicates, groups or features computed on all rows.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Bins come from the host's split plan summary (cs-ml SplitSummary: about 120 bins over row order, or time order when the plan is time-based); each bin is stacked by the share of its rows in each set.
  • Time-series plans show validation always to the right of training; a gap appears as an empty band between them.
  • The right margin repeats each fold's row counts.
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("split-strip-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["fold"] = pd.Categorical(df["fold"].astype("string"), categories=["Final", "Fold 1", "Fold 2", "Fold 3", "Fold 4"])

_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)))
ROW = "fold"
BIN = "rows in time order (binned)"
TR = "train"
VA = "validation"
TE = "test"
EX = "excluded"
d = df.dropna(subset=[ROW, BIN])
rows = levels_of(d[ROW])
parts = [(TR, PALETTE[0], "train"), (VA, PALETTE[1], "validation"), (TE, PALETTE[2], "test")] + ([(EX, GREY, "excluded")] if EX else [])
fig, ax = plt.subplots(figsize=(9, 0.5 * len(rows) + 1.4))
for r, name in enumerate(rows):
    s = d[d[ROW].astype(str) == str(name)].sort_values(BIN)
    total = sum(s[c].fillna(0) for c, _, _ in parts).replace(0, np.nan)
    bottom = np.full(len(s), len(rows) - 1 - r - 0.4)
    for col, colour, label in parts:  # each bin's height is split by share
        h = (s[col].fillna(0) / total).fillna(0).to_numpy() * 0.8
        hatch = SERIES_HATCHES[1] if label == "test" else ""  # the held-out test set is hatched, as in the app
        ax.bar(s[BIN], h, bottom=bottom, width=1.0, color=colour, hatch=hatch, hatchcolor=HATCH_INK, linewidth=0, label=label if r == 0 else None)
        bottom = bottom + h
ax.set_yticks(range(len(rows))[::-1], rows)
ax.set_xlabel(BIN)
ax.legend(fontsize=8, ncol=len(parts), loc="upper center", bbox_to_anchor=(0.5, -0.18))
plt.show()

Needs pandas, numpy, matplotlib · reads split-strip-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#cd-diagram

Critical-difference diagram

Across folds, which models are reliably better than which?

Demo data · seed 20261101 · 5 rows · default settings · 640 × 360

How to read it

  1. Read the top axis as mean rank across folds: lower is better.
  2. A thick bar joins models the test could not separate.
  3. Compare distances with the critical difference at the top.
  1. Callout 1: The critical difference.
  2. Callout 2: A thick bar: these models can't be separated.
  3. Callout 3: A model and its mean rank.

Watch out

  • Folds aren't fully independent, so the test can be optimistic. Use repeated folds if it matters.

Defaults

Critical difference
1.93
Nemenyi critical difference of mean ranks (the comparison sets it); 0 hides the bars.
Range 0 to 20, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Ranks are per fold (1 = best model in that fold, ties averaged) and averaged across the folds every model shared.
  • Bars join maximal runs of models within the critical difference (Demšar's layout); nested runs are drawn once.
  • Folds share training rows, so the Friedman/Nemenyi tests are optimistic — read the diagram as an ordering, and use the paired corrected t for claims about one pair.
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")
# controls: cd=1.93
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("cd-diagram-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

L = "model"
R = "mean rank"
CD = 1.93  # critical difference
d = df[[L, R]].dropna().sort_values([R, L]).reset_index(drop=True)
ranks, names = d[R].to_numpy(float), d[L].astype(str).tolist()
cliques, last = [], -1  # Demšar: maximal runs of models within CD of each other
for i in range(len(ranks)):
    j = i
    while CD and j + 1 < len(ranks) and ranks[j + 1] - ranks[i] <= CD + 1e-12:
        j += 1
    if j > i and j > last:
        cliques.append((i, j))
        last = j
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(ranks, [0] * len(ranks), "o", color=PALETTE[0])
for k, (i, j) in enumerate(cliques):
    ax.plot([ranks[i], ranks[j]], [-0.12 - 0.06 * k] * 2, color="black", linewidth=3)
for i, (r, n) in enumerate(zip(ranks, names)):
    ax.annotate(f"{n} ({r:.2f})", (r, 0), xytext=(r, 0.15 + 0.1 * i), fontsize=8, ha="center", arrowprops=dict(arrowstyle="-", color="grey"))
ax.set_xlim(max(0.5, ranks.min() - 0.5), ranks.max() + 0.5)
ax.set_ylim(-0.3 - 0.06 * len(cliques), 0.3 + 0.1 * len(ranks))
ax.set_yticks([])
ax.set_xlabel("Mean rank across folds (1 = best)")
plt.show()

Needs pandas, numpy, matplotlib · reads cd-diagram-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#validation-curve

Validation curve

How does one hyperparameter trade underfitting for overfitting?

Demo data · seed 20261101 · 16 rows · default settings · 640 × 360

How to read it

  1. Compare training and validation scores across one hyperparameter.
  2. Where validation peaks: the best trade-off.
  3. Where the lines part: more complexity only fits noise.
  1. Callout 1: Validation peaks at this value.
  2. Callout 2: Training keeps climbing.
  3. Callout 3: Low values: both low, so the model is too simple.

Watch out

  • The peak was chosen on validation data, so its score is optimistic.

Defaults

Log scale
Off
Log x axis (automatic when the values span 100× or more).

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Every value is re-fit on the same folds; bands are mean ± 1 SD across folds. Training scores are each fold's model scored on its own training rows.
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")
# controls: logX=false
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("validation-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["set"] = pd.Categorical(df["set"].astype("string"), categories=["Training", "Validation"])

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 = "max depth"
S = "ROC AUC"
K = "set"
LO = "lower"
HI = "upper"
numeric = pd.api.types.is_numeric_dtype(df[X])
settings = levels_of(df[X]) if not numeric else None
fig, ax = plt.subplots(figsize=(7, 4.5))
for i, k in enumerate(levels_of(df[K])):
    g = df[df[K].astype(str) == str(k)].dropna(subset=[S]).copy()
    g["_x"] = g[X].astype(float) if numeric else g[X].astype(str).map({s: j for j, s in enumerate(settings)})
    g, col = g.sort_values("_x"), PALETTE[i % len(PALETTE)]
    ax.plot(g["_x"], g[S], marker="o", color=col, label=str(k))
    if LO and HI:
        ax.fill_between(g["_x"], g[LO], g[HI], color=col, alpha=0.18)

if not numeric:
    ax.set_xticks(range(len(settings)), settings)
ax.set_xlabel(X)
ax.set_ylabel(S)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads validation-curve-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#stacking-weights

Ensemble weights

How much does each member contribute to the ensemble?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each bar as the member's share of the ensemble.
  2. “Not used” members add nothing beyond the others.
  3. Don't read a weight as a member's quality: correlated members share weight.
  1. Callout 1: The largest share.
  2. Callout 2: Not used: nothing to add beyond the others.

Watch out

  • Weights shift with small data changes when members are similar.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Weights sum to one. Stacking weights are non-negative least-squares coefficients on out-of-fold predictions, normalized (SuperLearner's NNLS).
# Ensemble weights — Codesplash Chart Lab (recipe "stacking-weights")
# 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("stacking-weights-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

L = "member"
W = "weight"
d = df[[L, W]].dropna().sort_values([W, L], ascending=[True, False])  # largest on top
fig, ax = plt.subplots(figsize=(7, 0.5 * len(d) + 1.2))
ax.barh(d[L].astype(str), d[W], color=PALETTE[0])
for y, w in enumerate(d[W]):
    ax.text(w, y, f" {w:.1%}" if w > 0 else " not used", va="center", fontsize=8)
ax.xaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
ax.set_xlabel("Share of the ensemble")
plt.show()

Needs pandas, numpy, matplotlib · reads stacking-weights-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#brier-over-time

Brier score over time

Are a deployed model's probabilities still trustworthy?

Demo data · seed 20261101 · 20 rows · default settings · 640 × 360

How to read it

  1. Read the line as the Brier score per period: lower is better.
  2. Compare with the dashed level at deployment.
  3. A sustained rise means predicted probabilities are drifting away from reality.
  1. Callout 1: Rising above the deployment level.
  2. Callout 2: Dashed line: the level at deployment.

Watch out

  • The score depends on the event rate: a seasonal rate change can move it without any model decay.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Brier score = mean squared difference between the predicted probability of the positive class and the outcome (0/1); lower is better.
# Brier score over time — Codesplash Chart Lab (recipe "brier-over-time")
# 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("brier-over-time-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["week"] = pd.to_datetime(df["week"])

_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")
T = "week"
B = "Brier score"
BASE = "at deployment"
d = df.dropna(subset=[T, B]).sort_values(T)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(d[T], d[B], marker="o", markersize=3, color=PALETTE[0], label="Brier score")
if BASE and d[BASE].notna().any():
    ax.axhline(d[BASE].dropna().iloc[0], color=REF, linestyle="--", linewidth=1, label="at deployment")
ax.set_ylim(bottom=0)
ax.set_xlabel(T)
ax.set_ylabel("Brier score")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads brier-over-time-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#shap-force

SHAP force plot

Which features pushed this one prediction up, and which pulled it down?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Start at the base value: the model's average output.
  2. Follow the contributions pushing up from one side and down from the other.
  3. They meet at f(x): this row's prediction.

Watch out

  • It explains one prediction of the model, not what would happen if you changed the feature.

Defaults

Base value E[f(x)]
0
The model's average output over the background rows: where the explanation starts.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the explanation the Python or R engine computed; the chart computes nothing statistical.
  • The largest contribution sits next to f(x) on each side. f(x) = base + Σ contributions, by SHAP's additivity.
  • Red raises the prediction and blue lowers it, the usual SHAP convention.
# SHAP force plot — Codesplash Chart Lab (recipe "shap-force")
# controls: base=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("shap-force-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure"])

_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")
FEAT = "feature"
CON = "SHAP value (log-odds)"
BASE = 0  # E[f(x)]
d = df.dropna(subset=[FEAT, CON])
pred = BASE + d[CON].sum()  # f(x) = base + sum of SHAP
fig, ax = plt.subplots(figsize=(8, 2.4))
at = pred
for _, r in d[d[CON] > 0].sort_values(CON, ascending=False).iterrows():  # raises it: red, stacked up to f(x)
    ax.barh(0, r[CON], left=at - r[CON], height=0.5, color=DIV[0], edgecolor="white")
    ax.text(at - r[CON] / 2, 0, str(r[FEAT]), ha="center", va="center", fontsize=8, color="white", clip_on=True)
    at -= r[CON]
at = pred
for _, r in d[d[CON] < 0].sort_values(CON).iterrows():  # lowers it: blue, stacked down from f(x)
    ax.barh(0, -r[CON], left=at, height=0.5, color=DIV[-1], edgecolor="white")
    ax.text(at - r[CON] / 2, 0, str(r[FEAT]), ha="center", va="center", fontsize=8, color="white", clip_on=True)
    at -= r[CON]
ax.axvline(BASE, color="grey", linestyle="--", linewidth=1)
ax.axvline(pred, color=REF, linewidth=1.2)
ax.set_yticks([])
ax.set_xlabel(f"E[f(x)] = {BASE:.3g},  f(x) = {pred:.3g}")
plt.show()

Needs pandas, numpy, matplotlib · reads shap-force-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#surrogate-tree

Surrogate decision tree

Can a small, readable tree imitate what this complicated model does?

Demo data · seed 20261101 · 9 rows · default settings · 640 × 360

How to read it

  1. Read from the top: each split sends rows left or right.
  2. Read each leaf as the model's average prediction for the rows that reach it.
  3. Check how well the tree imitates the model before trusting its story.

Watch out

  • The tree explains an imitation of the model, not the model itself or the world. A low fidelity score makes it misleading.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the explanation the Python or R engine computed; the chart computes nothing statistical.
  • Nodes arrive depth-first with the left (yes) child first. Leaves are evenly spaced and each split is centred over its children.
  • The tree explains the model, not the world: read it together with its fidelity, the R² between the tree's and the model's predictions.
# Surrogate decision tree — Codesplash Chart Lab (recipe "surrogate-tree")
# 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("surrogate-tree-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")
NODE = "node"
PARENT = "parent"
LABEL = "split"
N = "rows"
VALUE = "P(diabetic)"
d = df.sort_values(NODE)
kids, order = {}, list(d[NODE])
for node, parent in zip(d[NODE], d[PARENT]):
    if parent >= 0:
        kids.setdefault(parent, []).append(node)
pos, depth, leaves = {}, {}, [0]
def place(n, level):  # leaves evenly spaced; a split centred over its children
    depth[n] = level
    if n not in kids:
        pos[n] = leaves[0]; leaves[0] += 1
    else:
        xs = [place(k, level + 1) for k in kids[n]]
        pos[n] = (xs[0] + xs[-1]) / 2
    return pos[n]
place(order[0], 0)
fig, ax = plt.subplots(figsize=(9, 4.5))
rows = d.set_index(NODE)
for parent, children in kids.items():
    for i, k in enumerate(children):
        ax.plot([pos[parent], pos[k]], [-depth[parent], -depth[k]], color="grey", linewidth=0.8, zorder=1)
        ax.text((pos[parent] + pos[k]) / 2, -(depth[parent] + depth[k]) / 2, "yes" if i == 0 else "no", fontsize=7, color="grey", ha="center")
for n in order:
    leaf = n not in kids
    text = f"{rows.loc[n, VALUE]:.3g}\nn = {rows.loc[n, N]:.0f}" if leaf else f"{rows.loc[n, LABEL]}\nn = {rows.loc[n, N]:.0f}"
    ax.text(pos[n], -depth[n], text, ha="center", va="center", fontsize=8, bbox=dict(boxstyle="round", facecolor="white", edgecolor="grey"), zorder=2)
ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads surrogate-tree-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#h-statistic

Friedman's H interactions

Which features does the model combine, rather than use one at a time?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read each cell as how much of a pair's joint effect is interaction: 0 means the pair adds up.
  2. Read the outlined diagonal as each feature against all the others.
  3. Look at the partial dependence of any high pair to see what the interaction does.

Watch out

  • H is noisy with few rows and can be large for pairs whose total effect is tiny, so check their importance too.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the explanation the Python or R engine computed; the chart computes nothing statistical.
  • H is the square root of H², the share of the joint partial dependence's variance that the separate effects do not explain.
  • The colour scale runs from 0 to the largest H in the chart; a large H can still describe a small effect, so read it next to the partial dependence.
# Friedman's H interactions — Codesplash Chart Lab (recipe "h-statistic")
# 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("h-statistic-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])
df["with"] = pd.Categorical(df["with"].astype("string"), categories=["glucose", "BMI", "age", "pedigree"])

_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")
A = "feature"
B = "with"
H = "H"
feats = list(dict.fromkeys(list(df[A].astype(str)) + list(df[B].astype(str))))
m = pd.DataFrame(np.nan, index=feats, columns=feats)
for a, b, h in zip(df[A].astype(str), df[B].astype(str), df[H]):
    m.loc[a, b] = h; m.loc[b, a] = h  # the diagonal: each feature against all the others
fig, ax = plt.subplots(figsize=(5.5, 5))
im = ax.imshow(m.to_numpy(dtype=float), cmap="Blues", vmin=0)
ax.set_xticks(range(len(feats)), feats, rotation=45, ha="right")
ax.set_yticks(range(len(feats)), feats)
for i in range(len(feats)):
    for j in range(len(feats)):
        if pd.notna(m.iat[i, j]):
            ax.text(j, i, f"{m.iat[i, j]:.2f}", ha="center", va="center", fontsize=8)
fig.colorbar(im, label="Friedman's H")
plt.show()

Needs pandas, numpy, matplotlib · reads h-statistic-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#td-auc-curve

Time-dependent AUC

How well does a survival model rank who has the event by each time?

Demo data · seed 20261101 · 9 rows · default settings · 640 × 360

How to read it

  1. Read each point as one follow-up time: the chance that someone with the event by then was scored above someone still event-free.
  2. Compare with the dashed line at 0.5, where the score ranks no better than a coin flip.
  3. Follow the line across time: a falling line means the model ranks early events better than late ones.
  1. Callout 1: Early follow-up: how well the score ranks the first events.
  2. Callout 2: Dashed line: no skill.
  3. Callout 3: The plain mean over the times shown.

Watch out

  • Late times rest on few rows still under follow-up, so the right end of the line is the noisiest part.
  • A high AUC says the ranking is good, not that the predicted probabilities are right. Read the Brier curve for those.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Cases are events up to t, weighted by the inverse probability of remaining uncensored (a reverse Kaplan–Meier of the scored rows); controls are rows still at risk after t. Ties in risk count ½. The dashed line at 0.5 is a model with no skill.
# Time-dependent AUC — Codesplash Chart Lab (recipe "td-auc-curve")
# 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("td-auc-curve-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")
T = "Days since diagnosis"
A = "Time-dependent AUC"
d = df.dropna(subset=[T, A]).sort_values(T)
fig, ax = plt.subplots(figsize=(7, 4))
ax.axhline(0.5, color=REF, linestyle="--", linewidth=1, label="no skill")
ax.plot(d[T], d[A], marker="o", markersize=3, color=PALETTE[0], label=f"mean AUC {d[A].mean():.3f}")
ax.set_ylim(min(0.4, d[A].min()), 1)
ax.set_xlabel(T)
ax.set_ylabel(A)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads td-auc-curve-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#surv-brier-curve

Survival Brier score

How far are predicted survival probabilities from what happened, at each time?

Demo data · seed 20261101 · 9 rows · default settings · 640 × 360

How to read it

  1. Read each point as the squared error of the predicted survival probability at that time; lower is better.
  2. Compare with the dashed line at 0.25: the score of a forecast that always says 50%.
  3. Read the number at the top left, the integrated Brier score: the average of this curve across the times shown.
  1. Callout 1: Early on few events have happened, so errors are small for any model.
  2. Callout 2: Reference: a 50/50 forecast.
  3. Callout 3: Integrated Brier score.

Watch out

  • The curve tends to rise with time for any model as outcomes become less certain. Compare models at the same times, not early against late.
  • A low Brier score at a time when nearly everyone is alive can be earned by predicting survival for all.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Rows with an event by t count (S(t))² over the chance of remaining uncensored until their event; rows still at risk count (1 − S(t))² over the same chance at t. The integrated score is the trapezoid mean over the times shown.
# Survival Brier score — Codesplash Chart Lab (recipe "surv-brier-curve")
# 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("surv-brier-curve-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 trapezoid_mean(t, v):
    """The integrated Brier score: trapezoid area over the span of the times."""
    t, v = np.asarray(t, float), np.asarray(v, float)
    return float(np.sum(np.diff(t) * (v[1:] + v[:-1]) / 2) / (t[-1] - t[0])) if len(t) > 1 else float(v[0])
T = "Days since diagnosis"
B = "Brier score"
d = df.dropna(subset=[T, B]).sort_values(T)
fig, ax = plt.subplots(figsize=(7, 4))
ax.axhline(0.25, color=REF, linestyle="--", linewidth=1, label="0.25: a 50/50 forecast")
ax.plot(d[T], d[B], marker="o", markersize=3, color=PALETTE[0], label=f"integrated {trapezoid_mean(d[T], d[B]):.3f}")
ax.set_ylim(0, max(0.3, d[B].max()))
ax.set_xlabel(T)
ax.set_ylabel(B)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads surv-brier-curve-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#risk-group-km

Survival by risk group

Do people the model calls riskier actually have the event sooner?

Demo data · seed 20261101 · 48 rows · default settings · 640 × 360

How to read it

  1. Read each line as the share of one predicted-risk group still event-free over time.
  2. Check the order: the low-risk line should stay on top and the high-risk line at the bottom.
  3. Read the gap between lines: wider means the score separates people more, and crossing lines mean it stops doing so.
  1. Callout 1: The group the model scored as lowest risk.
  2. Callout 2: The group it scored as highest risk.
  3. Callout 3: Each group's label gives its size.

Watch out

  • Equal-sized groups are a display choice. Separation between thirds doesn't mean there are three natural kinds of patient.
  • These are observed curves on held-out rows, so they show how well the model ranks, not that its probabilities are calibrated.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Rows are sorted by predicted risk and cut into equal-sized groups; each curve is a plain Kaplan–Meier estimate of that group's observed times. Survival starts at 100% at time 0.
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("risk-group-km-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Risk group"] = pd.Categorical(df["Risk group"].astype("string"), categories=["Low risk (n = 76)", "Middle risk (n = 76)", "High risk (n = 76)"])

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)))
T = "Days"
S = "Survival"
G = "Risk group"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
end = float(df[T].max())
fig, ax = plt.subplots(figsize=(7, 4.5))
for i, (name, d) in enumerate(series):
    d = d.dropna(subset=[T, S]).sort_values(T)
    # Every curve starts at survival 1 at time 0 and holds its last value to the end.
    x = np.concatenate([[0.0], d[T], [end]])
    y = np.concatenate([[1.0], d[S], [d[S].iloc[-1] if len(d) else 1.0]])
    ax.step(x, y, where="post", color=PALETTE[i % len(PALETTE)], linewidth=1.8, linestyle=SERIES_DASHES[i % 8], label=name or S)  # dash per group, as in the app
ax.set_xlim(0, end)
ax.set_ylim(0, 1)
ax.yaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
ax.set_xlabel(T)
ax.set_ylabel(S)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads risk-group-km-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#gam-partial

GAM partial effects

What does each feature add to an additive model's prediction?

Demo data · seed 20261101 · 93 rows · default settings · 640 × 360

How to read it

  1. Read each panel as one feature: how far it moves the prediction above or below average as its value changes.
  2. Check the shaded band, about two standard errors: where it covers the dashed zero line, the data can't tell the effect from none.
  3. Compare heights across panels. They share one y axis, so a taller curve is a larger effect.
  1. Callout 1: A steep stretch: the feature matters most here.
  2. Callout 2: Dashed line: the average prediction.
  3. Callout 3: The band widens at the edges, where there are fewer rows.

Watch out

  • Effects are on the model's link scale: log-odds or log for binary, Poisson, Gamma and Tweedie models, not the original units.
  • A partial effect describes this model holding the others fixed. With correlated features it isn't a causal effect.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Effects are centred on the training rows, on the link scale (response, log-odds or log). The band is ±2 standard errors of the smooth from the penalized fit's covariance. All panels share one y axis, so curve heights compare directly.
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")
# 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("gam-partial-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Feature"] = pd.Categorical(df["Feature"].astype("string"), categories=["Temperature", "Wind", "Solar radiation"])

_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)))
F = "Feature"
X = "Value"
E = "Effect"
L = "Lower"
U = "Upper"
groups = levels_of(df[F]) if F else [None]
series = []
for name in groups:
    d = df if name is None else df[df[F].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
n = len(series)
cols = min(n, 3)
rows = int(np.ceil(n / cols))
fig, axes = plt.subplots(rows, cols, figsize=(3.4 * cols, 2.6 * rows), sharey=True, squeeze=False)
for ax in axes.flat[n:]:
    ax.set_visible(False)
for ax, (name, d) in zip(axes.flat, series):
    d = d.dropna(subset=[X, E]).sort_values(X)
    ax.axhline(0, color=REF, linestyle="--", linewidth=1)
    if L and U:
        ax.fill_between(d[X], d[L], d[U], color=PALETTE[0], alpha=0.16, linewidth=0)
    ax.plot(d[X], d[E], color=PALETTE[0], linewidth=2)
    ax.set_title(name, fontsize=10, loc="left")
for ax in axes[:, 0]:
    ax.set_ylabel(E)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads gam-partial-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#training-curves

Training curves

Is the network still learning, and when did it start to overfit?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read each solid line as one network's training loss, epoch by epoch (or NGBoost's training score, round by round).
  2. Read the dashed line in the same colour as its loss on the held-back validation rows.
  3. Find the ring: the epoch with the lowest validation loss, whose weights early stopping keeps.
  1. Callout 1: Steep early fall: the network is learning the main pattern.
  2. Callout 2: Ring: the kept epoch.
  3. Callout 3: Dashed line rising while the solid one falls: overfitting.

Watch out

  • Training loss is measured with dropout on and validation loss with it off, so a validation curve below the training curve is not a bug.
  • A smooth fall on training rows says nothing about new data; read the run's cross-validated metrics.

Defaults

Loss axis
Linear
A log axis spreads out the late epochs, where losses change little.
Also: Log
Validation loss
On
Show the dashed validation curves and the kept epoch.

Pinned in the code

  • Draws the numbers the learner published (training history, member predictions, predicted densities); the chart computes nothing statistical.
  • Training loss is the mean over the epoch's mini-batches (with dropout on); validation loss is computed once per epoch on the held-out slice with dropout off, so the two are not on quite the same footing.
  • The ring marks the lowest validation loss — the weights early stopping keeps.
# Training curves — Codesplash Chart Lab (recipe "training-curves")
# controls: scale=linear, valid=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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("training-curves-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["network"] = pd.Categorical(df["network"].astype("string"), categories=["member 1", "member 2", "member 3"])

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 = "epoch"
Y = "training log loss"
S = "network"
V = "validation log loss"
SHOW_VALID = True
series = levels_of(df[S]) if S else [None]
fig, ax = plt.subplots(figsize=(7, 4.2))
for i, s in enumerate(series):
    d = (df[df[S].astype(str) == s] if S else df).sort_values(X)
    colour = PALETTE[i % len(PALETTE)]
    many = len(series) > 1  # members share solid/dashed for train/validation, so a marker shape names each (as in the app)
    every = max(1, round(len(d) / 8))
    ax.plot(d[X], d[Y], color=colour, linewidth=1.6, marker=SERIES_MARKERS[i % 8] if many else None, markevery=((i * every) // len(series), every), markersize=4, label=s if s is not None else Y)
    if V and SHOW_VALID:
        dv = d.dropna(subset=[V])
        if len(dv):
            ax.plot(dv[X], dv[V], color=colour, linewidth=1.2, linestyle="--")
            best = dv.loc[dv[V].idxmin()]  # the epoch early stopping keeps
            ax.plot([best[X]], [best[V]], SERIES_MARKERS[i % 8] if many else "o", markerfacecolor="white", markeredgecolor=colour, markersize=6)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Training curves (dashed: validation)")
ax.legend(frameon=False, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads training-curves-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#ensemble-spread

Ensemble spread

Where do the members of an ensemble disagree, and does the band hold the actual values?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Read the x axis as rows ordered by the ensemble's prediction, lowest on the left.
  2. Read the grey dots at one position as the members' predictions for that row; a tall column means they disagree.
  3. Compare the ticks (actual values) with the shaded band: the legend says what share of them it holds.
  1. Callout 1: Members agree: the dots sit on the line.
  2. Callout 2: Members spread out: the model is unsure here.
  3. Callout 3: Shaded band around the consensus line.

Watch out

  • These are training rows, so the band looks better here than on new data; judge coverage from the held-out 90% coverage metric.
  • TabM's members share most weights, so their spread understates uncertainty; read it as disagreement, not as an interval.

Defaults

Member dots
On
Show each member's prediction as a dot.

Pinned in the code

  • Draws the numbers the learner published (training history, member predictions, predicted densities); the chart computes nothing statistical.
  • The band is whatever the learner published: a deep ensemble's mixture interval (mean ± 1.645 SD, 90% if Normal) or the members' lowest-to-highest range for TabM.
  • Rows are training rows, evenly spaced in the order of the ensemble's prediction; read held-out coverage from the run's metrics, not from this picture.
# Ensemble spread — Codesplash Chart Lab (recipe "ensemble-spread")
# controls: members=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("ensemble-spread-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["member"] = pd.Categorical(df["member"].astype("string"), categories=["member 1", "member 2", "member 3", "member 4", "member 5"])

_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")
X = "row (ordered by prediction)"
Y = "member prediction"
C = "ensemble"
LO = "90% low"
HI = "90% high"
A = "actual"
SHOW_MEMBERS = True
rows = df.drop_duplicates(subset=[X]).sort_values(X)  # one row per position: consensus, band, actual
fig, ax = plt.subplots(figsize=(7, 4.2))
if LO and HI:
    ax.fill_between(rows[X], rows[LO], rows[HI], color=PALETTE[0], alpha=0.18, linewidth=0, label="band")
if SHOW_MEMBERS:
    ax.scatter(df[X], df[Y], s=6, color=GREY, alpha=0.9, label="members")
ax.plot(rows[X], rows[C], color=PALETTE[0], linewidth=1.6, label=C)
if A:
    ax.scatter(rows[X], rows[A], marker="_", s=70, color=REF, linewidths=1.5, label=A)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(frameon=False, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads ensemble-spread-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#predicted-distributions

Predicted distributions

What does a probabilistic model predict for individual rows, and how likely was what actually happened?

Demo data · seed 20261101 · 405 rows · default settings · 640 × 360

How to read it

  1. Read each curve as the full distribution the model predicts for one row; its peak is the most likely value.
  2. Read a curve's width as the model's uncertainty for that row: narrow is confident.
  3. Follow the dashed line up from the actual value: its height is the likelihood the model gave to what happened.
  1. Callout 1: A narrow, tall curve: a confident prediction.
  2. Callout 2: A wide, low curve: an uncertain one.
  3. Callout 3: Dashed line: the density at the actual value.

Watch out

  • Five rows are an illustration, not evidence; check 90% coverage and the NLL or CRPS across held-out rows.
  • The chosen distribution shapes every curve. A Normal can put weight on impossible negative values.

Defaults

Counts (stems)
Off
Draw probability masses as stems, for a count distribution such as the Poisson.

Pinned in the code

  • Draws the numbers the learner published (training history, member predictions, predicted densities); the chart computes nothing statistical.
  • Curves are evaluated by the learner on a grid of target values (81 points spanning ±3.5 SD of the shown rows, or every count for the Poisson).
  • A tall curve is a confident prediction; the dashed line's height is the likelihood of the actual value — the quantity the log score rewards.
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")
# controls: discrete=false
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("predicted-distributions-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["row 12 (actual 25.1)", "row 47 (actual 19.3)", "row 3 (actual 50.6)", "row 88 (actual 88.2)", "row 61 (actual 72.8)"])

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 = "ozone (ppb)"
D = "density"
S = "row"
A = "actual"
DISCRETE = False
series = levels_of(df[S])
fig, ax = plt.subplots(figsize=(7, 4.2))
for i, s in enumerate(series):
    d = df[df[S].astype(str) == s].sort_values(X)
    colour = PALETTE[i % len(PALETTE)]
    if DISCRETE:
        off = (i - (len(series) - 1) / 2) * 0.14  # side by side at each count
        ax.vlines(d[X] + off, 0, d[D], color=colour, linewidth=1.2)
        ax.plot(d[X] + off, d[D], SERIES_MARKERS[i % 8], color=colour, markersize=3, label=s)  # marker shape per row, as in the app
    else:
        ax.fill_between(d[X], 0, d[D], color=colour, alpha=0.08, linewidth=0)
        ax.plot(d[X], d[D], color=colour, linewidth=1.6, linestyle=SERIES_DASHES[i % 8], label=s)  # dash per row, as in the app
    if A and d[A].notna().any():
        a = float(d[A].dropna().iloc[0])
        top = float(np.interp(a, d[X], d[D])) if not DISCRETE else float(d[D].max()) * 0.08
        ax.vlines(a, 0, top, color=colour, linestyle="--", linewidth=1.1)  # height = likelihood of the actual
        if not DISCRETE:
            ax.plot([a], [top], SERIES_MARKERS[i % 8], markerfacecolor="white", markeredgecolor=colour, markersize=6)  # the row's marker at the actual
ax.set_ylim(bottom=0)
ax.set_xlabel(X)
ax.set_ylabel(D)
ax.legend(frameon=False, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads predicted-distributions-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#training-components

Training loss and its parts

Is the network still learning, and which part of its loss moves?

Demo data · seed 20261101 · 360 rows · default settings · 640 × 360

How to read it

  1. Read each line as one part of the network's loss, averaged over an epoch's rows.
  2. Falling lines that level off mean training has settled; a line still falling at the right edge means more epochs could help.
  3. For a VAE, watch the KL line: near zero means the latent space carries no information. For a GAN, watch the Wasserstein estimate fall and flatten.
  1. Callout 1: Early epochs: the loss drops fast.
  2. Callout 2: Late epochs: the lines level off.
  3. Callout 3: A smaller part, such as the KL term.

Watch out

  • A low training loss doesn't mean good output: judge generators by the synthetic-data scorecard and maps by trustworthiness.
  • GAN losses aren't comparable across runs or with other models; only the trend within one run means anything.

Defaults

Y axis
Linear
A log axis spreads out small late changes; it falls back to linear when any value is zero or negative.
Also: Log
Smoothing
None
Centered moving average over this many epochs; GAN losses are noisy, so smoothing shows the trend.
Also: 5 epochs · 11 epochs · 21 epochs

Pinned in the code

  • Draws the engine's numbers as given (codesplash ↔ codesplashr torch twins); the chart computes nothing statistical.
  • Each value is the row-weighted mean over the epoch's batches (the GAN's critic values average its critic steps).
  • Smoothing is a centered moving average that shrinks at the ends; the table shows the unsmoothed values.
# Training loss and its parts — Codesplash Chart Lab (recipe "training-components")
# controls: scale=linear, smooth=1
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("training-components-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["total", "reconstruction", "KL"])

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 = "epoch"
V = "loss per row"
C = "part"
SMOOTH, LOG = 1, False  # centered moving average (1 = none); log y axis
d = df.dropna(subset=[X, V])
fig, ax = plt.subplots(figsize=(8, 4))
parts = levels_of(d[C])
many = len(parts) > 1  # several components: a dash each (and a marker shape when the points are few), as in the app
for i, name in enumerate(parts):
    s = d[d[C].astype(str) == name].sort_values(X)
    y = s[V].rolling(SMOOTH, center=True, min_periods=1).mean() if SMOOTH > 1 else s[V]
    ax.plot(s[X], y, label=name, linewidth=1.6, linestyle=SERIES_DASHES[i % 8] if many else "-",
            marker=(SERIES_MARKERS[i % 8] if many else "o") if len(s) <= 60 else None, markersize=3)
if LOG and (d[V] > 0).all():
    ax.set_yscale("log")
elif d[V].min() < 0 < d[V].max():
    ax.axhline(0, color="grey", linestyle=":", linewidth=1)
ax.set_xlabel(X)
ax.set_ylabel(V)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads training-components-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#embedding-map

Category embedding map

Which levels of a categorical variable does the model treat as alike?

Demo data · seed 20261101 · 11 rows · default settings · 640 × 360

How to read it

  1. Read each dot as one level of a categorical feature, placed by the vector the network learned for it.
  2. Levels close together act alike on the target; a level far from the rest gets treated differently.
  3. Compare levels within one colour (one feature): distances between features' levels are not comparable.
  1. Callout 1: Two levels the model treats alike: close together.
  2. Callout 2: A level set apart from the rest.
  3. Callout 3: The dashed zero lines: the centre of each feature's levels.

Watch out

  • The axes have no meaning: any rotation of an embedding fits equally well, so read distances and neighbours only.
  • A small dot (a rare level) keeps a vector near its random start; its position says little.
  • Two principal components show only part of the distances when the vectors have more dimensions; check the nearest-level table.

Defaults

Label levels
On
Names next to the dots; labels that would overlap are left out (hover shows every level).
Equal axis units
On
One unit has the same length on both axes, so distances on the map are comparable in every direction.

Pinned in the code

  • Draws the coordinates the Python or R engine computed; the chart computes nothing statistical.
  • Coordinates are each feature's level vectors projected on their first two principal components (centred; each component's sign fixed so its largest loading is positive). Two components show only part of the distances when vectors have more dimensions.
  • Read distances and neighbours, not axes: any rotation of an embedding fits the data equally well.
  • Dot area grows with the level's row count (√ scaling, 3–9 px); rare levels keep vectors near their random start, so their positions mean little.
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")
# controls: labels=true, equal=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("embedding-map-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["feature"] = pd.Categorical(df["feature"].astype("string"), categories=["weekday", "store type"])

_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 dot_px(sizes):
    """Dot radius as in the app: 3 + 6·√(rows / max rows) px, 4 px without rows."""
    s = np.asarray(sizes, dtype=float)
    top = np.nanmax(s) if np.isfinite(s).any() and np.nanmax(s) > 0 else 0
    return np.where(np.isfinite(s) & (s > 0) & (top > 0), 3 + 6 * np.sqrt(np.clip(s, 0, None) / (top or 1)), 4.0)
X = "PC 1"
Y = "PC 2"
LABEL = "level"
G = "feature"
SIZE = "rows"
LABELS, EQUAL = True, True
d = df.dropna(subset=[X, Y]).reset_index(drop=True)
groups = levels_of(d[G]) if G else [None]
r = dot_px(d[SIZE] if SIZE else np.full(len(d), np.nan))
fig, ax = plt.subplots(figsize=(7, 6))
ax.axhline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
ax.axvline(0, color=REF, alpha=0.35, linestyle="--", linewidth=0.8)
for i, k in enumerate(groups):
    m = (d[G].astype(str) == str(k)).to_numpy() if G else np.ones(len(d), bool)
    ax.scatter(d.loc[m, X], d.loc[m, Y], s=(r[m] * 1.4) ** 2, color=PALETTE[i % len(PALETTE)], alpha=0.72, edgecolors="white", linewidths=0.8, label=k)
if LABELS and LABEL:
    for _, row in d.iterrows():  # every level is labelled; the app skips labels that would overlap
        ax.annotate(str(row[LABEL]), (row[X], row[Y]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
if EQUAL:
    ax.set_aspect("equal", adjustable="datalim")  # equal units: distances read the same both ways
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(title=G, fontsize=8)
ax.set_title("Learned category embeddings: close levels act alike on the target")
plt.show()

Needs pandas, numpy, matplotlib · reads embedding-map-demo.csv · app theme from the optional codesplash helper

  • Every level is labelled here; the app leaves out labels that would overlap (hover shows them all).

Machine learning

svg#cnn-filters

CNN filters (first-layer kernels)

What local patterns did the first layer of a convolutional network learn to look for?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Read each small square as one kernel the first layer learned; the network slides it over every position of the image.
  2. Read the two ends of the colour scale as weights of opposite sign: a kernel lights up where the image looks like its positive cells and not its negative ones.
  3. Look for structure: a band of one sign beside a band of the other is an edge detector, a single strong centre is a spot detector, an even patch is a blur.
  1. Callout 1: One kernel: k × k weights.
  2. Callout 2: Opposite signs side by side: an edge detector.
  3. Callout 3: Colour scale centred on 0.

Watch out

  • Kernels act on scaled pixels after training from random weights; a noisy-looking kernel can still be useful in combination with the others.
  • With each filter on its own scale, a nearly-zero kernel looks as strong as a real one; switch to the shared scale to compare them.

Defaults

Colour scale
Shared by all filters
Shared: one scale, so a pale filter really has small weights. Each: every filter uses its full range, to see weak patterns.
Also: Each filter's own
Weights in cells
On
Prints each weight in its cell when the cells are large enough (about 22 px).

Pinned in the code

  • Draws the numbers the network published (kernel weights, activations, out-of-fold counts); the chart computes nothing statistical.
  • Rows and columns are the kernel's positions as torch stores them (row 1 at the top); the weights act on the image after it is divided by its largest training pixel.
  • The diverging scale is centred on 0; with a shared scale its ends are ± the largest absolute weight of any filter.
# CNN filters (first-layer kernels) — Codesplash Chart Lab (recipe "cnn-filters")
# controls: scale=shared, values=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("cnn-filters-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["panel"] = pd.Categorical(df["panel"].astype("string"), categories=["filter 1", "filter 2", "filter 3", "filter 4", "filter 5", "filter 6", "filter 7", "filter 8"])

_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)))
PANEL = "panel"
ROW = "row"
COL = "col"
VALUE = "weight"
SHARED, VALUES = True, True  # one colour scale for all panels; print values in small grids
panels = levels_of(df[PANEL])
grids = {}
for name in panels:  # rows and columns count from 1, row 1 at the top
    d = df[df[PANEL].astype(str) == str(name)]
    g = np.full((int(d[ROW].max()), int(d[COL].max())), np.nan)
    g[d[ROW].astype(int) - 1, d[COL].astype(int) - 1] = d[VALUE]
    grids[name] = g
top = max(np.nanmax(np.abs(g)) for g in grids.values()) or 1.0  # ± the largest weight of any filter
def limits(name):
    lim = top if SHARED else (np.nanmax(np.abs(grids[name])) or 1.0)
    return -lim, lim
n = len(panels)
per_row = max(1, int(np.ceil(np.sqrt(n * 1.6))))
lines = int(np.ceil(n / per_row))
cmap = LinearSegmentedColormap.from_list("div", DIV)
fig, axes = plt.subplots(lines, per_row, figsize=(1.7 * per_row, 1.9 * lines), squeeze=False)
for ax in axes.flat:
    ax.axis("off")
for ax, name in zip(axes.flat, panels):
    g = grids[name]
    lo, hi = limits(name)
    im = ax.imshow(g, cmap=cmap, vmin=lo, vmax=hi)
    if VALUES and g.size <= 49:
        for (i, j), v in np.ndenumerate(g):
            if not np.isnan(v):
                ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=6)
    ax.set_title(str(name), fontsize=8)
fig.colorbar(im, ax=axes, shrink=0.6, label=VALUE)
plt.show()

Needs pandas, numpy, matplotlib · reads cnn-filters-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#cnn-feature-maps

CNN feature maps

Which parts of an image does each first-layer filter respond to?

Demo data · seed 20261101 · 576 rows · default settings · 640 × 360

How to read it

  1. Start with the outlined panel: the input image as the network sees it.
  2. Read each other panel as the image filtered by one kernel, after the ReLU: bright cells are where that kernel's pattern is found, dark cells where it is absent.
  3. Compare the maps: different kernels pick out different strokes of the same image, which is what the next layer combines.
  1. Callout 1: The input image.
  2. Callout 2: A map: bright where the kernel's pattern is.
  3. Callout 3: Caption: the map's largest activation.

Watch out

  • This is one image; maps of other images, or of other classes, can look quite different.
  • Each map uses its own scale by default, so a faint map can look bright; read its caption or switch to the shared scale.

Defaults

Colour scale
Each map's own
Each: every map runs from 0 to its own peak, to see where it fires. Shared: one scale, to compare how strongly the filters fire.
Also: Shared by all maps
Values in cells
Off
Prints each activation in its cell when the cells are large enough (about 22 px).

Pinned in the code

  • Draws the numbers the network published (kernel weights, activations, out-of-fold counts); the chart computes nothing statistical.
  • The panel named input is the image as the network sees it (divided by the largest training pixel); the others are the first convolution block's outputs after the ReLU, before pooling, at full size.
  • Each map's caption gives its largest activation, so strength is readable without the colour scale.
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")
# controls: scale=each, values=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("cnn-feature-maps-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["panel"] = pd.Categorical(df["panel"].astype("string"), categories=["input", "map 1", "map 2", "map 3", "map 4", "map 5", "map 6", "map 7", "map 8"])

_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)))
PANEL = "panel"
ROW = "row"
COL = "col"
VALUE = "activation"
SHARED, VALUES = False, False  # one colour scale for all panels; print values in small grids
panels = levels_of(df[PANEL])
grids = {}
for name in panels:  # rows and columns count from 1, row 1 at the top
    d = df[df[PANEL].astype(str) == str(name)]
    g = np.full((int(d[ROW].max()), int(d[COL].max())), np.nan)
    g[d[ROW].astype(int) - 1, d[COL].astype(int) - 1] = d[VALUE]
    grids[name] = g
top = max([np.nanmax(g) for n, g in grids.items() if str(n).lower() != "input"] or [1.0]) or 1.0
def limits(name):  # the input keeps its own range; maps run from 0
    g = grids[name]
    if str(name).lower() == "input" or not SHARED:
        return min(0.0, np.nanmin(g)), (np.nanmax(g) or 1.0)
    return 0.0, top
n = len(panels)
per_row = max(1, int(np.ceil(np.sqrt(n * 1.6))))
lines = int(np.ceil(n / per_row))
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, axes = plt.subplots(lines, per_row, figsize=(1.7 * per_row, 1.9 * lines), squeeze=False)
for ax in axes.flat:
    ax.axis("off")
for ax, name in zip(axes.flat, panels):
    g = grids[name]
    lo, hi = limits(name)
    im = ax.imshow(g, cmap=cmap, vmin=lo, vmax=hi)
    if VALUES and g.size <= 49:
        for (i, j), v in np.ndenumerate(g):
            if not np.isnan(v):
                ax.text(j, i, f"{v:.2f}", ha="center", va="center", fontsize=6)
    is_input = str(name).lower() == "input"
    ax.set_title("input" if is_input else f"{name} · max {np.nanmax(g):.2f}", fontsize=8, fontweight="bold" if is_input else "normal")
    if is_input:
        ax.axis("on"); ax.set_xticks([]); ax.set_yticks([])  # the input keeps a full frame
        for side in ax.spines.values():
            side.set_visible(True); side.set_linewidth(1.4)
fig.colorbar(im, ax=axes, shrink=0.6, label=VALUE)
plt.show()

Needs pandas, numpy, matplotlib · reads cnn-feature-maps-demo.csv · app theme from the optional codesplash helper

Machine learning

svg#cnn-confusion

Confusion matrix (out of fold)

Which classes does the model mix up, and how often is each class recognised?

Demo data · seed 20261101 · 100 rows · default settings · 640 × 360

How to read it

  1. Read each row as the rows whose actual class is that label, and each column as what the model predicted for them.
  2. Read the outlined diagonal as correct predictions; the recall on the right is the diagonal's share of its row.
  3. Find the largest numbers off the diagonal: those are the pairs the model mixes up, named under the matrix.
  1. Callout 1: Outlined diagonal: correct predictions.
  2. Callout 2: Off-diagonal count: a mix-up.
  3. Callout 3: Recall per actual class.

Watch out

  • Shading by the share of each actual class hides how many rows a class has; switch to count to see where most rows are.
  • These are out-of-fold predictions on the training data; the locked test set is scored separately in the run's metrics.

Defaults

Shade by
Share of the actual class (recall)
Share of the actual class makes rare classes as visible as common ones; count shows where most of the rows are.
Also: Count
Counts in cells
On
Prints the count in every non-empty cell (and on the diagonal) when the cells are large enough.

Pinned in the code

  • Draws the numbers the network published (kernel weights, activations, out-of-fold counts); the chart computes nothing statistical.
  • Counts pool the out-of-fold predictions of every cross-validation fold (each row is predicted by a model that never saw it); the locked test rows are not included.
  • The predicted class is the most probable one (for two classes, probability ≥ 0.5 for the positive class), as in the run's accuracy.
  • Recall is the diagonal count over its row total; classes keep the target's level order.
# Confusion matrix (out of fold) — Codesplash Chart Lab (recipe "cnn-confusion")
# controls: normalize=row, values=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("cnn-confusion-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["actual"] = pd.Categorical(df["actual"].astype("string"), categories=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])
df["predicted"] = pd.Categorical(df["predicted"].astype("string"), categories=["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])

_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)))
A = "actual"
P = "predicted"
N = "rows"
BY_ROW, VALUES = True, True  # shade by the share of each actual class; print counts
classes = list(dict.fromkeys(levels_of(df[A]) + levels_of(df[P])))
idx = {cl: i for i, cl in enumerate(classes)}
k = len(classes)
M = np.zeros((k, k))  # rows actual, columns predicted
for a, p, n in zip(df[A], df[P], df[N] if N else np.ones(len(df))):
    if pd.notna(a) and pd.notna(p) and pd.notna(n):
        M[idx[str(a)], idx[str(p)]] += n
totals = M.sum(axis=1)
share = np.divide(M, totals[:, None], out=np.zeros_like(M), where=totals[:, None] > 0)
Z = share if BY_ROW else M / max(M.max(), 1)
recall = np.divide(np.diag(M), totals, out=np.full(k, np.nan), where=totals > 0)
ylabels = [f"{cl}  ({r:.0%})" if not np.isnan(r) else cl for cl, r in zip(classes, recall)]
title = f"accuracy {np.trace(M) / max(M.sum(), 1):.1%} of {M.sum():g} (diagonal outlined; recall in brackets)"
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(6.5, 5.6))
ax.imshow(Z, cmap=cmap, vmin=0, vmax=1)
for i in range(k):
    ax.add_patch(plt.Rectangle((i - 0.45, i - 0.45), 0.9, 0.9, fill=False, edgecolor=REF, linewidth=1.4))  # correct predictions
    for j in range(k):
        if VALUES and (M[i, j] > 0 or i == j):
            ax.text(j, i, f"{M[i, j]:g}", ha="center", va="center", fontsize=8, fontweight="bold" if i == j else "normal", color="white" if Z[i, j] > 0.55 else "black")
ax.set_xticks(range(k), classes)
ax.set_yticks(range(k), ylabels)
ax.xaxis.tick_top()
ax.xaxis.set_label_position("top")
ax.set_xlabel("predicted")
ax.set_ylabel("actual (recall)")
ax.set_title(title, fontsize=9, pad=28)
plt.show()

Needs pandas, numpy, matplotlib · reads cnn-confusion-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

Clusters, dendrograms, embeddings, association rules, topics, anomalies and forecasts with backtests.

20

Discover & forecasting

svg#cluster-scatter

Cluster map

Which rows group together, and how well separated are the groups?

Demo data · seed 20261101 · 519 rows · default settings · 640 × 360

How to read it

  1. Read colour as the cluster a row was assigned to.
  2. Check separation: are clusters distinct, or touching?
  3. Grey points are noise, assigned to no cluster.
  1. Callout 1: A cluster with its centre.
  2. Callout 2: Another, well separated.
  3. Callout 3: Grey: noise.

Watch out

  • Clustering always returns clusters, even from noise. Check stability before you name them.
  • A 2-D map can show separation that isn't in the full data, or hide it.

Defaults

Convex hull per cluster
Off
Outline each cluster with the smallest shape enclosing its points.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Clusters are the run's labels after canonicalization (1…k by size, largest first); −1 is noise (DBSCAN/HDBSCAN) and is drawn grey and listed last.
  • Rows flagged as centres (k-means centroids, PAM medoids projected into the same space) are drawn as diamonds.
  • Distances on a UMAP or t-SNE map are not faithful — use the map to see groups, not to measure them.
# Cluster map — Codesplash Chart Lab (recipe "cluster-scatter")
# controls: hull=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("cluster-scatter-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 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 is_noise(v):
    return str(v).strip().lower() in ("-1", "noise", "outlier")
def truthy(s):
    return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
X = "PC1"
Y = "PC2"
CL = "cluster"
CEN = "centre"
LAB = None
HULL = False  # convex hull around each cluster
d = df.dropna(subset=[X, Y, CL])
cen = truthy(d[CEN]) if CEN else pd.Series(False, index=d.index)
pts, centres = d[~cen], d[cen]
clusters = [k for k in levels_of(pts[CL]) if not is_noise(k)]
fig, ax = plt.subplots(figsize=(7, 6))
noise = pts[pts[CL].map(is_noise)]
if len(noise):
    ax.scatter(noise[X], noise[Y], s=8, color=GREY, label="noise")
for i, k in enumerate(clusters):
    g = pts[pts[CL].astype(str) == str(k)]
    col = PALETTE[i % len(PALETTE)]
    ax.scatter(g[X], g[Y], s=10, alpha=0.75, color=col, marker=SERIES_MARKERS[i % 8], label=str(k))  # shape per cluster (noise stays round), as in the app
    if HULL and len(g) >= 3:
        xy = g[[X, Y]].to_numpy(float)
        h = ConvexHull(xy).vertices
        ax.fill(xy[h, 0], xy[h, 1], color=col, alpha=0.08, edgecolor=col, linewidth=1)
ax.scatter(centres[X], centres[Y], marker="X", s=140, color="white", edgecolors=REF, linewidths=1.5, zorder=3, label="centre" if len(centres) else None)
if LAB:
    for _, row in centres.iterrows():
        ax.annotate(str(row[LAB]), (row[X], row[Y]), xytext=(6, 6), textcoords="offset points", fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(title=CL, fontsize=8, markerscale=1.5)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads cluster-scatter-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#dendrogram

Dendrogram

How do rows merge into clusters, and where should the tree be cut?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Read from the leaves up: branches join where groups merge.
  2. Read join height as how different the merged groups are.
  3. Cut across a long vertical gap to get a natural number of clusters.
  1. Callout 1: A high join: very different groups.
  2. Callout 2: Low joins: very similar rows.
  3. Callout 3: The leaves are rows.

Watch out

  • The left-to-right order isn't meaningful: only the heights are.

Defaults

Cut into k clusters (0 = no cut)
0
Colour the tree as if cut into this many clusters.
Range 0 to 30, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Input is R's hclust merge matrix (scipy's linkage converts with leaves as negative 1-based numbers); leaves are ordered like hclust$order (left subtree first) and each merge sits midway between its children.
  • The cut for k clusters lies midway between the (n − k)-th and (n − k + 1)-th merge heights; branches below it take the cluster colours, left to right.
  • Leaf names are drawn up to 60 leaves.
# Dendrogram — Codesplash Chart Lab (recipe "dendrogram")
# controls: k=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("dendrogram-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 dendro_layout(df, ML, MR, H, k):
    a, b, h = df[ML].to_numpy(float), df[MR].to_numpy(float), df[H].to_numpy(float)
    ok = ~(np.isnan(a) | np.isnan(b) | np.isnan(h))
    merges = [(int(x), int(y), float(z)) for x, y, z in zip(a[ok], b[ok], h[ok])]
    m = len(merges)
    order, stack = [], [m]
    while stack:  # hclust order: depth first, left subtree first
        v = stack.pop()
        if v < 0:
            order.append(-v)
        else:
            stack += [merges[v - 1][1], merges[v - 1][0]]
    pos = {leaf: i for i, leaf in enumerate(order)}
    xs, leaves = [0.0] * m, [[] for _ in range(m)]
    xo = lambda v: pos[-v] if v < 0 else xs[v - 1]
    lv = lambda v: [-v] if v < 0 else leaves[v - 1]
    for i, (left, right, _) in enumerate(merges):
        xs[i] = (xo(left) + xo(right)) / 2
        leaves[i] = lv(left) + lv(right)
    k = int(round(k))
    below = m - (k - 1) if k >= 2 else m  # merges below the cut
    cluster, cut = {}, None
    if k >= 2:
        roots = [ch for i in range(below, m) for ch in merges[i][:2] if ch < 0 or ch - 1 < below]
        roots.sort(key=lambda v: min(pos[x] for x in lv(v)))
        for ci, rt in enumerate(roots):
            for x in lv(rt):
                cluster[x] = ci
        lo = merges[below - 1][2] if below >= 1 else 0.0
        cut = (lo + merges[below][2]) / 2
    return merges, order, xo, lv, below, cluster, cut
ML = "merge left"
MR = "merge right"
H = "height (Ward)"
LAB = "state"
K = 0  # cut into k clusters (0 = no cut)
merges, order, xo, lv, below, cluster, cut = dendro_layout(df, ML, MR, H, K)
labels = df[LAB].astype(str).tolist() if LAB else [str(i) for i in range(1, len(order) + 1)]
ho = lambda v: 0.0 if v < 0 else merges[v - 1][2]
fig, ax = plt.subplots(figsize=(9, 4.8))
for i, (left, right, h) in enumerate(merges):
    col = PALETTE[cluster[lv(left)[0]] % len(PALETTE)] if cluster and i < below else REF
    ax.plot([xo(left), xo(left), xo(right), xo(right)], [ho(left), h, h, ho(right)], color=col, linewidth=1.2)
if cut is not None:
    ax.axhline(cut, color="#ce5342", linestyle="--", linewidth=1)
ax.set_xticks(range(len(order)), [labels[x - 1] if x - 1 < len(labels) else str(x) for x in order], rotation=90, fontsize=8)
ax.set_ylabel(H)
ax.set_xlim(-0.5, len(order) - 0.5)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads dendrogram-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#silhouette-plot

Silhouette plot

How well does each row fit its cluster compared with the next-nearest cluster?

Demo data · seed 20261101 · 150 rows · default settings · 640 × 360

How to read it

  1. Read each thin bar as one row's fit: near 1 is well inside its cluster.
  2. Compare clusters with the dashed average.
  3. Bars below zero: rows closer to another cluster.
  1. Callout 1: Wide bars: rows well inside this cluster.
  2. Callout 2: Dashed line: the average silhouette.
  3. Callout 3: Near zero: rows on a boundary.

Watch out

  • Silhouette favours round, equally sized clusters, and can miss valid long or nested ones.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Widths s(i) = (b − a) / max(a, b) from the engine (a = mean distance to the own cluster, b = to the nearest other); the chart sorts them within each cluster and draws each cluster as one filled profile, so any number of rows stays light.
  • Rule of thumb (Kaufman & Rousseeuw): average > 0.7 strong, 0.5–0.7 reasonable, 0.25–0.5 weak structure.
# Silhouette plot — Codesplash Chart Lab (recipe "silhouette-plot")
# 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("silhouette-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cluster"] = pd.Categorical(df["cluster"].astype("string"), categories=["1", "2", "3"])

_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)))
CL = "cluster"
W = "silhouette width"
d = df.dropna(subset=[CL, W])
clusters = levels_of(d[CL])
fig, ax = plt.subplots(figsize=(7, 6))
y0, ticks = 0, []
for i, k in enumerate(clusters):
    w = d.loc[d[CL].astype(str) == str(k), W].sort_values(ascending=False).to_numpy()  # sorted within the cluster
    ax.barh(np.arange(y0, y0 + len(w)), w, height=1.0, color=PALETTE[i % len(PALETTE)], linewidth=0)
    ticks.append(y0 + len(w) / 2)
    y0 += len(w) + 3
avg = d[W].mean()
ax.axvline(avg, color=REF, linestyle="--", linewidth=1, label=f"average {avg:.2f}")
ax.axvline(0, color="grey", linewidth=0.8)
ax.set_yticks(ticks, [str(k) for k in clusters])
ax.invert_yaxis()
ax.set_xlabel(W)
ax.set_ylabel(CL)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads silhouette-plot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#elbow-plot

Choosing k

How many clusters does the data support?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Read one panel per criterion against the number of clusters.
  2. Look for a bend or peak: the ringed point is the suggested k.
  3. Prefer a k that several criteria agree on, and that makes sense for your data.
  1. Callout 1: The elbow: extra clusters stop helping much.
  2. Callout 2: A peak: the best silhouette.
  3. Callout 3: The gap statistic's choice.

Watch out

  • Elbows are often not sharp, and the criteria can disagree: there may be no natural k.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Criteria have different scales and directions (lower inertia / Davies–Bouldin is better, higher silhouette / Calinski–Harabasz / gap is better), so each gets its own panel and y-axis.
  • The ringed point is the run's recommendation for that criterion (elbow by kneedle, maximum silhouette, gap's first k within one SE, …).
# Choosing k — Codesplash Chart Lab (recipe "elbow-plot")
# 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("elbow-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["criterion"] = pd.Categorical(df["criterion"].astype("string"), categories=["within-cluster SS", "silhouette", "gap statistic"])

_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 truthy(s):
    return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
K = "number of clusters k"
S = "score"
CRIT = "criterion"
CH = "recommended"
d = df.dropna(subset=[K, S]).sort_values(K)
crits = levels_of(d[CRIT]) if CRIT else [None]
fig, axes = plt.subplots(1, len(crits), figsize=(3.4 * len(crits) + 1, 3.8), squeeze=False)
for i, (ax, cr) in enumerate(zip(axes[0], crits)):  # one panel per criterion (different scales)
    g = d if cr is None else d[d[CRIT].astype(str) == str(cr)]
    ax.plot(g[K], g[S], color=PALETTE[i % len(PALETTE)], marker="o", ms=4, linewidth=1.8)
    if CH:
        pick = g[truthy(g[CH])]
        ax.scatter(pick[K], pick[S], s=180, facecolors="none", edgecolors=REF, linewidths=1.6, zorder=3)
    ax.set_title(str(cr) if cr is not None else S, fontsize=10)
    ax.set_xlabel(K)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads elbow-plot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#scree-plot

Scree plot

How many components carry most of the variance?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each bar as the variance one component carries.
  2. Read the line as the running total.
  3. Stop where bars flatten, or at a total share you need.
  1. Callout 1: The first component's share.
  2. Callout 2: The running total.
  3. Callout 3: Small bars: little beyond noise.

Watch out

  • Without scaling, components mostly reflect the columns with the largest units.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Variance shares are proportions (eigenvalue ÷ total); the cumulative line is the engine's when sent, else the running sum.
# Scree plot — Codesplash Chart Lab (recipe "scree-plot")
# 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("scree-plot-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")
COMP = "component"
VAR = "share of variance"
CUM = None
d = df.dropna(subset=[COMP, VAR]).sort_values(COMP)
cum = d[CUM] if CUM else d[VAR].cumsum()
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.bar(d[COMP].astype(str), d[VAR], color=PALETTE[0], label=VAR)
ax.plot(d[COMP].astype(str), cum, color=REF, marker="o", ms=4, linewidth=1.6, label="cumulative")
for x, v in zip(d[COMP].astype(str), d[VAR]):
    ax.annotate(f"{v:.0%}" if d[VAR].max() <= 1 else f"{v:.3g}", (x, v), xytext=(0, 3), textcoords="offset points", ha="center", fontsize=8)
ax.set_xlabel(COMP)
ax.set_ylabel(VAR)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads scree-plot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#biplot

PCA biplot

How do rows spread on the main components, and which variables drive each direction?

Demo data · seed 20261101 · 28 rows · default settings · 640 × 360

How to read it

  1. Read points as rows on the first two components.
  2. Read arrows as variables: long arrows contribute more.
  3. Rows far along an arrow have high values for that variable.
  1. Callout 1: An arrow: this variable's direction.
  2. Callout 2: A row far along this direction.
  3. Callout 3: Rows on the other side: low values.

Watch out

  • It shows only part of the variance: check the percentages on the axes before you trust distances.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Loadings are multiplied by one factor so the longest arrow reaches 80% of the largest score (the legend shows the factor); arrow lengths compare variables, not rows.
  • Both axes share one scale so angles between arrows read as correlations.
# PCA biplot — Codesplash Chart Lab (recipe "biplot")
# 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("biplot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["point", "loading"])

_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")
X = "PC1 (62%)"
Y = "PC2 (25%)"
KIND = "kind"
LAB = "label"
d = df.dropna(subset=[X, Y])
load = d[KIND].astype(str).str.lower().str.startswith("load")
pts, ld = d[~load], d[load]
reach = float(np.abs(pts[[X, Y]].to_numpy()).max()) if len(pts) else 1.0
longest = float(np.hypot(ld[X], ld[Y]).max()) if len(ld) else 1.0
scale = 0.8 * reach / longest if len(pts) else 1.0  # longest arrow reaches 80% of the score extent
fig, ax = plt.subplots(figsize=(7, 6))
ax.axhline(0, color="grey", linewidth=0.6)
ax.axvline(0, color="grey", linewidth=0.6)
ax.scatter(pts[X], pts[Y], s=16, color=PALETTE[0], alpha=0.8)
for _, row in pts.iterrows():
    ax.annotate(str(row[LAB]), (row[X], row[Y]), xytext=(3, 3), textcoords="offset points", fontsize=7, color=GREY if len(pts) > 40 else REF)
for _, row in ld.iterrows():
    ax.annotate("", xy=(row[X] * scale, row[Y] * scale), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color="#ce5342", lw=1.4))
    ax.annotate(str(row[LAB]), (row[X] * scale, row[Y] * scale), xytext=(4, 4), textcoords="offset points", fontsize=9, color="#ce5342")
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads biplot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#rules-scatter

Association rules

Which item combinations co-occur often and reliably, beyond chance?

Demo data · seed 20261101 · 90 rows · default settings · 640 × 360

How to read it

  1. Read x as how common the rule is and y as how often it holds.
  2. Read colour as lift: how much more often than chance.
  3. Prefer rules that are high on all three.
  1. Callout 1: High confidence, but rare.
  2. Callout 2: Common but less reliable.
  3. Callout 3: Colour scale: lift.

Watch out

  • Confidence can be high only because the consequent is common: use lift. Many rules means some look strong by chance.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Support = share of transactions containing all items; confidence = P(consequent | antecedent); lift = confidence ÷ P(consequent) (> 1 means the items co-occur more than by chance).
  • High confidence with lift near 1 only reflects a popular consequent.
# Association rules — Codesplash Chart Lab (recipe "rules-scatter")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("rules-scatter-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")
SUP = "support"
CONF = "confidence"
LIFT = "lift"
LAB = "rule"
d = df.dropna(subset=[SUP, CONF, LIFT])
cmap = LinearSegmentedColormap.from_list("seq", [SEQ[0], SEQ[-1]])
fig, ax = plt.subplots(figsize=(8, 5))
sc = ax.scatter(d[SUP], d[CONF], c=d[LIFT], cmap=cmap, s=30, edgecolors=GREY, linewidths=0.4)
for _, row in d.nlargest(5, LIFT).iterrows():  # the highest-lift rules
    ax.annotate(str(row[LAB]), (row[SUP], row[CONF]), xytext=(4, 4), textcoords="offset points", fontsize=7)
fig.colorbar(sc, ax=ax, label=LIFT)
ax.set_xlabel(SUP)
ax.set_ylabel(CONF)
plt.show()

Needs pandas, numpy, matplotlib · reads rules-scatter-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#topic-terms

Topic terms

What is each topic about?

Demo data · seed 20261101 · 40 rows · default settings · 640 × 360

How to read it

  1. Read each panel's top terms to name the topic.
  2. Compare bar lengths: the most representative terms.
  3. A term in several panels doesn't distinguish topics.
  1. Callout 1: This topic's top term.
  2. Callout 2: The topic's label, for you to check.
  3. Callout 3: Bars: the term's weight.

Watch out

  • Topics are bags of words: the name you give them is your interpretation.

Defaults

Terms per topic
10
How many terms each topic shows.
Range 3 to 30, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Bars are scaled within each panel (the largest term fills the panel); weights are not comparable across topics for NMF.
# Topic terms — Codesplash Chart Lab (recipe "topic-terms")
# controls: top=10
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("topic-terms-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["topic"] = pd.Categorical(df["topic"].astype("string"), categories=["Topic 1 · pricing", "Topic 2 · delivery", "Topic 3 · quality", "Topic 4 · service"])

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)))
TOPIC = "topic"
TERM = "term"
W = "P(word | topic)"
TOP = 10  # terms per topic
d = df.dropna(subset=[TOPIC, TERM, W])
topics = levels_of(d[TOPIC])
ncol = min(4, len(topics))
nrow = int(np.ceil(len(topics) / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(3.2 * ncol + 1, 0.28 * TOP * nrow + 1.2), squeeze=False)
for i, ax in enumerate(axes.flat):
    if i >= len(topics):
        ax.axis("off")
        continue
    g = d[d[TOPIC].astype(str) == str(topics[i])].nlargest(TOP, W).iloc[::-1]
    ax.barh(g[TERM].astype(str), g[W], color=PALETTE[i % len(PALETTE)])
    ax.set_title(str(topics[i]), fontsize=9)
    ax.tick_params(labelsize=8)
fig.supxlabel(W)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads topic-terms-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#anomaly-scores

Anomaly score distribution

How unusual are the most anomalous rows compared with the rest, and where is the cut?

Demo data · seed 20261101 · 1,200 rows · default settings · 640 × 360

How to read it

  1. Read the histogram as all rows' anomaly scores.
  2. Find the dashed threshold: rows beyond it are flagged in red.
  3. A clear gap before the threshold is reassuring; a smooth tail means the cut is arbitrary.
  1. Callout 1: Most rows: low scores.
  2. Callout 2: Threshold: the flagging cut.
  3. Callout 3: Flagged rows.

Watch out

  • An anomaly isn't an error or a fraud. Investigate each flag.

Defaults

Threshold (0 = smallest flagged score)
0
The score above which rows are flagged.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Scores are oriented so higher = more anomalous (the run converts scikit-learn's negative outlier factor and isotree's depth-based scores to that convention).
  • Bins: about 1.5 √n, between 10 and 60. Without an explicit threshold the line sits at the smallest flagged score (the contamination cut the run used).
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")
# controls: threshold=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("anomaly-scores-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 truthy(s):
    return s.astype(str).str.strip().str.lower().isin(["true", "1", "yes", "t"])
S = "anomaly score"
FLAG = "flagged"
THRESHOLD = 0  # 0 = the smallest flagged score
d = df.dropna(subset=[S])
flag = truthy(d[FLAG]) if FLAG else pd.Series(False, index=d.index)
k = int(min(60, max(10, round(1.5 * np.sqrt(len(d))))))  # about 1.5 √n bins
edges = np.linspace(d[S].min(), d[S].max(), k + 1)
normal, _ = np.histogram(d.loc[~flag, S], bins=edges)
flagged, _ = np.histogram(d.loc[flag, S], bins=edges)
thr = THRESHOLD if THRESHOLD != 0 else (d.loc[flag, S].min() if flag.any() else None)
fig, ax = plt.subplots(figsize=(8, 4.5))
w = np.diff(edges)
ax.bar(edges[:-1], normal, width=w, align="edge", color=PALETTE[0], label="normal")
ax.bar(edges[:-1], flagged, width=w, align="edge", bottom=normal, color="#ce5342", label="flagged")
if thr is not None:
    ax.axvline(thr, color=REF, linestyle="--", linewidth=1.2, label=f"threshold {thr:.3g}")
ax.set_xlabel(S)
ax.set_ylabel("rows")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads anomaly-scores-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#forecast-fan

Forecast fan chart

Where is the series heading, and how uncertain is the forecast?

Demo data · seed 20261101 · 156 rows · default settings · 640 × 360

How to read it

  1. Read the line for history and where the forecast continues from.
  2. Read the bands: the darker is 80%, the lighter 95%.
  3. Bands that widen quickly mean the forecast is soon uncertain.
  1. Callout 1: The forecast's centre line.
  2. Callout 2: The lighter band: 95% prediction interval.
  3. Callout 3: History.

Watch out

  • Intervals assume the future behaves like the past, so a structural change can break them.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Intervals are the model's prediction intervals (not confidence intervals for the mean); the forecast line starts at the last observed point so the hand-off is visible.
  • Long histories are drawn with largest-triangle-three-buckets downsampling (1,500 points); the Data table keeps every row.
  • Panel data (a series column) gets one small multiple per series, up to nine.
# Forecast fan chart — Codesplash Chart Lab (recipe "forecast-fan")
# 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("forecast-fan-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["actual", "fitted", "forecast"])

_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)))
T = "month"
V = "passengers (thousands)"
KIND = "kind"
L80 = "lo 80"
H80 = "hi 80"
L95 = "lo 95"
H95 = "hi 95"
SER = None
d = df.dropna(subset=[T]).sort_values(T)
kind = d[KIND].astype(str).str.lower() if KIND else pd.Series("actual", index=d.index)
names = levels_of(d[SER]) if SER else [None]
fig, axes = plt.subplots(len(names), 1, figsize=(8, 3.4 * len(names)), squeeze=False)
for ax, name in zip(axes[:, 0], names):
    m = pd.Series(True, index=d.index) if name is None else d[SER].astype(str) == str(name)
    act, fit, fc = d[m & (kind == "actual")], d[m & (kind == "fitted")], d[m & (kind == "forecast")]
    for lo, hi, a in ((L95, H95, 0.15), (L80, H80, 0.3)):  # nested 95% and 80% prediction intervals
        if lo and hi and len(fc):
            ax.fill_between(fc[T], fc[lo], fc[hi], color=PALETTE[0], alpha=a, lw=0)
    ax.plot(act[T], act[V], color=REF, linewidth=1.4, label="actual")
    if len(fit):
        ax.plot(fit[T], fit[V], color=PALETTE[1], linewidth=1, linestyle="--", label="fitted")
    if len(fc):
        joined = pd.concat([act.tail(1), fc])  # continue from the last observation
        ax.plot(joined[T], joined[V], color=PALETTE[0], linewidth=2, label="forecast")
    ax.set_title(str(name) if name is not None else V, fontsize=10)
    ax.set_ylabel(V)
axes[0, 0].legend(fontsize=8, loc="upper left")
axes[-1, 0].set_xlabel(T)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads forecast-fan-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#backtest-errors

Backtest errors by horizon

How does forecast error grow with the horizon, and how stable is it across origins?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360

How to read it

  1. Read thin lines as individual backtest windows, the thick line as the mean.
  2. Rising with horizon is normal; compare how fast.
  3. Thin lines far apart mean accuracy depends on when you start.
  1. Callout 1: Mean error at short horizons.
  2. Callout 2: Thin line: one forecast origin.
  3. Callout 3: Mean error at the longest horizon.

Watch out

  • Few windows make these noisy; check a naive baseline on the same windows.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Each origin is one backtest window (rolling origin, fixed horizon); the thick line is the arithmetic mean of the windows' errors at each horizon.
# Backtest errors by horizon — Codesplash Chart Lab (recipe "backtest-errors")
# 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("backtest-errors-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["origin"] = pd.Categorical(df["origin"].astype("string"), categories=["1958-12", "1959-03", "1959-06", "1959-09", "1959-12", "1960-03"])
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["MAE", "MAPE"])

_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)))
H = "months ahead"
E = "error"
ORIG = "origin"
MET = "metric"
d = df.dropna(subset=[H, E]).sort_values(H)
metrics = levels_of(d[MET]) if MET else [None]
fig, axes = plt.subplots(1, len(metrics), figsize=(4.2 * len(metrics) + 1, 4), squeeze=False)
for i, (ax, met) in enumerate(zip(axes[0], metrics)):  # one panel per metric
    g = d if met is None else d[d[MET].astype(str) == str(met)]
    col = PALETTE[i % len(PALETTE)]
    if ORIG:
        for _, s in g.groupby(ORIG, observed=True):  # each rolling-origin window
            ax.plot(s[H], s[E], color=GREY, linewidth=0.8)
    mean = g.groupby(H)[E].mean()
    ax.plot(mean.index, mean.values, color=col, linewidth=2.6, marker="o", ms=3.5, label="mean across origins")
    ax.set_title(str(met) if met is not None else E, fontsize=10)
    ax.set_xlabel(H)
axes[0, 0].set_ylabel(E)
axes[0, 0].legend(fontsize=8)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads backtest-errors-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#acf-plot

ACF / PACF (precomputed)

Is a series (or a model's residuals) autocorrelated, and at which lags?

Demo data · seed 20261101 · 48 rows · default settings · 640 × 360

How to read it

  1. Read bars outside the band as autocorrelation beyond noise.
  2. For model residuals, you want nothing outside.
  3. A spike at the seasonal lag means the season is not fully modelled.
  1. Callout 1: A bar beyond the band, at the seasonal lag.
  2. Callout 2: The band: the range for white noise.
  3. Callout 3: The same lag on the partial side.

Watch out

  • About 1 lag in 20 pokes out by chance.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Correlations come from the engine (statsmodels acf/pacf ↔ R acf/pacf on the residuals or the series); the band is the engine's ±1.96/√n white-noise bound when sent.
  • Use the time-series family's "acf" recipe to compute these from raw data instead.
# ACF / PACF (precomputed) — Codesplash Chart Lab (recipe "acf-plot")
# 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("acf-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["acf", "pacf"])

_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)))
LAG = "lag (months)"
ACF = "correlation"
B = "bound"
KIND = "kind"
d = df.dropna(subset=[LAG, ACF]).sort_values(LAG)
kinds = levels_of(d[KIND]) if KIND else [None]
fig, axes = plt.subplots(1, len(kinds), figsize=(4.2 * len(kinds) + 1, 3.8), squeeze=False, sharey=True)
for ax, k in zip(axes[0], kinds):  # ACF and PACF side by side
    g = d if k is None else d[d[KIND].astype(str) == str(k)]
    bound = float(g[B].iloc[0]) if B else None
    if bound is not None:
        ax.axhspan(-bound, bound, color=GREY, alpha=0.4, lw=0)  # ±1.96/√n
    out = (g[ACF].abs() > bound) if bound is not None else pd.Series(False, index=g.index)
    cols = np.where(out, "#ce5342", PALETTE[0])
    ax.vlines(g[LAG], 0, g[ACF], colors=cols, linewidth=2)
    ax.scatter(g[LAG], g[ACF], c=cols, s=14, zorder=3)
    ax.axhline(0, color="grey", linewidth=0.8)
    ax.set_title(str(k).upper() if k is not None else ACF, fontsize=10)
    ax.set_xlabel(LAG)
axes[0, 0].set_ylabel(ACF)
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads acf-plot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#k-distance

k-distance curve

Which neighbourhood radius (eps) separates dense rows from sparse ones?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Read rows sorted by distance to their k-th neighbour.
  2. The ringed knee is where distances begin to climb.
  3. Use the distance at the knee for eps: rows above it become noise.
  1. Callout 1: The knee: a candidate for eps.
  2. Callout 2: Flat region: rows in dense areas.
  3. Callout 3: Steep end: isolated rows.

Watch out

  • Clusters of different densities don't share one eps: consider OPTICS.

Defaults

eps line (0 = the chosen row)
0
Draw the distance you are considering for eps; 0 uses the knee.
Range 0 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • k-distance = distance to the k-th nearest row with the row itself counted (k = minimum neighbours), as dbscan::kNNdist(k − 1) and scikit-learn's NearestNeighbors(k).
  • The knee is the point farthest from the chord between the curve's end points on normalized axes (kneedle).
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")
# controls: eps=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("k-distance-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")
X = "rows (sorted)"
D = "distance to the 5th neighbour"
CH = "chosen eps"
d = df.dropna(subset=[X, D]).sort_values(X)
eps = 0
chosen = d[d[CH].astype(str).str.lower() == "true"] if CH else d.iloc[:0]
if not eps and len(chosen):
    eps = float(chosen[D].iloc[0])
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(d[X], d[D], color=PALETTE[0], label="sorted k-distance")
if len(chosen):
    ax.scatter(chosen[X], chosen[D], s=50, facecolor="none", edgecolor=REF, zorder=3)
if eps:
    ax.axhline(eps, color=REF, linestyle="--", linewidth=1, label=f"eps = {eps:.3g}")
ax.set_xlabel("rows (sorted)")
ax.set_ylabel(D)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads k-distance-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#reachability-plot

Reachability plot (OPTICS)

Where are the dense regions, at every density at once?

Demo data · seed 20261101 · 157 rows · default settings · 640 × 360

How to read it

  1. Read left to right in OPTICS order.
  2. Read each valley as a cluster; deeper valleys are denser.
  3. Read the peaks between valleys as the boundaries.
  1. Callout 1: A valley: one cluster.
  2. Callout 2: A peak: a boundary between clusters.
  3. Callout 3: A shallower valley: a denser or sparser cluster.

Watch out

  • Valleys can look deeper from the display's scale. A cut line gives a concrete clustering.

Defaults

Cut (0 = none)
0
Draw the reachability level that defines clusters; valleys below it become clusters.
Range 0 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Reachability of a row = max(core distance of its predecessor, distance to it); the first row of each region has none and is drawn as a faint full-height bar.
  • Bars are coloured by the DBSCAN-equivalent clusters at the cut; noise is grey.
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")
# controls: cut=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("reachability-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["cluster"] = pd.Categorical(df["cluster"].astype("string"), categories=["1", "2", "3", "-1"])

_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 = "OPTICS order"
R = "reachability distance"
K = "cluster"
U = "no reachability"
d = df.sort_values(X)
h = d[R].astype(float)
top = np.nanmax(h) * 1.05
fig, ax = plt.subplots(figsize=(8, 4))
no_reach = h.isna() | (d[U].astype(str).str.lower() == "true" if U else False)
ax.bar(d.loc[no_reach, X], top, width=1, color=GREY, label="no reachability")
clusters = levels_of(d[K]) if K else []
for i, k in enumerate(clusters):
    g = d[(d[K].astype(str) == str(k)) & ~no_reach]
    noise = str(k).lower() in ("noise", "-1")
    ax.bar(g[X], g[R], width=1, color=GREY if noise else PALETTE[i % len(PALETTE)], label=str(k))
if not K:
    g = d[~no_reach]
    ax.bar(g[X], g[R], width=1, color=PALETTE[0])

ax.set_xlabel("OPTICS order")
ax.set_ylabel("reachability distance")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads reachability-plot-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#consensus-heatmap

Consensus matrix

How often do two rows end up in the same cluster when the data is resampled?

Demo data · seed 20261101 · 1,024 rows · default settings · 640 × 360

How to read it

  1. Read a cell as how often two rows cluster together across resamples.
  2. Solid dark blocks: stable clusters.
  3. Mottled cells between blocks: rows that move between clusters.
  1. Callout 1: A solid block: a stable cluster.
  2. Callout 2: Another block.
  3. Callout 3: Pale: these rows rarely cluster together.

Watch out

  • Stable doesn't mean real: an artefact of scaling can be perfectly stable.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Each cell is (resamples with both rows clustered together) / (resamples containing both rows); rows are a fixed evenly spaced sample, grouped by their cluster on the full data.
  • PAC (share of pairs strictly between 0.1 and 0.9) summarises ambiguity: lower is crisper.
# Consensus matrix — Codesplash Chart Lab (recipe "consensus-heatmap")
# 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("consensus-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

R = "row (by cluster)"
C = "column (by cluster)"
V = "share of resamples together"
m = df.pivot_table(index=R, columns=C, values=V, aggfunc="mean").sort_index().sort_index(axis=1)
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(m.to_numpy(), cmap="Blues", aspect="equal", interpolation="nearest", extent=[m.columns.min() - 0.5, m.columns.max() + 0.5, m.index.max() + 0.5, m.index.min() - 0.5])
fig.colorbar(im, label=V, shrink=0.8)
ax.set_xlabel("row (by cluster)")
ax.set_ylabel("row (by cluster)")
plt.show()

Needs pandas, numpy, matplotlib · reads consensus-heatmap-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#vat-heatmap

VAT image (cluster tendency)

Is there cluster structure before any clustering is run?

Demo data · seed 20261101 · 900 rows · default settings · 640 × 360

How to read it

  1. Read the diagonal: dark blocks along it are candidate clusters.
  2. Count the blocks and their sizes.
  3. No blocks suggests no clear structure.
  1. Callout 1: A dark block: a candidate cluster.
  2. Callout 2: Another block.
  3. Callout 3: A smaller block.

Watch out

  • It's a pre-check: an empty display doesn't rule out non-round clusters.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Order: start at the row holding the largest distance, then repeatedly add the unvisited row nearest to the visited set (Bezdek & Hathaway's VAT).
  • Large tables are evenly sampled (≤ 500 rows) and averaged into at most 80 × 80 blocks; darker = closer.
# VAT image (cluster tendency) — Codesplash Chart Lab (recipe "vat-heatmap")
# 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("vat-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

R = "row block"
C = "column block"
V = "mean distance"
m = df.pivot_table(index=R, columns=C, values=V, aggfunc="mean").sort_index().sort_index(axis=1)
fig, ax = plt.subplots(figsize=(6, 5))
im = ax.imshow(m.to_numpy(), cmap="Blues_r", aspect="equal", interpolation="nearest", extent=[m.columns.min() - 0.5, m.columns.max() + 0.5, m.index.max() + 0.5, m.index.min() - 0.5])
fig.colorbar(im, label=V, shrink=0.8)
ax.set_xlabel("block (VAT order)")
ax.set_ylabel("block (VAT order)")
plt.show()

Needs pandas, numpy, matplotlib · reads vat-heatmap-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#sequence-sankey

Journey flow

Where do journeys go from each step to the next?

Demo data · seed 20261101 · 22 rows · default settings · 640 × 360

How to read it

  1. Read columns left to right as steps in a journey.
  2. Read ribbon width as how many journeys take that move.
  3. Look for the widest paths and for the (end) nodes, where journeys stop.
  1. Callout 1: The first step: where journeys start.
  2. Callout 2: A wide ribbon: a common move.
  3. Callout 3: Journeys that stop here.

Watch out

  • It shows moves between adjacent steps; longer patterns aren't visible, and rare paths get collapsed.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Nodes are "step: event" pairs; within a step, the most frequent events are on top, then Other, then (end).
  • Only the most frequent events get their own colour; the rest are grouped as Other by the run.
# Journey flow — Codesplash Chart Lab (recipe "sequence-sankey")
# 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("sequence-sankey-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

SRC = "from"
DST = "to"
N = "journeys"
d = df[[SRC, DST, N]].dropna()
d = d[d[N] > 0]
nodes = list(dict.fromkeys(list(d[SRC].astype(str)) + list(d[DST].astype(str))))
index = {n: i for i, n in enumerate(nodes)}
step = lambda n: int(str(n).split(":")[0].split()[-1]) if str(n).split(":")[0].split()[-1].isdigit() else 0  # labels are "step: event"
events = sorted({str(n).split(":", 1)[-1].strip() for n in nodes})
colour = {e: PALETTE[i % len(PALETTE)] for i, e in enumerate(events)}
steps = sorted({step(n) for n in nodes})
size = {n: max(d.loc[d[SRC].astype(str) == n, N].sum(), d.loc[d[DST].astype(str) == n, N].sum()) for n in nodes}
total = max(sum(size[n] for n in nodes if step(n) == s) for s in steps)
gap = 0.03 * total
top, out_at, in_at = {}, {}, {}
for s in steps:
    y = 0.0
    for n in sorted((n for n in nodes if step(n) == s), key=lambda n: -size[n]):
        top[n] = out_at[n] = in_at[n] = y
        y += size[n] + gap
fig, ax = plt.subplots(figsize=(9, 5))
for _, r in d.sort_values(N, ascending=False).iterrows():  # ribbons: width = journeys
    a, b, w = str(r[SRC]), str(r[DST]), float(r[N])
    x = np.linspace(step(a) + 0.03, step(b) - 0.03, 40)
    t = (x - x[0]) / (x[-1] - x[0])
    ease = 3 * t**2 - 2 * t**3
    y0, y1 = out_at[a], in_at[b]
    ax.fill_between(x, y0 + (y1 - y0) * ease, y0 + w + (y1 - y0) * ease, color=colour[b.split(":", 1)[-1].strip()], alpha=0.3, linewidth=0)
    out_at[a] += w
    in_at[b] += w
for n in nodes:
    ax.fill_between([step(n) - 0.03, step(n) + 0.03], top[n], top[n] + size[n], color=colour[n.split(":", 1)[-1].strip()])
    ax.text(step(n) + 0.05, top[n] + size[n] / 2, f"{n.split(':', 1)[-1].strip()} {size[n]:.0f}", fontsize=7, va="center")
ax.invert_yaxis()
ax.set_xticks(steps, [f"step {s}" for s in steps])
ax.set_yticks([])
plt.show()

Needs pandas, numpy, matplotlib · reads sequence-sankey-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#shepard-diagram

Shepard diagram

How faithfully does an MDS map keep the original distances?

Demo data · seed 20261101 · 400 rows · default settings · 640 × 360

How to read it

  1. Read x as the original dissimilarity, y as the map distance.
  2. A tight rising band: the map keeps the order of distances.
  3. Read stress in the legend: lower is better.
  1. Callout 1: Monotone fit: map distances follow the original.
  2. Callout 2: A wide spread here: short distances are less faithful.
  3. Callout 3: Stress.

Watch out

  • Low stress in two dimensions doesn't make clusters real: pairs can still be misplaced.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
  • Kruskal stress-1 = √(Σ (distance − fit)² / Σ distance²); below 0.05 excellent, 0.1 fair, above 0.2 poor (Kruskal 1964).
  • Large maps show an evenly spaced sample of pairs; the stress in the legend is recomputed from the pairs shown.
# Shepard diagram — Codesplash Chart Lab (recipe "shepard-diagram")
# 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("shepard-diagram-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")
X = "dissimilarity"
Y = "map distance"
F = "monotone fit"
d = df.dropna(subset=[X, Y]).sort_values(X)
fig, ax = plt.subplots(figsize=(6, 4.5))
ax.scatter(d[X], d[Y], s=8, color=PALETTE[0], alpha=0.5, label="pairs of rows")
if F:
    ax.step(d[X], d[F], where="post", color=PALETTE[1], linewidth=1.6, label="monotone fit")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads shepard-diagram-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#topics-over-time

Topics over time

Which topics are growing or fading?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read a band's thickness as that topic's share or count in that period.
  2. A widening band is a rising topic; the bottom band is the easiest to read.
  3. Switch between share and counts: a share can fall while the count rises.
  1. Callout 1: The largest topic, at the bottom.
  2. Callout 2: A band that thins: this topic is fading.

Watch out

  • Topics come from a model, so check that a topic means the same thing throughout the period.

Defaults

Show
Share of each period
Shares show which topics rise relative to the rest, even if the total volume changes.
Also: Counts
Topics shown
6
Smaller topics are grouped into Other.
Range 2 to 12, step 1

Pinned in the code

  • Rows are summed per period and topic; topics are ranked by total weight, largest at the bottom.
  • Topics beyond the top N join Other. Periods are as given: bin dates before charting.
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")
# controls: mode=share, top=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("topics-over-time-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])

T = "month"
K = "topic"
W = "tickets"
TOP, SHARE = 6, True
d = df.dropna(subset=[T, K]).assign(_w=lambda f: f[W].astype(float) if W else 1.0)
totals = d.groupby(K)["_w"].sum().sort_values(ascending=False)
keep = list(totals.index[:TOP])
d["_k"] = d[K].where(d[K].isin(keep), "Other")
wide = d.pivot_table(index=T, columns="_k", values="_w", aggfunc="sum", fill_value=0).sort_index()
wide = wide[keep + (["Other"] if "Other" in wide else [])]  # largest topic at the bottom
if SHARE:
    wide = wide.div(wide.sum(axis=1), axis=0)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.stackplot(wide.index, wide.T.to_numpy(), labels=wide.columns, colors=PALETTE, alpha=0.85, hatch=[SERIES_HATCHES[i % 8] for i in range(wide.shape[1])], hatchcolor=HATCH_INK, linewidth=0)  # texture per topic, as in the app
ax.set_xlabel(T)
ax.set_ylabel("share" if SHARE else "count")
ax.legend(fontsize=8, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib · reads topics-over-time-demo.csv · app theme from the optional codesplash helper

Discover & forecasting

svg#latent-prior

Latent means against the prior

Does a variational autoencoder's latent space fill its N(0, I) prior, or leave holes and collapse?

Demo data · seed 20261101 · 150 rows · default settings · 640 × 360

How to read it

  1. Read each point as one row's position in the latent space (its posterior mean μ).
  2. The dashed rings are the prior's 1σ and 2σ circles; rows should spread across them without big empty regions.
  3. Clusters of colour show what the model separates; points far outside 2σ decode from places the prior rarely samples.
  1. Callout 1: The prior's centre.
  2. Callout 2: The 2σ ring.
  3. Callout 3: A group the model keeps together.

Watch out

  • Everything piled near the centre on one axis suggests that dimension collapsed onto the prior.
  • Holes inside the rings are regions that decode to rows unlike any in the data; generated rows can land there.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the engine's numbers as given (codesplash ↔ codesplashr torch twins); the chart computes nothing statistical.
  • Both axes span the same symmetric range around 0; the prior's rings are circles in latent units (they look oval when the plot isn't square).
  • Labels give the share of posterior means inside each ring next to the prior's mass (39.3% inside 1σ, 86.5% inside 2σ in two dimensions); means sit closer to 0 than draws because each row's own spread is left out.
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("latent-prior-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica"])

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 = "latent 1 (μ)"
Y = "latent 2 (μ)"
G = "species"
d = df.dropna(subset=[X, Y])
fig, ax = plt.subplots(figsize=(6, 6))
for i, name in enumerate(levels_of(d[G]) if G else [None]):
    s = d if name is None else d[d[G].astype(str) == name]
    ax.scatter(s[X], s[Y], s=10, alpha=0.75, label=name, linewidths=0, marker=SERIES_MARKERS[i % 8])  # marker shape per group, as in the app
theta = np.linspace(0, 2 * np.pi, 200)
r2 = d[X] ** 2 + d[Y] ** 2
for r in (1, 2):  # the N(0, I) prior's 1σ and 2σ rings; 39.3% and 86.5% of its mass lie inside
    ax.plot(r * np.cos(theta), r * np.sin(theta), color="grey", linestyle="--", linewidth=1)
    ax.annotate(f"{r}σ: {(r2 <= r * r).mean():.0%} inside (prior {1 - np.exp(-r * r / 2):.0%})", (r * 0.707, r * 0.707), fontsize=8, color="grey")
m = max(2.2, 1.05 * float(np.abs(d[[X, Y]].to_numpy()).max()))
ax.set_xlim(-m, m)
ax.set_ylim(-m, m)
ax.set_aspect("equal")
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads latent-prior-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

Headline numbers with change and targets: KPI tiles, sparklines, bullet charts, gauges, progress and variance to target.

8

KPI & dashboard widgets

svg#kpi-tile

KPI tile

What is the headline number now, and is it moving the right way?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read the big number: the latest period's value.
  2. Read the change below it, against the previous period.
  3. Read the sparkline for context and the bar for progress to target.
  1. Callout 1: The latest value.
  2. Callout 2: Change against the previous period.
  3. Callout 3: Recent shape.
  4. Callout 4: Progress to target.

Watch out

  • An unfinished latest period makes a comparison misleading; check the period before reacting.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Period
Month
The length of each period: day, week, month, quarter or year.
Also: Day · ISO week · Quarter · Year
Compare with the previous period
On
Show the change against the previous period under the value.
Sparkline periods
12
How many of the latest periods the sparkline shows.
Range 0 to 60, step 1
Good direction
Higher is better
Whether up or down counts as good, which sets the colours.
Also: Lower is better · Neutral
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1

Pinned in the code

  • With a time column the value is the aggregate over the latest period (the period containing the latest timestamp); the change is against the period before it, and % change = change / |previous| (none when the previous value is 0).
  • The sparkline shows the latest N periods; empty periods are skipped, not drawn as zero.
  • Progress = value / target, where the target is the target column aggregated the same way over the same rows (or the fixed target).
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
  • Periods are UTC calendar periods (ISO weeks start on Monday), like DuckDB date_trunc; the latest period may be partial.
  • Numbers round half to even (compact: 1 decimal on k/M/B/T); the change is coloured by the good direction.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# KPI tile — Codesplash Chart Lab (recipe "kpi-tile")
# controls: agg=sum, grain=month, compare=true, points=12, good=up, format=compact, target=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("kpi-tile-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1

AGG, GRAIN, POINTS, COMPARE, GOOD, STYLE = "sum", "month", 12, True, "up", "compact"
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
k = kpi(df, "date", "revenue", "target", GRAIN, AGG, POINTS, COMPARE)
target = k["target"] if k["target"] is not None and np.isfinite(k["target"]) else FIXED_TARGET
progress = k["value"] / target if target else None
label = "revenue · sum"
if k["period"] is None:
    caption = f"all rows (n = {k['n']:,})"
elif k["previous"] is not None:
    caption = f"{period_name(k['period'], GRAIN)} vs {period_name(k['prev_period'], GRAIN)}"
else:
    caption = period_name(k["period"], GRAIN)
delta_colour = {1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)]
target_text = f"{fmt_kpi(progress, 'percent', 0)} of target {fmt_kpi(target, STYLE)}" if target else None

fig = plt.figure(figsize=(6.4, 3.6))
fig.text(0.04, 0.88, label, fontsize=12, color=MUTED)
fig.text(0.04, 0.70, fmt_kpi(k["value"], STYLE), fontsize=40, fontweight="bold", color=FG)
fig.text(0.04, 0.61, fmt_delta(k['delta'], k['pct'], STYLE), fontsize=11, fontweight="bold", color=delta_colour)
fig.text(0.96, 0.61, caption, fontsize=11, color=MUTED, ha="right")
s = k["series"]
if s is not None and len(s) >= 2:  # sparkline: equal spacing per period, scaled to its own range
    ax = fig.add_axes([0.04, 0.2 if target else 0.06, 0.92, 0.33])
    xs = np.arange(len(s))
    ax.fill_between(xs, s["v"], s["v"].min(), color=COL, alpha=0.15, linewidth=0)
    ax.plot(xs, s["v"], color=COL, linewidth=2)
    ax.plot(xs[-1], s["v"].iloc[-1], "o", color=COL)
    ax.axis("off")
if target:  # progress to target
    fig.text(0.04, 0.095, target_text, fontsize=10, color=MUTED)
    bar = fig.add_axes([0.04, 0.05, 0.92, 0.025])
    bar.barh(0, 1, color=TRACK, height=1)
    bar.barh(0, min(max(progress, 0), 1), color=PASS if progress >= 1 else COL, height=1)
    bar.set_xlim(0, 1)
    bar.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads kpi-tile-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#sparkline

Sparkline

What is the recent shape of a measure at a glance?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read only the shape: there's no axis.
  2. Read the labelled minimum, maximum and last value.
  3. The shaded band marks the middle half.
  1. Callout 1: The maximum.
  2. Callout 2: The minimum.
  3. Callout 3: The latest value.

Watch out

  • Each sparkline scales to its own range, so two can't be compared by height.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Period
Month
The length of each period: day, week, month, quarter or year.
Also: Day · ISO week · Quarter · Year
Periods
24
How many of the latest periods to show.
Range 2 to 60, step 1
Band
Middle 50% of periods
What the shaded band around the line shows.
Also: None
Min / max markers
On
Label the lowest and highest points.
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • One point per period (the aggregate of its rows); the y range is the data range of the shown periods, so the line shows shape, not level.
  • Band: quartiles (type 7) of the shown period values — Tufte's “normal range”.
  • Minimum in the fail colour, maximum in the pass colour, last value as a dot and on the right.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
  • Periods are UTC calendar periods (ISO weeks start on Monday), like DuckDB date_trunc; the latest period may be partial.

Use with care

Sparklines show shape only: two sparklines side by side usually have different y ranges.

# Sparkline — Codesplash Chart Lab (recipe "sparkline")
# controls: agg=sum, grain=month, points=24, band=iqr, markers=true, format=compact
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("sparkline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1

AGG, GRAIN, POINTS, STYLE = "sum", "month", 24, "compact"
BAND, MARKERS = "iqr", True
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
s = period_series(df, "date", "revenue", GRAIN, AGG).tail(POINTS).dropna().reset_index(drop=True)
q1, q3 = s["v"].quantile([0.25, 0.75])  # the "normal range" band (type 7)
imin, imax = s["v"].idxmin(), s["v"].idxmax()

fig = plt.figure(figsize=(6.4, 1.6))
fig.text(0.01, 0.55, "revenue", fontsize=12, fontweight="bold", color=FG)
fig.text(0.01, 0.38, f"{AGG} per {GRAIN}", fontsize=9, color=MUTED)
ax = fig.add_axes([0.24, 0.12, 0.56, 0.76])
xs = np.arange(len(s))
if BAND == "iqr":
    ax.axhspan(q1, q3, color=MUTED, alpha=0.14, linewidth=0)
ax.plot(xs, s["v"], color=COL, linewidth=1.8)
if MARKERS:
    ax.plot(imin, s["v"][imin], "o", color=FAIL, markersize=5)
    ax.plot(imax, s["v"][imax], "o", color=PASS, markersize=5)
    ax.annotate(fmt_kpi(s["v"][imin], STYLE), (imin, s["v"][imin]), xytext=(0, -12), textcoords="offset points", ha="center", fontsize=8, color=MUTED)
    ax.annotate(fmt_kpi(s["v"][imax], STYLE), (imax, s["v"][imax]), xytext=(0, 6), textcoords="offset points", ha="center", fontsize=8, color=MUTED)
ax.plot(xs[-1], s["v"].iloc[-1], "o", color=COL, markersize=5)
ax.axis("off")
fig.text(0.99, 0.55, fmt_kpi(s["v"].iloc[-1], STYLE), fontsize=14, fontweight="bold", color=FG, ha="right")
fig.text(0.99, 0.38, period_name(s["t"].iloc[-1], GRAIN), fontsize=9, color=MUTED, ha="right")
plt.show()

Needs pandas, numpy, matplotlib · reads sparkline-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#bullet-chart

Bullet chart

How does each measure compare with its target and with qualitative ranges?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read the dark bar as the actual value.
  2. Read the tick as the target.
  3. Read the grey bands as poor, satisfactory and good ranges.
  1. Callout 1: Actual reaches past the target.
  2. Callout 2: The tick: the target.
  3. Callout 3: The grey bands: qualitative ranges.

Watch out

  • The bands (60, 80, 100%) are conventions. Change them if your targets work differently.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1
Qualitative bands
On
Shade bands for poor, satisfactory and good performance.
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • Actual and target per group are aggregated the same way (target column, else the fixed target).
  • Bands are poor (< 60% of target), satisfactory (60–80%) and good (80–100%), darkest first; the axis starts at zero.
  • Groups keep their stored level order (else first appearance); at most 12.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# Bullet chart — Codesplash Chart Lab (recipe "bullet-chart")
# controls: agg=sum, target=0, bands=true, format=compact
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("bullet-chart-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=["North", "South", "East", "West"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
    """Per group: the aggregate of the values and of the targets (or the fixed target)."""
    out = []
    for lv in levels:
        g = d[d[group].astype(str) == lv]
        t = agg(g[target], how) if target else fixed
        out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
    out = pd.DataFrame(out)
    out["variance"] = out["value"] - out["target"]
    out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
    out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
    return out
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, STYLE, GOOD = "sum", "compact", "up"
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df["region"], 12))
BANDS = [0.6, 0.8, 1.0]  # poor / satisfactory / good, as shares of target
SHOW_BANDS = True

top = np.nanmax(np.r_[rows["value"], rows["target"] * 1.15, 0])
fig, ax = plt.subplots(figsize=(8, 0.6 + 0.7 * len(rows)))
for i, r in rows.iloc[::-1].reset_index(drop=True).iterrows():
    t = r["target"]
    if SHOW_BANDS and np.isfinite(t) and t > 0:
        edges = [0] + [b * t for b in BANDS]
        for lo, hi, alpha in zip(edges[:-1], edges[1:], [0.32, 0.2, 0.1]):
            ax.barh(i, hi - lo, left=lo, height=0.8, color=MUTED, alpha=alpha, linewidth=0)
    ax.barh(i, r["value"], height=0.32, color=COL)
    if np.isfinite(t):
        ax.plot([t, t], [i - 0.3, i + 0.3], color=FG, linewidth=2.5)
    ax.text(top * 1.02, i, fmt_kpi(r["value"], STYLE), va="center", fontsize=9)
ax.set_yticks(range(len(rows)), rows["group"].iloc[::-1])
ax.set_xlim(0, top * 1.12)
ax.set_xlabel("revenue" + f" ({AGG})")
ax.spines[["top", "right", "left"]].set_visible(False)
ax.grid(False)
plt.show()

Needs pandas, numpy, matplotlib · reads bullet-chart-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#gauge

Gauge

How close is a measure to its target on a fixed scale?

Demo data · seed 20261101 · 92 rows · default settings · 640 × 360

How to read it

  1. Read the arc's length as the value on a fixed scale.
  2. Compare with the target tick.
  3. Read the coloured outer rim for the bands, if on.
  1. Callout 1: The value.
  2. Callout 2: The target tick.
  3. Callout 3: The scale's maximum.

Watch out

  • A gauge uses much space for one number and hides any trend. Pair it with a sparkline.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1
Scale maximum (0 = auto)
0
Auto: a round number ≥ 125% of the target and ≥ the value
Range 0 to 1,000,000,000,000, step 1
Target bands
On
Colour the dial by distance from the target.
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • The arc's angle is proportional to value / scale maximum (0 at the left end, the maximum at the right).
  • Bands outside the arc mark < 60%, 60–80% and 80–100% of target; the arc turns the pass colour when the target is met.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.

Use with care

Gauges use a lot of space for one number; a bullet chart or a KPI tile with a target bar shows the same information more compactly and comparably.

# Gauge — Codesplash Chart Lab (recipe "gauge")
# controls: agg=sum, target=0, max=0, bands=true, format=compact
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

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("gauge-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
    """Per group: the aggregate of the values and of the targets (or the fixed target)."""
    out = []
    for lv in levels:
        g = d[d[group].astype(str) == lv]
        t = agg(g[target], how) if target else fixed
        out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
    out = pd.DataFrame(out)
    out["variance"] = out["value"] - out["target"]
    out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
    out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
    return out
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, STYLE, SCALE_MAX, SHOW_BANDS = "sum", "compact", None, True
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df.assign(_all="revenue"), "_all", "revenue", "target", AGG, FIXED_TARGET, ["revenue"])

def nice_ceil(v):
    """A round scale maximum: 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8 or 10 × a power of ten."""
    if not v > 0:
        return 1.0
    p = 10 ** np.floor(np.log10(v))
    return next(m * p for m in [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10] if m * p >= v)

rows["max"] = [SCALE_MAX or nice_ceil(max(v, (0 if np.isnan(t) else t) * 1.25, 0)) for v, t in zip(rows["value"], rows["target"])]

fig, axes = plt.subplots(1, len(rows), figsize=(4 * len(rows), 3), squeeze=False)
for ax, r in zip(axes[0], rows.itertuples()):
    frac = min(max(r.value / r.max, 0), 1) if np.isfinite(r.value) else 0
    met = np.isfinite(r.target) and r.value >= r.target
    ax.add_patch(Wedge((0, 0), 1, 0, 180, width=0.2, color=TRACK))  # angles: 180° = 0, 0° = scale max
    ax.add_patch(Wedge((0, 0), 1, 180 - 180 * frac, 180, width=0.2, color=PASS if met else COL))
    if np.isfinite(r.target):
        a = np.pi * (1 - min(max(r.target / r.max, 0), 1))
        ax.plot([0.76 * np.cos(a), 1.04 * np.cos(a)], [0.76 * np.sin(a), 1.04 * np.sin(a)], color=FG, linewidth=2.5)
        if SHOW_BANDS:  # zones run bad → good along the arc, split by small gaps so they read without colour (as in the app)
            for k, (lo, hi, colour) in enumerate([(0, 0.6, FAIL), (0.6, 0.8, MUTED), (0.8, 1.0, PASS)]):
                a0 = 180 - 180 * min(hi * r.target / r.max, 1) + (0.8 if k < 2 else 0)
                a1 = 180 - 180 * min(lo * r.target / r.max, 1) - (0.8 if k > 0 else 0)
                if a1 > a0:
                    ax.add_patch(Wedge((0, 0), 1.07, a0, a1, width=0.025, color=colour, alpha=0.7))
    ax.text(0, 0.08, fmt_kpi(r.value, STYLE), ha="center", fontsize=20, fontweight="bold", color=FG)
    sub = f"{fmt_kpi(r.progress, 'percent', 0)} of {fmt_kpi(r.target, STYLE)}" if np.isfinite(r.target) else r.group
    ax.text(0, -0.12, sub, ha="center", fontsize=9, color=MUTED)
    ax.text(-0.9, -0.1, "0", ha="center", fontsize=8, color=MUTED)
    ax.text(0.9, -0.1, fmt_kpi(r.max, "compact", 0), ha="center", fontsize=8, color=MUTED)
    ax.set_title(r.group if len(rows) > 1 else "", fontsize=11)
    ax.set_xlim(-1.15, 1.15)
    ax.set_ylim(-0.25, 1.15)
    ax.set_aspect("equal")
    ax.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads gauge-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#target-progress

Progress to target

How far along is each group towards its target?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read each bar as actual as a share of target.
  2. Compare with the 100% line.
  3. Colour tells you who met the target.
  1. Callout 1: Past the line: target met.
  2. Callout 2: The 100% line.
  3. Callout 3: Share of target, with values.

Watch out

  • Targets vary by group: a big share against a small target can be less than it looks.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1
Sort
Progress (highest first)
How rows are sorted.
Also: Actual (largest first) · Group order
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • Progress = actual / target per group, both aggregated the same way; groups without a target show “no target”.
  • The axis runs from 0 to at least 120% so the 100% line is always visible; bars beyond the axis are capped.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# Progress to target — Codesplash Chart Lab (recipe "target-progress")
# controls: agg=sum, target=0, sort=progress, format=compact
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("target-progress-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=["North", "South", "East", "West"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
    """Per group: the aggregate of the values and of the targets (or the fixed target)."""
    out = []
    for lv in levels:
        g = d[d[group].astype(str) == lv]
        t = agg(g[target], how) if target else fixed
        out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
    out = pd.DataFrame(out)
    out["variance"] = out["value"] - out["target"]
    out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
    out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
    return out
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, STYLE, GOOD = "sum", "compact", "up"
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df["region"], 12))
SORT = "progress"

if SORT != "order":
    rows = rows.sort_values("value" if SORT == "value" else "progress", ascending=False, na_position="last")
top = max(1.2, np.ceil(np.nanmax(np.r_[rows["progress"], 0]) * 10) / 10)
fig, ax = plt.subplots(figsize=(8, 0.6 + 0.6 * len(rows)))
ys = np.arange(len(rows))[::-1]
ax.barh(ys, top, color=MUTED, alpha=0.08, height=0.7)
ax.barh(ys, np.minimum(rows["progress"].fillna(0), top), height=0.7, color=[PASS if p >= 1 else COL for p in rows["progress"].fillna(0)])
ax.axvline(1, color=MUTED, linestyle="--", linewidth=1)
for y, r in zip(ys, rows.itertuples()):
    text = "no target" if not np.isfinite(r.target) else f"{fmt_kpi(r.progress, 'percent', 0)}  {fmt_kpi(r.value)} / {fmt_kpi(r.target)}"
    ax.text(top * 1.01, y, text, va="center", fontsize=9)
ax.set_yticks(ys, rows["group"])
ax.set_xlim(0, top)
ax.xaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
ax.set_xlabel("% of target")
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Needs pandas, numpy, matplotlib · reads target-progress-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#target-variance

Variance to target

Which groups are ahead of or behind target, and by how much?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read bars from the centre: right is above target, left is below.
  2. Read colour as better or worse than target.
  3. Compare sizes for how far each is from its target.
  1. Callout 1: Better than target.
  2. Callout 2: Worse than target.
  3. Callout 3: The zero line: on target.

Watch out

  • Percent gaps exaggerate small targets; check the absolute difference too.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Show
% of target
Which view to draw.
Also: Absolute difference
Sort
Variance (largest first)
How rows are sorted.
Also: Actual (largest first) · Group order
Good direction
Higher is better
Whether up or down counts as good, which sets the colours.
Also: Lower is better · Neutral
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • Variance = actual − target; % variance = (actual − target) / |target| (none when the target is 0).
  • Bars above target are in the pass colour when higher is better (fail when lower is better); the axis is symmetric around zero.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# Variance to target — Codesplash Chart Lab (recipe "target-variance")
# controls: agg=sum, mode=percent, sort=variance, good=up, format=compact
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("target-variance-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=["North", "South", "East", "West"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
    """Per group: the aggregate of the values and of the targets (or the fixed target)."""
    out = []
    for lv in levels:
        g = d[d[group].astype(str) == lv]
        t = agg(g[target], how) if target else fixed
        out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
    out = pd.DataFrame(out)
    out["variance"] = out["value"] - out["target"]
    out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
    out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
    return out
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, STYLE, GOOD = "sum", "compact", "up"
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df["region"], 12))
MODE, SORT = "percent", "variance"

key = "variance_pct" if MODE == "percent" else "variance"
if SORT != "order":
    rows = rows.sort_values("value" if SORT == "value" else key, ascending=False, na_position="last")
v = rows[key]
m = max(np.nanmax(np.r_[v.abs(), 0]), 0.05 if MODE == "percent" else 1) * 1.25
fmt = (lambda x: f"{'+' if x > 0 else ''}{fmt_kpi(x, 'percent', 1)}") if MODE == "percent" else (lambda x: f"{'+' if x > 0 else ''}{fmt_kpi(x, STYLE)}")
fig, ax = plt.subplots(figsize=(8, 0.6 + 0.6 * len(rows)))
ys = np.arange(len(rows))[::-1]
colours = [MUTED if tone_of(x, GOOD) == 0 else (PASS if tone_of(x, GOOD) > 0 else FAIL) for x in v.fillna(0)]
ax.barh(ys, v.fillna(0), color=colours, height=0.7)
ax.axvline(0, color=MUTED, linewidth=1)
for y, x in zip(ys, v):
    ax.text(x if np.isfinite(x) else 0, y, fmt(x) if np.isfinite(x) else " no target", va="center", ha="left" if not np.isfinite(x) or x >= 0 else "right", fontsize=9)
ax.set_yticks(ys, rows["group"])
ax.set_xlim(-m, m)
ax.set_xlabel("Actual vs target (%)" if MODE == "percent" else "Actual − target")
ax.spines[["top", "right"]].set_visible(False)
plt.show()

Needs pandas, numpy, matplotlib · reads target-variance-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#kpi-grid

KPI grid

How is the same KPI doing in every group?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Compare the big numbers across tiles.
  2. Read each tile's change and progress bar.
  3. Sparklines share no scale, so use them for each group's own shape.
  1. Callout 1: The group's latest value.
  2. Callout 2: Its change.
  3. Callout 3: Its progress to target.

Watch out

  • Groups of very different sizes make the numbers hard to compare. Consider rates.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Period
Month
The length of each period: day, week, month, quarter or year.
Also: Day · ISO week · Quarter · Year
Compare with the previous period
On
Show the change against the previous period under the value.
Sparkline periods
12
How many of the latest periods the sparkline shows.
Range 0 to 60, step 1
Good direction
Higher is better
Whether up or down counts as good, which sets the colours.
Also: Lower is better · Neutral
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1
Columns (0 = auto)
0
How many tiles per row; 0 fits them to the width.
Range 0 to 6, step 1

Pinned in the code

  • Each tile is the KPI tile computed on its group's rows (latest period of the whole group, change vs the period before it).
  • Sparklines are scaled per tile (shape, not level); compare levels with the values.
  • Groups keep their stored level order (else by frequency); at most 12.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
  • Periods are UTC calendar periods (ISO weeks start on Monday), like DuckDB date_trunc; the latest period may be partial.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# KPI grid — Codesplash Chart Lab (recipe "kpi-grid")
# controls: agg=sum, grain=month, compare=true, points=12, good=up, format=compact, target=0, columns=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("kpi-grid-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, GRAIN, POINTS, COMPARE, GOOD, STYLE = "sum", "month", 12, True, "up", "compact"
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
tiles = [(lv, kpi(df[df["region"].astype(str) == lv], "date", "revenue", "target", GRAIN, AGG, POINTS, COMPARE))
         for lv in freq_levels(df["region"], 12)]
FIXED_TARGET = None

ncol = int(np.ceil(len(tiles) / np.ceil(len(tiles) / 3)))  # balanced rows of at most 3, like the app
nrow = int(np.ceil(len(tiles) / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(3.2 * ncol, 2.2 * nrow), squeeze=False)
for ax in axes.flat[len(tiles):]:
    ax.axis("off")
for ax, (name, k) in zip(axes.flat, tiles):
    ax.axis("off")
    ax.text(0, 1, name, transform=ax.transAxes, fontsize=10, color=MUTED, va="top")
    ax.text(0, 0.86, fmt_kpi(k["value"], STYLE), transform=ax.transAxes, fontsize=20, fontweight="bold", color=FG, va="top")
    if k["delta"] is not None:
        ax.text(0, 0.62, f"{fmt_delta(k['delta'], k['pct'], STYLE)}  vs {period_name(k['prev_period'], GRAIN)}", transform=ax.transAxes,
                fontsize=8, color={1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)], va="top")
    s = k["series"]
    if s is not None and len(s) >= 2:
        inset = ax.inset_axes([0, 0.08, 1, 0.42])
        xs = np.arange(len(s))
        inset.fill_between(xs, s["v"], s["v"].min(), color=COL, alpha=0.15, linewidth=0)
        inset.plot(xs, s["v"], color=COL, linewidth=1.5)
        inset.plot(xs[-1], s["v"].iloc[-1], "o", color=COL, markersize=3)
        inset.axis("off")
    target = k["target"] if k["target"] is not None and np.isfinite(k["target"]) else FIXED_TARGET
    if target:
        prog = k["value"] / target
        ax.text(0, 0.02, f"{fmt_kpi(prog, 'percent', 0)} of target {fmt_kpi(target, STYLE)}", transform=ax.transAxes, fontsize=7, color=MUTED)
        ax.plot([0, 1], [-0.04, -0.04], transform=ax.transAxes, color=TRACK, linewidth=4, solid_capstyle="round", clip_on=False)
        ax.plot([0, min(max(prog, 0), 1)], [-0.04, -0.04], transform=ax.transAxes, color=PASS if prog >= 1 else COL, linewidth=4, solid_capstyle="round", clip_on=False)
plt.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads kpi-grid-demo.csv · app theme from the optional codesplash helper

KPI & dashboard widgets

svg#sparkline-table

Sparkline table

How do many groups compare on level, recent change and trend?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360

How to read it

  1. Read each row across: shape, latest, change, range.
  2. Sort by the column you care about.
  3. Compare change with the row's minimum and maximum to judge whether it's unusual.
  1. Callout 1: This group's recent shape.
  2. Callout 2: The change against the previous period.
  3. Callout 3: The range over the shown periods.

Watch out

  • A big percent change on a small base can be noise.

Defaults

Aggregate
Sum
How rows combine into one number per group or period, such as a sum or a mean.
Also: Mean · Median · Count · Minimum · Maximum
Period
Month
The length of each period: day, week, month, quarter or year.
Also: Day · ISO week · Quarter · Year
Periods
24
How many of the latest periods to show.
Range 2 to 60, step 1
Good direction
Higher is better
Whether up or down counts as good, which sets the colours.
Also: Lower is better · Neutral
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)

Pinned in the code

  • Latest = the aggregate over the group's latest period; change = % change against the period before it, coloured by the good direction.
  • Min and max are over the periods shown in the sparkline; sparklines are scaled per row.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
  • Periods are UTC calendar periods (ISO weeks start on Monday), like DuckDB date_trunc; the latest period may be partial.

Use with care

Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.

# Sparkline table — Codesplash Chart Lab (recipe "sparkline-table")
# controls: agg=sum, grain=month, points=24, good=up, format=compact
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("sparkline-table-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])

GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
        "quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}


def period_start(t, grain):
    """UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
    day = t.dt.floor("D")
    if grain == "day":
        return day
    if grain == "week":
        return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
    return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time


def agg(s, how):
    """sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
    s = pd.to_numeric(s, errors="coerce").dropna()
    if how == "count":
        return float(len(s))
    if s.empty:
        return float("nan")
    return float(s.quantile(0.5) if how == "median" else getattr(s, how)())


def period_series(d, time, value, grain, how):
    """One row per period (t = period start, v = the aggregate), oldest first."""
    d = d.dropna(subset=[time])
    v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
    return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)


def kpi(d, time, value, target, grain, how, points, compare):
    """The latest period against the previous one, the sparkline series and the target."""
    if time is None:
        return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
                    period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
    s = period_series(d, time, value, grain, how)
    latest = s.iloc[-1]
    prev_t = latest["t"] - STEP[grain]
    prev = s.loc[s["t"] == prev_t, "v"]
    previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
    delta = float(latest["v"]) - previous if previous is not None else None
    pct = delta / abs(previous) if delta is not None and previous != 0 else None
    rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
    return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
                prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
                target=agg(rows[target], how) if target else None)


def _group(a, d):
    return f"{a:,.{d}f}"


def _trim(s):
    return s.rstrip("0").rstrip(".") if "." in s else s


def _is_zero(s):
    return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")


def _kpi_body(v, style, decimals, currency):
    cur = (currency or "USD").strip().upper() or "USD"
    a = abs(v)
    if decimals is None:
        decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
                    "currency": 0 if cur in ("JPY", "KRW") else 2}[style]
    if style == "percent":
        return _group(a * 100, decimals) + "%"
    if style == "currency":
        return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
    if style == "compact":
        units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
        i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
        while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
            i += 1  # a mantissa that rounds to 1000 moves up a unit
        return _trim(_group(a / units[i][0], decimals)) + units[i][1]
    return _group(a, decimals)


def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
    """The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
    true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
    if v is None or not np.isfinite(v):
        return "—"
    text = _kpi_body(v, style, decimals, currency)
    return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix


def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
    """A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
    if delta is None:
        return ""
    if not np.isfinite(delta):
        return "—"
    if style == "percent":
        text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
    else:
        text = _kpi_body(abs(delta), style, decimals, currency)
    out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
    if pct is not None and np.isfinite(pct):
        pt = _group(abs(pct) * 100, 1)
        out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
    return out


def period_name(t, grain):
    if t is None:
        return ""
    t = pd.Timestamp(t)
    return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
            "quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]


def tone_of(delta, good):
    """1 = good change, -1 = bad, 0 = neutral or none."""
    if delta is None or delta == 0 or good == "neutral":
        return 0
    return 1 if (delta > 0) == (good == "up") else -1
def freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]

AGG, GRAIN, POINTS, COMPARE, GOOD, STYLE = "sum", "month", 24, True, "up", "compact"
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
tiles = [(lv, kpi(df[df["region"].astype(str) == lv], "date", "revenue", None, GRAIN, AGG, POINTS, COMPARE))
         for lv in freq_levels(df["region"], 12)]

n = len(tiles)
fig = plt.figure(figsize=(8, 0.5 + 0.55 * n))
heads = [(0.01, "Group", "left"), (0.2, f"{AGG} per {GRAIN}", "left"), (0.66, "Latest", "right"), (0.78, "Change", "right"), (0.89, "Min", "right"), (0.99, "Max", "right")]
for x, text, ha in heads:
    fig.text(x, 1 - 0.3 / (0.5 + 0.55 * n), text, fontsize=9, fontweight="bold", color=MUTED, ha=ha)
for i, (name, k) in enumerate(tiles):
    y = 1 - (0.5 + 0.55 * (i + 0.5)) / (0.5 + 0.55 * n)
    s = k["series"]
    vals = s["v"].dropna() if s is not None else pd.Series(dtype=float)
    fig.text(0.01, y, name, fontsize=10, va="center")
    if len(vals) >= 2:
        ax = fig.add_axes([0.2, y - 0.35 / (0.5 + 0.55 * n), 0.36, 0.7 / (0.5 + 0.55 * n)])
        ax.plot(np.arange(len(s)), s["v"], color=COL, linewidth=1.4)
        ax.plot(len(s) - 1, s["v"].iloc[-1], "o", color=COL, markersize=3)
        ax.axis("off")
    change = "—" if k["pct"] is None else ("+" if k["pct"] > 0 and not _is_zero(fmt_kpi(k["pct"], "percent", 1)) else "") + fmt_kpi(k["pct"], "percent", 1)
    fig.text(0.66, y, fmt_kpi(k["value"], STYLE), fontsize=10, fontweight="bold", ha="right", va="center")
    fig.text(0.78, y, change, fontsize=10, ha="right", va="center", color={1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)])
    fig.text(0.89, y, fmt_kpi(vals.min() if len(vals) else None, STYLE), fontsize=10, ha="right", va="center", color=MUTED)
    fig.text(0.99, y, fmt_kpi(vals.max() if len(vals) else None, STYLE), fontsize=10, ha="right", va="center", color=MUTED)
plt.show()

Needs pandas, numpy, matplotlib · reads sparkline-table-demo.csv · app theme from the optional codesplash helper

Causal inference

Balance and overlap, event studies, regression discontinuity, synthetic control gaps, uplift (Qini) curves and bias contours — the Causal studio's charts.

9

Causal inference

svg#love-plot

Covariate balance (love plot)

After matching or weighting, are treated and control groups alike on every covariate?

Demo data · seed 20261101 · 30 rows · default settings · 640 × 360

How to read it

  1. Read each row as one covariate's imbalance: the standardized difference between groups.
  2. Hollow points are before adjustment, filled ones after.
  3. After adjustment, points should sit inside the threshold band.
  1. Callout 1: Before adjustment: imbalanced.
  2. Callout 2: After adjustment: balanced.
  3. Callout 3: The threshold band.

Watch out

  • Balance on measured covariates says nothing about unmeasured ones.

Defaults

Balance threshold
0.1
The standardized difference below which a covariate counts as balanced; 0.1 is a common choice.
Range 0.01 to 1, step 0.01
Absolute differences
On
Plot the size of each imbalance, ignoring its sign.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Covariates are sorted by |SMD| in the first stage (largest at the top); the first stage is drawn hollow, later stages filled and joined by a grey line per covariate.
  • The shaded region is |SMD| ≤ threshold (0.1 by convention; Austin 2009). Binary covariates use the raw difference in proportions when the engine follows cobalt's convention.
# Covariate balance (love plot) — Codesplash Chart Lab (recipe "love-plot")
# controls: threshold=0.1, absolute=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("love-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["stage"] = pd.Categorical(df["stage"].astype("string"), categories=["Before", "Nearest-neighbour matching", "Entropy balancing"])

_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)))
COV = "covariate"
SMD = "standardized mean difference"
STAGE = "stage"
THRESHOLD, ABSOLUTE = 0.1, True
d = df.dropna(subset=[COV, SMD]).copy()
d["shown"] = d[SMD].abs() if ABSOLUTE else d[SMD]
stages = levels_of(d[STAGE]) if STAGE else [""]
d["_stage"] = d[STAGE].astype(str) if STAGE else ""
first = d[d["_stage"] == str(stages[0])].assign(a=lambda t: t[SMD].abs()).sort_values("a")
order = list(dict.fromkeys(first[COV].astype(str))) + [v for v in d[COV].astype(str).unique() if v not in set(first[COV].astype(str))]
ypos = {v: i for i, v in enumerate(order)}  # largest first-stage |SMD| at the top
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axvspan(0 if ABSOLUTE else -THRESHOLD, THRESHOLD, color="#19966e", alpha=0.08, lw=0)
for t in ([THRESHOLD] if ABSOLUTE else [-THRESHOLD, THRESHOLD]):
    ax.axvline(t, color=REF, linestyle="--", linewidth=1)
for cov, g in d.groupby(COV, observed=True):
    ax.plot(g["shown"], [ypos[str(cov)]] * len(g), color=GREY, linewidth=1.2, zorder=1)
for j, st in enumerate(stages):
    g = d[d["_stage"] == str(st)]
    ys = [ypos[str(v)] for v in g[COV]]
    if j == 0:
        ax.scatter(g["shown"], ys, s=34, facecolors="none", edgecolors="grey", label=st or "SMD", zorder=2)
    else:
        ax.scatter(g["shown"], ys, s=30, color=PALETTE[(j - 1) % len(PALETTE)], label=st, zorder=3)
ax.set_yticks(range(len(order)), order)
ax.set_xlabel(("|" + SMD + "|") if ABSOLUTE else SMD)
ax.legend(fontsize=8, loc="lower right")
plt.show()

Needs pandas, numpy, matplotlib · reads love-plot-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#event-study

Event study

Were treated and control units on parallel paths before treatment, and how did the effect evolve after?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Read points left of zero: before treatment. They should hover around zero.
  2. Read points right of zero: the effect at each period after.
  3. Check the intervals: do pre-period intervals stay away from zero?
  1. Callout 1: Pre-period: flat around zero supports parallel trends.
  2. Callout 2: The reference period.
  3. Callout 3: The effect grows after treatment.

Watch out

  • Flat pre-trends don't prove parallel trends would have continued; test sensitivity.

Defaults

Reference (omitted) period
-1
Send null when the design has no omitted period.
Range -50 to 50, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • The reference period is drawn hollow at 0 (its coefficient is normalized away); the dashed line marks treatment onset half a period after it.
  • Pre-period coefficients near zero support (but cannot prove) parallel trends; the engine reports the joint pre-trend test and HonestDiD bounds separately.
  • Several estimators or cohorts are dodged horizontally so their intervals do not overlap.
# Event study — Codesplash Chart Lab (recipe "event-study")
# controls: reference=-1
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("event-study-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["estimator"] = pd.Categorical(df["estimator"].astype("string"), categories=["TWFE", "Callaway–Sant'Anna"])

_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)))
T = "years relative to adoption"
EST = "effect on employment (pp)"
LO = "ci_low"
HI = "ci_high"
G = "estimator"
REFERENCE = -1  # omitted period, drawn hollow at 0
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values(T)))
fig, ax = plt.subplots(figsize=(8, 4.5))
onset = (REFERENCE if REFERENCE is not None else -1) + 0.5
ax.axvspan(df[T].min() - 0.6, onset, color="grey", alpha=0.06, lw=0)
ax.axhline(0, color="grey", linewidth=0.8)
ax.axvline(onset, color=REF, linestyle="--", linewidth=1)
k = len(series)
for i, (name, d) in enumerate(series):
    off = (i - (k - 1) / 2) * 0.16 if k > 1 else 0
    col = PALETTE[i % len(PALETTE)]
    ax.errorbar(d[T] + off, d[EST], yerr=[d[EST] - d[LO], d[HI] - d[EST]], fmt="o-", color=col, ms=5, lw=1, elinewidth=1.6, label=name or None)
    if REFERENCE is not None and not (d[T] == REFERENCE).any():
        ax.plot([REFERENCE + off], [0], "o", mfc="white", mec=col, ms=6)
ax.set_xlabel(T)
ax.set_ylabel(EST)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads event-study-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#rdd-plot

Regression discontinuity

Does the outcome jump where the running variable crosses the cutoff?

Demo data · seed 20261101 · 82 rows · default settings · 640 × 360

How to read it

  1. Read the dots as binned means on each side of the cutoff.
  2. Look for a jump in the fit lines at the cutoff.
  3. Compare the jump with the bands around it.
  1. Callout 1: The jump at the cutoff: the estimated effect.
  2. Callout 2: The local fit below the cutoff.
  3. 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

Causal inference

svg#synth-gap

Synthetic control gaps

Did the treated unit diverge from its synthetic control more than placebo units did?

Demo data · seed 20261101 · 961 rows · default settings · 640 × 360

How to read it

  1. Read the coloured line as the treated unit's gap from its synthetic control.
  2. Grey lines are placebo units: what gaps happen by chance.
  3. A real effect drops outside the grey after the intervention.
  1. Callout 1: The intervention.
  2. Callout 2: The treated unit diverges from the placebos.
  3. Callout 3: Before: a small gap means a good match.

Watch out

  • A poor pre-period fit undermines the comparison: check pre-period gaps first.

Defaults

Intervention time
0
When the treatment began.
Range -10,000,000,000,000 to 10,000,000,000,000, step 1
Mark the intervention
On
Draw a vertical line at the intervention.
Drop placebos with pre-RMSPE > k × treated (0 = keep all)
5
Hide placebo units that fit poorly before treatment, since they tell you little.
Range 0 to 50, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • RMSPE is computed from the gaps as sent: pre-period t < intervention, post-period t ≥ intervention; the p-value is the treated unit's rank of post/pre RMSPE among the units shown divided by their number (Abadie, Diamond & Hainmueller 2010).
  • Placebos whose pre-period fit is poor (pre-RMSPE above k times the treated unit's; k = 5 in the original study) are dropped from the display and the rank.
# Synthetic control gaps — Codesplash Chart Lab (recipe "synth-gap")
# controls: intervention=0, show_intervention=true, max_pre=5
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("synth-gap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["state"] = pd.Categorical(df["state"].astype("string"), categories=["California", "State 01", "State 02", "State 03", "State 04", "State 05", "State 06", "State 07", "State 08", "State 09", "State 10", "State 11", "State 12", "State 13", "State 14", "State 15", "State 16", "State 17", "State 18", "State 19", "State 20", "State 21", "State 22", "State 23", "State 24", "State 25", "State 26", "State 27", "State 28", "State 29", "State 30"])

_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")
T = "years since program"
GAP = "gap in packs per capita"
UNIT = "state"
TR = "treated"
INTERVENTION = 0
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
for unit, d in df.dropna(subset=[T, GAP]).sort_values(T).groupby(UNIT, observed=True):
    treated = bool(d[TR].astype(bool).any())
    ax.plot(d[T], d[GAP], color=PALETTE[0] if treated else "grey", alpha=1 if treated else 0.35, linewidth=2.4 if treated else 1, label=f"{unit} (treated)" if treated else None, zorder=3 if treated else 1)
if INTERVENTION is not None:
    ax.axvline(INTERVENTION, color=REF, linestyle="--", linewidth=1)
ax.set_xlabel(T)
ax.set_ylabel(GAP)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads synth-gap-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#overlap-density

Propensity score overlap

Do treated and control units share a range of propensity scores (overlap / positivity)?

Demo data · seed 20261101 · 900 rows · default settings · 640 × 360

How to read it

  1. Read the top and bottom histograms as each group's propensity scores.
  2. Check that they cover the same range: that's the shaded common support.
  3. Compare the outline after weighting.
  1. Callout 1: Treated units.
  2. Callout 2: Control units.
  3. Callout 3: The common-support region.

Watch out

  • Few controls at high propensity scores makes results depend on extreme weights.

Defaults

Mirror the second group
On
Flip the second group below the axis, so shapes can be compared.
Bins
25
How many bins to divide the range into.
Range 5 to 80, step 1

Pinned in the code

  • Draws the scores the engine estimated; the chart bins them on shared edges ([0, 1] when every score lies in it) and scales each group to a density.
  • Common support = [max of the group minimums, min of the group maximums]; little mass outside it means weights and matches rely less on extrapolation.
  • With a weight role, the outlines are the weighted densities (e.g. ATT or overlap weights) on the same bins.
# Propensity score overlap — Codesplash Chart Lab (recipe "overlap-density")
# controls: mirrored=true, bins=25
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("overlap-density-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["treated", "control"])

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)))
S = "propensity score"
G = "group"
W = "ATT weight"
BINS, MIRRORED = 25, True
d = df.dropna(subset=[S, G])
groups = levels_of(d[G].astype(str))[:2]
lo, hi = (0, 1) if d[S].between(0, 1).all() else (d[S].min(), d[S].max())
edges = np.linspace(lo, hi, BINS + 1)  # shared edges
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, g in enumerate(groups):
    s = d.loc[d[G].astype(str) == g, S]
    dens, _ = np.histogram(s, bins=edges, density=True)
    sign = -1 if (MIRRORED and i == 1) else 1
    ax.bar(edges[:-1], sign * dens, width=np.diff(edges), align="edge", color=PALETTE[i], alpha=0.65, label=g)
    if W:
        wd, _ = np.histogram(s, bins=edges, weights=d.loc[d[G].astype(str) == g, W], density=True)
        ax.stairs(sign * wd, edges, color="black", linewidth=1.2)
ax.axhline(0, color="grey", linewidth=0.8)
ax.set_xlabel(S)
ax.set_ylabel("density")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads overlap-density-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#qini-curve

Qini curve

If we treat the units with the highest predicted uplift first, how much more effect do we get than targeting at random?

Demo data · seed 20261101 · 84 rows · default settings · 640 × 360

How to read it

  1. Read x as the share targeted, highest predicted uplift first.
  2. Read y as the incremental gain.
  3. The area between a curve and the diagonal is its Qini: bigger is better.
  1. Callout 1: This model's gain curve.
  2. Callout 2: Random targeting.
  3. Callout 3: The best possible targeting.

Watch out

  • Uplift needs randomized (or carefully adjusted) data to be trusted.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Curves named random/optimal (also perfect/oracle) are drawn as references; without a random curve, the line from the origin to the first model's end point is used.
  • Qini coefficient (legend) = area between the model curve and the random line by the trapezoid rule over the model's points; the engine's RATE/AUUC values are reported separately.
# Qini curve — Codesplash Chart Lab (recipe "qini-curve")
# 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("qini-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["curve"] = pd.Categorical(df["curve"].astype("string"), categories=["Causal forest", "X-learner", "random", "optimal"])

_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)))
F = "share of customers targeted"
GAIN = "incremental customers retained"
CURVE = "curve"
groups = levels_of(df[CURVE]) if CURVE else [None]
series = []
for name in groups:
    d = df if name is None else df[df[CURVE].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[F]).sort_values(F)))
fig, ax = plt.subplots(figsize=(8, 4.5))
k = 0
for name, d in series:
    low = str(name).lower()
    if "random" in low:
        ax.plot(d[F], d[GAIN], color=REF, linestyle="--", linewidth=1, label=name)
    elif any(w in low for w in ("optimal", "perfect", "oracle")):
        ax.plot(d[F], d[GAIN], color="grey", linestyle=":", linewidth=1.4, label=name)
    else:
        ax.plot(d[F], d[GAIN], color=PALETTE[k % len(PALETTE)], linewidth=2, label=name or GAIN)
        k += 1
if not any("random" in str(n).lower() for n, _ in series):
    end = series[0][1].iloc[-1]
    ax.plot([0, end[F]], [0, end[GAIN]], color=REF, linestyle="--", linewidth=1, label="random targeting")
ax.set_xlabel(F)
ax.set_ylabel(GAIN)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads qini-curve-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#contour-grid

Contour grid

How does a quantity change over two inputs — where is it zero, where is it highest?

Demo data · seed 20261101 · 679 rows · default settings · 640 × 360

How to read it

  1. Read colour as the value across two inputs.
  2. Follow the bold zero contour: where the conclusion flips.
  3. Check the labelled points: benchmarks for how strong an unmeasured confounder would be.
  1. Callout 1: Stronger red: a larger bias.
  2. Callout 2: Benchmark points.
  3. Callout 3: Colour scale.

Watch out

  • Benchmarks assume unmeasured confounders resemble measured ones, which may not hold.

Defaults

Contour levels
10
How many contour bands to draw.
Range 3 to 30, step 1
Emphasize the zero contour
Off
Draw the line where the value is zero in bold: where the conclusion flips.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • The grid rows form a lattice over their distinct x and y values; bands are marching squares (d3-contour) at k equally spaced levels strictly between the minimum and maximum, plus 0 when 'zero contour' is on.
  • A diverging palette is used when the values span zero (blue above, red below), else a sequential one.
  • Sensemakr: x = partial R² of the confounder with the treatment, y = with the outcome, z = adjusted estimate; the dashed zero contour is where the effect would vanish, and points are the benchmark confounders.
# Contour grid — Codesplash Chart Lab (recipe "contour-grid")
# controls: levels=10, zero_line=false
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("contour-grid-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["grid", "point"])

X = "partial R² of confounder with treatment"
Y = "partial R² of confounder with outcome"
Z = "adjusted estimate"
KIND = "kind"
LABEL = "label"
LEVELS, ZERO = 10, False
grid = df[df[KIND].astype(str) != "point"] if KIND else df
wide = grid.pivot_table(index=Y, columns=X, values=Z)  # lattice over the distinct x and y values
zmin, zmax = np.nanmin(wide.values), np.nanmax(wide.values)
levels = np.linspace(zmin, zmax, LEVELS + 2)
cmap = "RdBu" if zmin < 0 < zmax else "Blues"
fig, ax = plt.subplots(figsize=(8, 4.5))
norm = plt.Normalize(-max(abs(zmin), abs(zmax)), max(abs(zmin), abs(zmax))) if zmin < 0 < zmax else None
cs_ = ax.contourf(wide.columns, wide.index, wide.values, levels=levels, cmap=cmap, norm=norm)
fig.colorbar(cs_, ax=ax, label=Z)
if ZERO and zmin < 0 < zmax:
    ax.contour(wide.columns, wide.index, wide.values, levels=[0], colors="black", linestyles="--", linewidths=1.6)
if KIND:
    pts = df[df[KIND].astype(str) == "point"]
    ax.scatter(pts[X], pts[Y], marker="D", color="black", s=24)
    for _, r in pts.iterrows():
        ax.annotate(f"{r[LABEL]}" if LABEL else "", (r[X], r[Y]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads contour-grid-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#within-between

Within and between units

Does the relationship inside a unit point the same way as the relationship across units?

Demo data · seed 20261101 · 96 rows · default settings · 640 × 360

How to read it

  1. Read the dots as observations and the larger marks as each unit's mean.
  2. Compare the slopes: within units, between units and pooled.
  3. Slopes that disagree suggest unit-level differences are confounding the pooled estimate.

Watch out

  • The within slope removes stable differences between units, not those that change over time.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • The within slope regresses y on x after subtracting each unit's means: the fixed-effects coefficient without covariates.
  • The between slope is an unweighted regression on the unit means; the pooled slope ignores units.
  • All three lines pass through the grand means so their angles can be compared directly.

Use with care

When within and between slopes differ, pooled OLS mixes two different questions; only the within slope removes what stays constant inside a unit.

# Within and between units — Codesplash Chart Lab (recipe "within-between")
# 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("within-between-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")
X = "training (hours/week)"
Y = "fitness score"
UNIT = "person"
KIND = None
d = df.dropna(subset=[X, Y])
means = d[d[KIND] == "unit mean"] if KIND else d.iloc[0:0]
obs = d[d[KIND] != "unit mean"] if KIND else d
def ls_slope(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    sxx = ((x - x.mean()) ** 2).sum()
    return ((x - x.mean()) * (y - y.mean())).sum() / sxx if len(x) > 1 and sxx > 1e-12 else None
within, between, pooled = None, None, None
if UNIT:
    grouped = obs.groupby(UNIT, observed=True)
    means = grouped[[X, Y]].mean().reset_index()
    wx, wy = obs[X] - grouped[X].transform("mean"), obs[Y] - grouped[Y].transform("mean")
    within = within if within is not None else ls_slope(wx, wy)
between = between if between is not None else ls_slope(means[X], means[Y])
pooled = pooled if pooled is not None else ls_slope(obs[X], obs[Y])
x_mean, y_mean = obs[X].mean(), obs[Y].mean()
span = np.array([min(obs[X].min(), means[X].min() if len(means) else obs[X].min()), max(obs[X].max(), means[X].max() if len(means) else obs[X].max())])
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(obs[X], obs[Y], s=8, alpha=0.35, color="#8a8f98")
for label, slope, colour, style in [("Within units", within, PALETTE[0], "-"), ("Between units", between, PALETTE[1], "-"), ("Pooled", pooled, REF, "--")]:
    if slope is not None:
        ax.plot(span, y_mean + slope * (span - x_mean), color=colour, linestyle=style, linewidth=2, label=f"{label}: slope {slope:.3g}")
ax.scatter(means[X], means[Y], s=36, color=PALETTE[1], edgecolor="white", linewidth=0.8, zorder=3)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Within and between units")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads within-between-demo.csv · app theme from the optional codesplash helper

Causal inference

svg#unit-effects

Unit effects

How far apart are the units once the regressors are held fixed, and how precisely is each one known?

Demo data · seed 20261101 · 14 rows · default settings · 640 × 360

How to read it

  1. Read each row as one unit's level once the regressors are held fixed.
  2. Rows are sorted, with the mean effect marked.
  3. 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

Experiments

A/B tests: sequential boundaries with the observed path, posterior densities and cumulative lift over time.

5

Experiments

svg#sequential-boundary

Group-sequential boundaries

At each interim look, has the test statistic crossed the efficacy or futility boundary?

Demo data · seed 20261101 · 13 rows · default settings · 640 × 360

How to read it

  1. Read the black path as the test statistic at each look.
  2. Crossing the upper boundary means stop for efficacy; the lower, for futility.
  3. Boundaries are wider early because evidence is thin.
  1. Callout 1: The path crosses the efficacy boundary here.
  2. Callout 2: Efficacy region.
  3. Callout 3: Futility region.

Watch out

  • Estimates at early stopping tend to be too large: use the adjusted estimate.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Series named like efficacy/upper/lower are boundaries (a level holding both signs is split into upper and lower for two-sided designs); futility is dashed; the observed path is drawn on top.
  • A crossing is the first observed look with z at or above the efficacy boundary interpolated at that information; the engine's spending function and decision are authoritative.
# Group-sequential boundaries — Codesplash Chart Lab (recipe "sequential-boundary")
# 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("sequential-boundary-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["series"] = pd.Categorical(df["series"].astype("string"), categories=["efficacy (O'Brien–Fleming)", "futility (non-binding)", "observed z"])

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)))
I = "information fraction"
Z = "z statistic"
B = "series"
groups = levels_of(df[B]) if B else [None]
series = []
for name in groups:
    d = df if name is None else df[df[B].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[I]).sort_values(I)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
for name, d in series:
    low = str(name).lower()
    kind = "futility" if "futil" in low else "observed" if any(w in low for w in ("observ", "path", "stat")) else "efficacy"
    col = {"efficacy": PALETTE[0], "futility": PALETTE[1], "observed": "black"}[kind]
    for part in ([d[d[Z] >= 0], d[d[Z] < 0]] if kind != "observed" and (d[Z] < 0).any() and (d[Z] > 0).any() else [d]):
        ax.plot(part[I], part[Z], marker="o", ms=4 if kind != "observed" else 6, color=col, linestyle="--" if kind == "futility" else "-", linewidth=2 if kind == "observed" else 1.5)
    ax.plot([], [], color=col, label=name)
ax.set_xlabel(I)
ax.set_ylabel(Z)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads sequential-boundary-demo.csv · app theme from the optional codesplash helper

Experiments

svg#posterior-density

Posterior densities

Given the data, where does each arm's true rate (or the lift) probably lie, and how much do the posteriors overlap?

Demo data · seed 20261101 · 242 rows · default settings · 640 × 360

How to read it

  1. Read each curve as where that arm's true rate probably lies.
  2. Read the bars below for the 95% highest-density intervals.
  3. Less overlap means more certainty that the arms differ.
  1. Callout 1: Arm A's most plausible rates.
  2. Callout 2: Arm B's.
  3. Callout 3: The intervals under the axis.

Watch out

  • The result depends on the prior, though less so with plenty of data.

Defaults

ROPE lower (equal bounds = none)
0
The lower end of the range of effects you would call practically zero.
Range -1,000,000,000 to 1,000,000,000, step 0.001
ROPE upper
0
The upper end of the range of effects you would call practically zero.
Range -1,000,000,000 to 1,000,000,000, step 0.001

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • The engine evaluates each posterior on a grid; the chart integrates the grid by the trapezoid rule for the mean and takes the narrowest set of grid points holding 95% of the mass as the HDI (exact for unimodal posteriors up to the grid spacing).
  • Values below 0.5 on a [0, 1] scale are shown as percentages (conversion rates).
  • P(B > A) and expected loss come from the engine's joint posterior draws, not from these marginal curves.
# Posterior densities — Codesplash Chart Lab (recipe "posterior-density")
# controls: rope_low=0, rope_high=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("posterior-density-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (control)", "B (new checkout)"])

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 = "conversion rate"
D = "posterior density"
ARM = "arm"
ROPE = (0, 0)
groups = levels_of(df[ARM]) if ARM else [None]
series = []
for name in groups:
    d = df if name is None else df[df[ARM].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
if None not in ROPE and ROPE[1] > ROPE[0]:
    ax.axvspan(*ROPE, color="grey", alpha=0.12, lw=0, label="ROPE")
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    ax.fill_between(d[X], d[D], color=col, alpha=0.2, lw=0)
    ax.plot(d[X], d[D], color=col, linewidth=1.8, label=name or D)
ax.set_xlabel(X)
ax.set_ylabel("density")
ax.set_ylim(bottom=0)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads posterior-density-demo.csv · app theme from the optional codesplash helper

Experiments

svg#cumulative-lift

Cumulative lift

Is the treatment effect stable over the test, or fading (novelty) or growing (primacy)?

Demo data · seed 20261101 · 56 rows · default settings · 640 × 360

How to read it

  1. Read the line as cumulative lift since launch.
  2. Early values swing widely, then settle.
  3. A steady fall may be novelty; a steady climb, primacy.
  1. Callout 1: Early: wide, unstable.
  2. Callout 2: Settled lift.
  3. Callout 3: The band still crosses zero.

Watch out

  • Peeking at this chart and stopping when it looks good inflates false positives.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Each point is the lift on all data up to that time (not the daily lift), so bands narrow as data accumulate; early wide swings are expected.
  • A trend after the band has narrowed suggests novelty or primacy effects — compare by days since first exposure, which the engine reports as a separate breakdown.
# Cumulative lift — Codesplash Chart Lab (recipe "cumulative-lift")
# 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("cumulative-lift-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["conversion", "revenue per user"])

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 = "day since launch"
Y = "cumulative relative lift"
LO = "ci_low"
HI = "ci_high"
G = "metric"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0)
    ax.plot(d[X], d[Y], color=col, linewidth=2, label=name or Y)
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads cumulative-lift-demo.csv · app theme from the optional codesplash helper

Experiments

svg#sprt-path

SPRT log-likelihood ratio walk

After each observation (or event), has the evidence crossed the boundary for H₁ or for H₀?

Demo data · seed 20261101 · 43 rows · default settings · 640 × 360

How to read it

  1. Read the black path as the evidence after each observation.
  2. Crossing the upper line: reject H₀; the lower: accept H₀.
  3. Stop at the first crossing.
  1. Callout 1: The first crossing: stop here.
  2. Callout 2: The reject-H₀ boundary.
  3. Callout 3: The accept-H₀ boundary.

Watch out

  • An SPRT plans for specific hypotheses; a true effect between them can take a long time to decide.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Series named like reject / log A / critical value are the upper boundary, accept / log B the lower one; any other series is the observed walk.
  • The first crossing is the first observed point at or beyond a boundary interpolated at that x; the engine's decision is authoritative (Wald's truncation rule may decide earlier).
# SPRT log-likelihood ratio walk — Codesplash Chart Lab (recipe "sprt-path")
# 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("sprt-path-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["series"] = pd.Categorical(df["series"].astype("string"), categories=["reject H₀ (log A)", "accept H₀ (log B)", "observed log Λ"])

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 = "observation"
L = "log Λ"
S = "series"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
for name, d in series:
    low = str(name).lower()
    kind = "upper" if any(w in low for w in ("reject", "log a", "critical", "upper", "signal")) else "lower" if any(w in low for w in ("accept", "log b", "lower")) else "path"
    col = {"upper": PALETTE[0], "lower": PALETTE[1], "path": "black"}[kind]
    ax.plot(d[X], d[L], color=col, linestyle="-" if kind == "path" else "--", marker="o" if kind == "path" else None, ms=3, linewidth=2 if kind == "path" else 1.5, label=name)
ax.set_xlabel(X)
ax.set_ylabel(L)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads sprt-path-demo.csv · app theme from the optional codesplash helper

Experiments

svg#expected-loss

Expected loss by decision

If we ship (or keep the control) now, how much do we expect to lose if that choice turns out wrong?

Demo data · seed 20261101 · 3 rows · default settings · 640 × 360

How to read it

  1. Read blue as the expected loss of shipping that arm, orange as that of keeping control.
  2. Compare with your tolerable loss.
  3. Ship only when the loss from shipping is below that threshold.
  1. Callout 1: Keeping control here risks a large loss.
  2. Callout 2: Shipping B risks almost nothing.
  3. Callout 3: Shipping D has a larger expected loss than keeping control.

Watch out

  • Expected loss depends on the prior and on a loss scale that must suit the business.

Defaults

Tolerable loss ε
0
The loss you can accept if your decision turns out wrong.
Range 0 to 1,000,000,000, step 0.0001

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Expected loss of shipping = E[max(control − treatment, 0)] under the posterior (in the metric's units, for a higher-is-better metric); of keeping the control = E[max(treatment − control, 0)].
  • The decision rule ships the treatment when its expected loss is below ε and keeps the control when that loss is below ε; otherwise keep collecting data.
# Expected loss by decision — Codesplash Chart Lab (recipe "expected-loss")
# controls: threshold=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("expected-loss-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["B", "C", "D"])

A = "arm"
SHIP = "loss if shipped"
KEEP = "loss if not shipped"
EPS = 0
d = df.dropna(subset=[A, SHIP, KEEP])
x = np.arange(len(d))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(x - 0.2, d[SHIP], width=0.4, color=PALETTE[0], label="expected loss if shipped")
ax.bar(x + 0.2, d[KEEP], width=0.4, color=PALETTE[1], label="expected loss if not shipped")
if EPS:
    ax.axhline(EPS, color="black", linestyle="--", linewidth=1.2, label=f"tolerable loss ε = {EPS:g}")
ax.set_xticks(x, d[A].astype(str))
ax.set_ylabel("expected loss")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads expected-loss-demo.csv · app theme from the optional codesplash helper

DoE & process control

Control charts with rules, capability against specification limits, effect screening (half-normal, Pareto), main effects and gauge R&R.

12

DoE & process control

svg#control-chart

Control chart

Is the process in statistical control, and where are the signals?

Demo data · seed 20261101 · 50 rows · default settings · 640 × 360

How to read it

  1. Read points in time order against the centre line.
  2. Points beyond the red limits, or runs on one side, signal a special cause.
  3. Read the spread chart first: its limits must be stable before the means chart can be trusted.
  1. Callout 1: Signals: points beyond the limits or breaking a rule.
  2. Callout 2: The centre line.
  3. Callout 3: The range chart: variability over time.

Watch out

  • Control limits describe the process, not the specification: a stable process can still make bad parts.

Defaults

Show ±1σ / ±2σ zones
Off
Shade the bands used by the zone rules.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Limits are drawn as sent, stepping between samples when they vary (p, u charts with varying n; Laney p′). Without a signal role, points beyond the limits are marked.
  • Zones divide the distance from the centre to each limit into thirds (Western Electric zones A, B, C); rule labels come from the engine (Nelson / Western Electric rule numbers).
# Control chart — Codesplash Chart Lab (recipe "control-chart")
# controls: zones=false
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("control-chart-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["chart"] = pd.Categorical(df["chart"].astype("string"), categories=["X̄", "R"])

_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)))
I = "subgroup"
V = "statistic"
CL = "centre"
LCL = "lcl"
UCL = "ucl"
VIO = "signal"
RULE = "rule"
CHART = "chart"
charts = levels_of(df[CHART]) if CHART else [None]
fig, axes = plt.subplots(len(charts), 1, figsize=(8, 2.6 * len(charts)), sharex=True, squeeze=False)
for ax, ch in zip(axes[:, 0], charts):
    d = (df if ch is None else df[df[CHART].astype(str) == str(ch)]).sort_values(I)
    out = d[VIO].astype(bool) if VIO else (d[V] > d[UCL]) | (d[V] < d[LCL])
    ax.step(d[I], d[CL], where="mid", color="grey", linewidth=1)
    ax.step(d[I], d[UCL], where="mid", color=REF, linestyle="--", linewidth=1)
    ax.step(d[I], d[LCL], where="mid", color=REF, linestyle="--", linewidth=1)
    ax.plot(d[I], d[V], marker="o", ms=3.5, color=PALETTE[0], linewidth=1.2)
    ax.scatter(d.loc[out, I], d.loc[out, V], color="#ce5342", s=40, zorder=3)
    ax.set_ylabel(str(ch) if ch is not None else V)
axes[-1, 0].set_xlabel(I)
plt.show()

Needs pandas, numpy, matplotlib · reads control-chart-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#capability-histogram

Process capability

Does the process fit inside its specification limits, and how much falls outside?

Demo data · seed 20261101 · 250 rows · default settings · 640 × 360

How to read it

  1. Read the histogram and curve as the process output.
  2. Compare with the red specification limits.
  3. Read the indices at the top: how comfortably the process fits.
  1. Callout 1: The lower specification limit.
  2. Callout 2: The upper specification limit.
  3. Callout 3: A process centred away from the target.
  4. Callout 4: Pp, Ppk and the share outside.

Watch out

  • Capability assumes a stable process and a suitable distribution. Check the control chart first.

Defaults

Lower specification limit (null = none)
9.95
The smallest value the requirement accepts.
Range -1,000,000,000 to 1,000,000,000, step 0.001
Upper specification limit (null = none)
10.05
The largest value the requirement accepts.
Range -1,000,000,000 to 1,000,000,000, step 0.001
Target (null = none)
10
The outcome you want to reach; the chart shows the chance of missing it.
Range -1,000,000,000 to 1,000,000,000, step 0.001

Pinned in the code

  • Bins: equal width over the values and limits (at least 10, Sturges otherwise). The fitted curve is the engine's (normal or a Box–Cox/Johnson fit, as sent); without one, a normal density with the sample mean and SD.
  • Pp/Ppk in the legend use the overall (long-term) SD of the plotted values; Cp/Cpk from within-subgroup variation come from the engine's capability table.
  • Specification limits are customer requirements, not control limits; send null for a one-sided specification.
# Process capability — Codesplash Chart Lab (recipe "capability-histogram")
# controls: lsl=9.95, usl=10.05, target=10
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("capability-histogram-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

V = "diameter (mm)"
FX = None
FD = None
LSL, USL, TARGET = 9.95, 10.05, 10
v = df[V].dropna()
lims = [x for x in (LSL, USL) if x is not None]
edges = np.linspace(min([v.min()] + lims), max([v.max()] + lims), max(10, int(np.ceil(np.log2(len(v)) + 1))) + 1)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.hist(v, bins=edges, density=True, color=PALETTE[0], alpha=0.45, edgecolor="white")
if FX and FD:
    f = df.dropna(subset=[FX, FD]).sort_values(FX)
    ax.plot(f[FX], f[FD], color=PALETTE[0], linewidth=2)
else:  # normal with the sample mean and SD (overall)
    xs = np.linspace(edges[0], edges[-1], 200)
    ax.plot(xs, stats.norm.pdf(xs, v.mean(), v.std(ddof=1)), color=PALETTE[0], linewidth=2)
for x, name, col, ls in ((LSL, "LSL", "#ce5342", "--"), (USL, "USL", "#ce5342", "--"), (TARGET, "target", "#19966e", ":")):
    if x is not None:
        ax.axvline(x, color=col, linestyle=ls, linewidth=1.4)
        ax.annotate(name, (x, 1), xycoords=("data", "axes fraction"), ha="center", va="bottom", fontsize=8, color=col)
s = v.std(ddof=1)
if LSL is not None and USL is not None:
    ax.set_title(f"Pp {(USL - LSL) / (6 * s):.3f} · Ppk {min((USL - v.mean()) / (3 * s), (v.mean() - LSL) / (3 * s)):.3f}", fontsize=9, loc="left")
ax.set_xlabel(V)
ax.set_ylabel("density")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads capability-histogram-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#half-normal-effects

Half-normal plot of effects

Which factor effects in an unreplicated factorial stand out from noise?

Demo data · seed 20261101 · 15 rows · default settings · 640 × 360

How to read it

  1. Read points near the line through the origin as noise.
  2. Read points far above and to the right as active effects.
  3. The labels name the factors.
  1. Callout 1: Active effects, far from the line.
  2. Callout 2: Inactive effects, on the line.
  3. Callout 3: The line through the inactive ones.

Watch out

  • Effects are aliased in a fraction: a labelled effect may be another one in disguise.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Quantiles are Φ⁻¹(0.5 + 0.5·(i − 0.5)/m) for the i-th smallest of m effects (Daniel 1959); activity is the engine's decision (Lenth's ME by default).
  • The reference line is least squares through the origin on the inactive effects.
# Half-normal plot of effects — Codesplash Chart Lab (recipe "half-normal-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("half-normal-effects-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")
E = "effect"
A = "|effect|"
Q = "half-normal quantile"
S = "active"
d = df.dropna(subset=[A, Q])
sig = d[S].astype(bool)
inert = d[~sig]
slope = (inert[A] * inert[Q]).sum() / (inert[A] ** 2).sum()  # least squares through the origin
fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.array([0, d[A].abs().max() * 1.1])
ax.plot(xs, slope * xs, color=REF, linestyle="--", linewidth=1)
ax.scatter(d.loc[~sig, A].abs(), d.loc[~sig, Q], color="grey", s=18)
ax.scatter(d.loc[sig, A].abs(), d.loc[sig, Q], color=PALETTE[1], s=30)
for _, r in d[sig].iterrows():
    ax.annotate(str(r[E]), (abs(r[A]), r[Q]), xytext=(-6, 0), textcoords="offset points", ha="right", va="center", fontsize=9, fontweight="bold")
ax.set_ylim(0, d[Q].max() * 1.08)
ax.set_xlabel(A)
ax.set_ylabel(Q)
plt.show()

Needs pandas, numpy, matplotlib · reads half-normal-effects-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#pareto-effects

Pareto chart of effects

Which effects are largest, and which exceed Lenth's margin of error?

Demo data · seed 20261101 · 15 rows · default settings · 640 × 360

How to read it

  1. Read the bars top down: the largest effects.
  2. Compare with the margin of error (ME) and the simultaneous margin (SME).
  3. Bars past SME stand out even after correcting for many comparisons.
  1. Callout 1: The largest effect.
  2. Callout 2: ME: the margin of error.
  3. Callout 3: SME: the simultaneous margin.

Watch out

  • Lenth's method assumes few active effects: if most are active, it underestimates the noise.

Defaults

Margin of error (ME; null = none)
6.08
Lenth's margin: an effect beyond this may be real.
Range 0 to 1,000,000,000, step 0.01
Simultaneous margin (SME; null = none)
12.36
Lenth's margin after correcting for testing all effects at once.
Range 0 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Bars beyond ME are coloured; ME = t(0.975, d)·PSE with d = m/3 (Lenth 1989); SME uses the simultaneous quantile. The engine computes both.
# Pareto chart of effects — Codesplash Chart Lab (recipe "pareto-effects")
# controls: margin=6.08, smargin=12.36
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("pareto-effects-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")
E = "effect"
V = "|effect|"
ME, SME = 6.08, 12.36
d = df.dropna(subset=[E, V]).assign(a=lambda t: t[V].abs()).sort_values("a")  # largest at the top
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.barh(d[E].astype(str), d["a"], color=[PALETTE[1] if ME is None or a > ME else "grey" for a in d["a"]])
if ME is not None: ax.axvline(ME, color=REF, linestyle="--", linewidth=1.2, label=f"ME {ME:g}")
if SME is not None: ax.axvline(SME, color="#ce5342", linestyle=":", linewidth=1.2, label=f"SME {SME:g}")
ax.set_xlabel(V)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads pareto-effects-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#main-effects

Main effects

How does the mean response change across each factor's levels?

Demo data · seed 20261101 · 8 rows · default settings · 640 × 360

How to read it

  1. Read each panel as one factor: mean response at each level.
  2. Steeper lines mean larger main effects.
  3. Compare with the dashed grand mean.
  1. Callout 1: A steep line: a large effect.
  2. Callout 2: A shallow line: a small effect.
  3. Callout 3: The grand mean.

Watch out

  • If factors interact, a main effect alone can mislead: check the interaction plot too.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Levels are drawn in the order sent (coded low → high); the y axis is shared across a response's panels so slopes compare. The dashed line is the grand mean of the first factor's level means.
  • Main effects can mislead when interactions are large — check the interaction plot and the effects screening first.
# Main effects — Codesplash Chart Lab (recipe "main-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("main-effects-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["factor"] = pd.Categorical(df["factor"].astype("string"), categories=["Temperature", "Pressure", "Concentration", "Stirring"])
df["level"] = pd.Categorical(df["level"].astype("string"), categories=["low", "high"])

_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)))
F = "factor"
L = "level"
M = "mean filtration rate"
RESP = None
factors = levels_of(df[F])
fig, axes = plt.subplots(1, len(factors), figsize=(2.2 * len(factors) + 1, 3.6), sharey=True, squeeze=False)
grand = df[df[F].astype(str) == str(factors[0])][M].mean()
for ax, f in zip(axes[0], factors):
    d = df[df[F].astype(str) == str(f)]
    ax.plot(d[L].astype(str), d[M], marker="o", color=PALETTE[0], linewidth=1.8)
    ax.axhline(grand, color=REF, linestyle="--", linewidth=1)
    ax.set_title(str(f), fontsize=10, loc="left")
axes[0, 0].set_ylabel(M)
plt.show()

Needs pandas, numpy, matplotlib · reads main-effects-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#gage-components

Gauge R&R components

How much of the observed variation comes from the measurement system rather than the parts?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Read each cluster as one variance source, by three measures.
  2. Compare gauge R&R with the 10% and 30% guidelines.
  3. Part-to-part should dominate if the gauge is good.
  1. Callout 1: Gauge R&R: the measurement system.
  2. Callout 2: Part-to-part: what you want to see.
  3. Callout 3: Guidelines: below 10% is good, above 30% is not.

Watch out

  • Too few parts or operators make these percentages very uncertain.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Values are percentages (fractions ≤ 1.5 are scaled to percent). % contribution is on the variance scale and sums to 100; % study variation is on the SD scale (6σ) and does not.
  • AIAG guidelines on % study variation: under 10% acceptable, 10–30% may be acceptable, over 30% unacceptable; the engine also reports the number of distinct categories.
# Gauge R&R components — Codesplash Chart Lab (recipe "gage-components")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("gage-components-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["source"] = pd.Categorical(df["source"].astype("string"), categories=["Gauge R&R", "Repeatability", "Reproducibility", "Part-to-part"])
df["measure"] = pd.Categorical(df["measure"].astype("string"), categories=["contribution", "study_var", "tolerance"])

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)))
S = "source"
V = "percent"
ME = "measure"
d = df.dropna(subset=[S, V]).copy()
d["_m"] = d[ME].astype(str) if ME else "contribution"
scale = 100 if d[V].max() <= 1.5 else 1  # fractions → percent
sources, measures = levels_of(d[S]), levels_of(d["_m"])
w = 0.8 / len(measures)
fig, ax = plt.subplots(figsize=(8, 4.5))
for j, m in enumerate(measures):
    vals = [d.loc[(d[S].astype(str) == str(s)) & (d["_m"] == m), V].sum() * scale for s in sources]
    ax.bar(np.arange(len(sources)) + (j - (len(measures) - 1) / 2) * w, vals, width=w * 0.95, color=PALETTE[j % len(PALETTE)], label=m, hatch=SERIES_HATCHES[j % 8], hatchcolor=HATCH_INK, linewidth=0)  # texture per measure, as in the app
for t in (10, 30):  # AIAG guidelines
    ax.axhline(t, color="grey", linestyle="--", linewidth=1)
ax.set_xticks(range(len(sources)), [str(s) for s in sources])
ax.set_ylabel("percent")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads gage-components-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#probability-plot

Probability plot

Do these failures fall on a straight line on this family's probability paper?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read x as time and y as the share of units failed; both axes are stretched so the chosen family plots as a straight line.
  2. Check whether the points follow the line: straight points support that family.
  3. On Weibull paper the slope is the shape: above 1 the failure rate rises, below 1 it falls.
  1. Callout 1: The earliest failures, where a family most often fails to fit.
  2. Callout 2: The fitted line: a straight run of points supports this family.
  3. Callout 3: The latest failures, based on the fewest units.
  4. Callout 4: Time on a log scale for this paper.

Watch out

  • A few points at either end always wander, so judge the middle first and the ends with care.
  • Censored units are not plotted, but they raise the order number of later failures, so do not drop them from the data.

Defaults

Paper
Weibull
The family whose straight line you are checking against.
Also: Log-normal · Exponential · Log-logistic · Normal

Pinned in the code

  • Plotting positions: Benard's median ranks (i − 0.3)/(n + 0.4) with Johnson's adjusted order numbers for censored units; failures come before suspensions at a tie.
  • Without engine rows the line is rank regression of paper y on paper x. With them it is the fitted CDF the engine sent.
  • The plot correlation is Pearson's r of the plotted points.
# Probability plot — Codesplash Chart Lab (recipe "probability-plot")
# controls: paper=weibull
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("probability-plot-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")
T = "hours"
E = "failed"
F = None
FAM = None
def median_ranks(t, e=None):
    """Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie."""
    t = np.asarray(t, dtype=float)
    e = np.ones(t.size, dtype=bool) if e is None else np.asarray(e, dtype=float) > 0
    keep = np.isfinite(t) & (t > 0)
    t, e = t[keep], e[keep]
    o = np.lexsort((~e, t))
    t, e = t[o], e[o]
    n, prev, ts, fs = t.size, 0.0, [], []
    for i in range(n):
        if e[i]:
            prev += (n + 1 - prev) / (n - i + 1)
            ts.append(t[i])
            fs.append((prev - 0.3) / (n + 0.4))
    return np.array(ts), np.array(fs)
def paper_x(paper, t):
    return t if paper in ("exponential", "normal") else np.log(t)

def paper_y(paper, f):
    if paper == "weibull":
        return np.log(-np.log1p(-f))
    if paper == "exponential":
        return -np.log1p(-f)
    if paper == "loglogistic":
        return np.log(f / (1 - f))
    return stats.norm.ppf(f)

def paper_line(rows, paper, x):
    """The engine's fitted curve for this family when present, else rank regression of paper y on paper x."""
    if rows is not None and len(rows):
        curve = rows[(rows[F] > 0) & (rows[F] < 1)].sort_values(T)
        return paper_x(paper, curve[T].to_numpy(float)), paper_y(paper, curve[F].to_numpy(float))
    xs, ys = x
    b, a = np.polyfit(xs, ys, 1)
    return np.array([xs.min(), xs.max()]), a + b * np.array([xs.min(), xs.max()])

def split_rows(df):
    is_data = df[FAM].astype(str).str.lower().eq("data") if FAM else pd.Series(True, index=df.index)
    return df[is_data], df[~is_data]
PAPER = "weibull"
sample, curves = split_rows(df)
tt, ff = median_ranks(sample[T], sample[E] if E else None)
xs, ys = paper_x(PAPER, tt), paper_y(PAPER, ff)
fit_rows = curves[curves[FAM].astype(str) == PAPER] if FAM and F else None
lx, ly = paper_line(fit_rows, PAPER, (xs, ys))
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(lx, ly, color=REF, linewidth=1.5)
ax.scatter(xs, ys, s=18, color=PALETTE[0], alpha=0.8)
probs = np.array([0.01, 0.05, 0.1, 0.2, 0.5, 0.8, 0.9, 0.99])
probs = probs[(probs >= ff.min() * 0.9) & (probs <= ff.max() * 1.1)]
ax.set_yticks(paper_y(PAPER, probs), [f"{p:.0%}" for p in probs])
ax.set_xlabel(T if PAPER in ("exponential", "normal") else f"log {T}")
ax.set_ylabel("Cumulative failure probability")
ax.set_title(f"{PAPER} probability plot: plot correlation {np.corrcoef(xs, ys)[0, 1]:.3f}", fontsize=10, loc="left")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads probability-plot-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#dist-id-grid

Distribution ID plot

Which lifetime family fits: Weibull, log-normal, exponential or log-logistic?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Each panel is one family's probability paper, and the panel title gives how well the points follow its line.
  2. Look for the panel where the points lie straightest, across the whole range.
  3. Read it with the AIC table: agreement between them is stronger evidence than either alone.
  1. Callout 1: The family and how straight its points are: r nearer 1 is straighter.
  2. Callout 2: A family that fits: the points stay on the line.
  3. Callout 3: Points bending away from the line: this family misses the early failures.

Watch out

  • With few failures several panels look straight. Compare the B-lives before you pick one, because the choice matters most in the tails.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Median ranks with adjusted order numbers on each paper; r is the plot correlation of the points.
  • Lines are the engine's maximum-likelihood fits when it sends them, otherwise rank regression.
  • Gamma, generalized gamma and Gompertz have no straight-line paper, so they appear only in the AIC table.
# Distribution ID plot — Codesplash Chart Lab (recipe "dist-id-grid")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("dist-id-grid-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")
T = "hours"
E = "failed"
F = None
FAM = None
def median_ranks(t, e=None):
    """Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie."""
    t = np.asarray(t, dtype=float)
    e = np.ones(t.size, dtype=bool) if e is None else np.asarray(e, dtype=float) > 0
    keep = np.isfinite(t) & (t > 0)
    t, e = t[keep], e[keep]
    o = np.lexsort((~e, t))
    t, e = t[o], e[o]
    n, prev, ts, fs = t.size, 0.0, [], []
    for i in range(n):
        if e[i]:
            prev += (n + 1 - prev) / (n - i + 1)
            ts.append(t[i])
            fs.append((prev - 0.3) / (n + 0.4))
    return np.array(ts), np.array(fs)
def paper_x(paper, t):
    return t if paper in ("exponential", "normal") else np.log(t)

def paper_y(paper, f):
    if paper == "weibull":
        return np.log(-np.log1p(-f))
    if paper == "exponential":
        return -np.log1p(-f)
    if paper == "loglogistic":
        return np.log(f / (1 - f))
    return stats.norm.ppf(f)

def paper_line(rows, paper, x):
    """The engine's fitted curve for this family when present, else rank regression of paper y on paper x."""
    if rows is not None and len(rows):
        curve = rows[(rows[F] > 0) & (rows[F] < 1)].sort_values(T)
        return paper_x(paper, curve[T].to_numpy(float)), paper_y(paper, curve[F].to_numpy(float))
    xs, ys = x
    b, a = np.polyfit(xs, ys, 1)
    return np.array([xs.min(), xs.max()]), a + b * np.array([xs.min(), xs.max()])

def split_rows(df):
    is_data = df[FAM].astype(str).str.lower().eq("data") if FAM else pd.Series(True, index=df.index)
    return df[is_data], df[~is_data]
sample, curves = split_rows(df)
tt, ff = median_ranks(sample[T], sample[E] if E else None)
fig, axes = plt.subplots(2, 2, figsize=(9, 6))
for i, (ax, paper) in enumerate(zip(axes.flat, ["weibull", "lognormal", "exponential", "loglogistic"])):
    xs, ys = paper_x(paper, tt), paper_y(paper, ff)
    lx, ly = paper_line(curves[curves[FAM].astype(str) == paper] if FAM and F else None, paper, (xs, ys))
    ax.plot(lx, ly, color=REF, linewidth=1.4)
    ax.scatter(xs, ys, s=12, color=PALETTE[i % len(PALETTE)], alpha=0.8)
    ax.set_title(f"{paper}: r = {np.corrcoef(xs, ys)[0, 1]:.3f}", fontsize=9, loc="left")
plt.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads dist-id-grid-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#ttt-plot

Total-time-on-test plot

Is the failure rate rising, falling, constant or bathtub-shaped?

Demo data · seed 20261101 · 50 rows · default settings · 640 × 360

How to read it

  1. Read x as the share of units failed and y as the share of total running time used by then.
  2. On the dashed diagonal the failure rate is constant, as an exponential lifetime requires.
  3. Bowed above means a rising failure rate (wear-out); bowed below means a falling one (early failures); an S shape suggests a bathtub.
  1. Callout 1: The curve above the diagonal: a rising failure rate.
  2. Callout 2: The diagonal: a constant failure rate.
  3. Callout 3: Which side means what.

Watch out

  • It needs complete lifetimes. Units still running would need a censored version of this plot.
  • With few failures the curve wanders around the diagonal by chance, so check the battery's p-values too.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Normalized spacings D_i = (n − i + 1)(x_(i) − x_(i−1)); the curve is (i/n, Σ_{j≤i} D_j / Σ D_j). Complete lifetimes only.
  • The area statistic is the mean of the interior points, which equals one minus the Gini statistic.
# Total-time-on-test plot — Codesplash Chart Lab (recipe "ttt-plot")
# 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("ttt-plot-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")
V = "hours"
x = np.sort(df[V].dropna().to_numpy(dtype=float))
x = x[x > 0]
n = x.size
d = (n - np.arange(n)) * np.diff(x, prepend=0.0)  # normalized spacings
u = np.concatenate(([0.0], np.arange(1, n + 1) / n))
ttt = np.concatenate(([0.0], np.cumsum(d) / d.sum()))
area = ttt[1:-1].mean()
fig, ax = plt.subplots(figsize=(6, 5))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", label="exponential (constant hazard)")
ax.plot(u, ttt, color=PALETTE[0], linewidth=1.8, label="TTT curve")
ax.set_xlabel("Share of units failed (i/n)")
ax.set_ylabel("Scaled total time on test")
ax.set_title(f"Scaled total-time-on-test plot: area {area:.3f}", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads ttt-plot-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#reliability-curve

Reliability curve

What share of units is still working at each age?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read x as age and y as the share of units still working at that age.
  2. Find your mission time on x and read across for the reliability; a line marks it when one is set.
  3. Compare curves by how far apart they are at the age you care about.
  1. Callout 1: All units start out working.
  2. Callout 2: A fitted curve: the share still working at each age.
  3. Callout 3: One curve per group or profile.

Watch out

  • It comes from a fitted family. Past the last failure it is extrapolation, however smooth it looks.
  • The curves show no uncertainty, so read the intervals in the life table beside them.

Defaults

Mission time
0
Draw a line at this time (0 for none).
Range 0 to 1,000,000, step 10
B-life
0
Draw a line at this B-life (0 for none).
Range 0 to 1,000,000, step 10

Pinned in the code

  • R(t) = 1 − F(t). A curve named Kaplan–Meier is drawn as steps, others as smooth lines.
# Reliability curve — Codesplash Chart Lab (recipe "reliability-curve")
# controls: mission=0, bLife=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("reliability-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["supplier"] = pd.Categorical(df["supplier"].astype("string"), categories=["A", "B"])

_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")
T = "hours"
Y = "reliability"
G = "supplier"
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 curves():
    groups = levels_of(df[G]) if G else [None]
    for g in groups:
        d = df if g is None else df[df[G].astype(str) == str(g)]
        d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
        t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
        keep = np.isfinite(v)
        t, v = t[keep], v[keep]
        yield ("all" if g is None else str(g)), t, v
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, y) in enumerate(curves()):
    ax.plot(t, y, color=PALETTE[i % len(PALETTE)], label=name)
ax.set_xlabel(T)
ax.set_ylabel("Reliability")
ax.set_title("Reliability: share of units still working", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads reliability-curve-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#hazard-plot

Hazard curve

Does the failure rate rise, fall or stay flat with age?

Demo data · seed 20261101 · 180 rows · default settings · 640 × 360

How to read it

  1. Read x as age and y as the failure rate among units still working at that age.
  2. Falling means early failures, flat means random failures, rising means wear-out.
  3. Compare the families' curves where you have data: they often agree there and diverge beyond it.
  1. Callout 1: A falling hazard: early failures.
  2. Callout 2: A flat hazard: an exponential lifetime.
  3. Callout 3: A rising hazard: wear-out.
  4. Callout 4: One curve per family or group.

Watch out

  • These curves come from fitted families, so each one's shape is partly assumed: a Weibull cannot show a bathtub.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • The y axis stops at the 98th percentile so very early hazards do not flatten the rest.
# Hazard curve — Codesplash Chart Lab (recipe "hazard-plot")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("hazard-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["shape"] = pd.Categorical(df["shape"].astype("string"), categories=["0.7", "1", "2"])

_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")
T = "hours"
Y = "hazard"
G = "shape"
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 curves():
    groups = levels_of(df[G]) if G else [None]
    for g in groups:
        d = df if g is None else df[df[G].astype(str) == str(g)]
        d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
        t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
        keep = np.isfinite(v)
        t, v = t[keep], v[keep]
        yield ("all" if g is None else str(g)), t, v
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, y) in enumerate(curves()):
    ax.plot(t, y, color=PALETTE[i % len(PALETTE)], linestyle=SERIES_DASHES[i % 8], label=name)  # dash per stratum, as in the app
ax.set_xlabel(T)
ax.set_ylabel("Hazard")
ax.set_title("Hazard: failure rate among units still working", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads hazard-plot-demo.csv · app theme from the optional codesplash helper

DoE & process control

svg#lorenz-gini

Lorenz curve and Gini

How unevenly is the total lifetime shared out among units?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read x as the share of units, shortest-lived first, and y as their share of all the lifetime in the sample.
  2. Compare the curve with the dashed exponential curve, whose Gini is one half.
  3. Further below it means lifetimes are more unequal, which points to a falling failure rate; above it, a rising one.
  1. Callout 1: The line of equality: every unit lasts equally long.
  2. Callout 2: The exponential reference, Gini one half.
  3. Callout 3: The sample's curve, and the Gini is twice the area between it and equality.

Watch out

  • It compares lifetimes with each other, so it ignores the time scale. Two samples with very different mean lives can share a curve.

Defaults

Exponential reference
On
Show the Lorenz curve of an exponential distribution.

Pinned in the code

  • Curve: (i/n, Σ_{j≤i} x_(j) / Σ x). Gini: ΣΣ|x_i − x_j| / (2n(n−1)x̄), the finite-sample normalization of the guide's entry 145.
  • The exponential reference is L(p) = p + (1 − p) log(1 − p).
# Lorenz curve and Gini — Codesplash Chart Lab (recipe "lorenz-gini")
# controls: reference=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("lorenz-gini-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")
V = "hours"
x = np.sort(df[V].dropna().to_numpy(dtype=float))
n = x.size
p_ = np.concatenate(([0.0], np.arange(1, n + 1) / n))
l_ = np.concatenate(([0.0], np.cumsum(x) / x.sum()))
gini = 2 * np.sum((2 * np.arange(1, n + 1) - n - 1) * x) / (2 * n * (n - 1) * x.mean())
grid = np.linspace(0, 0.999, 60)
ref = grid + (1 - grid) * np.log1p(-grid)  # exponential Lorenz curve
fig, ax = plt.subplots(figsize=(6, 5))
ax.plot([0, 1], [0, 1], color=GREY, label="equality")
ax.plot(grid, ref, color=REF, linestyle="--", label="exponential (Gini = 0.5)")
ax.plot(p_, l_, color=PALETTE[0], linewidth=1.8, label="Lorenz curve")
ax.set_xlabel("Share of units, shortest-lived first")
ax.set_ylabel("Share of total lifetime")
ax.set_title(f"Lorenz curve: Gini {gini:.3f}", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads lorenz-gini-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

Tornado and spider sensitivity, Monte Carlo distributions, efficient frontiers, bandit regret and arm shares, and fairness metrics by group.

7

Simulation, optimization & decisions

svg#tornado

Tornado diagram

Which uncertain inputs move the outcome most when each is varied alone?

Demo data · seed 20261101 · 7 rows · default settings · 640 × 360

How to read it

  1. Read bars top down: the inputs that move the output most.
  2. Read each side as the input's low or high value, with others held at base.
  3. Focus effort on the top bars.
  1. Callout 1: The most influential input.
  2. Callout 2: A small swing: this input matters little.
  3. Callout 3: The base-case output.

Watch out

  • It varies one input at a time, so it misses interactions: use a Monte Carlo run for those.

Defaults

Base-case output
1,240
The output with every input at its base value; bars diverge from here.
Range -1,000,000,000,000 to 1,000,000,000,000, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • One-way sensitivity: each input moves to its low and high value (e.g. P10 and P90) with every other input at its base case; bars run from the base-case output.
  • Interactions between inputs are invisible here — use Sobol indices or Monte Carlo for joint uncertainty.
# Tornado diagram — Codesplash Chart Lab (recipe "tornado")
# controls: base=1240
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("tornado-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")
INPUT = "input"
LO = "NPV ($k) at low"
HI = "NPV ($k) at high"
BASE = 1240
d = df.dropna(subset=[INPUT, LO, HI]).assign(swing=lambda t: (t[HI] - t[LO]).abs()).sort_values("swing")  # widest on top
base = BASE if BASE is not None else (d[LO].iloc[-1] + d[HI].iloc[-1]) / 2
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(d))
ax.barh(y, d[LO] - base, left=base, color=PALETTE[1], label="input at its low value")
ax.barh(y, d[HI] - base, left=base, color=PALETTE[0], label="input at its high value")
ax.axvline(base, color="black", linewidth=1.2)
ax.set_yticks(y, d[INPUT].astype(str))
ax.set_xlabel("output")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads tornado-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#spider

Spider plot

How steeply does the output respond as each input moves away from its base value?

Demo data · seed 20261101 · 28 rows · default settings · 640 × 360

How to read it

  1. Read each line as the output as one input moves from base.
  2. Steeper means more sensitive.
  3. All lines cross at the base case.
  1. Callout 1: A steep line: a sensitive input.
  2. Callout 2: The base case.
  3. Callout 3: This input lowers the output as it rises.

Watch out

  • A percent change isn't equally likely for every input, so steepness alone doesn't rank risks.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Changes within ±2 are read as fractions (−0.2 = −20%), larger values as percent; the dashed line is the output at zero change.
# Spider plot — Codesplash Chart Lab (recipe "spider")
# 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("spider-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

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)))
CH = "change from base"
K = "NPV ($k)"
INPUT = "input"
groups = levels_of(df[INPUT]) if INPUT else [None]
series = []
for name in groups:
    d = df if name is None else df[df[INPUT].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[CH]).sort_values(CH)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axvline(0, color="grey", linewidth=0.8)
for i, (name, d) in enumerate(series):
    ax.plot(d[CH], d[K], marker="o", ms=4, color=PALETTE[i % len(PALETTE)], linewidth=1.8, label=name)
ax.set_xlabel(CH)
ax.set_ylabel(K)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads spider-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#mc-distribution

Monte Carlo distribution

Across all simulated scenarios, how likely is each outcome — and of missing the target?

Demo data · seed 20261101 · 20,000 rows · default settings · 640 × 360

How to read it

  1. Read the histogram as the spread of simulated outcomes.
  2. Read the curve for the cumulative chance, on the right axis.
  3. Read the shaded part as the chance of missing the target.
  1. Callout 1: The chance of missing the target.
  2. Callout 2: P5, P50 and P95.
  3. Callout 3: The cumulative chance.

Watch out

  • The result is only as good as your input distributions. Simulated precision isn't real-world precision.

Defaults

Target (null = none)
0
The outcome you want to reach; the chart shows the chance of missing it.
Range -1,000,000,000,000 to 1,000,000,000,000, step 1
Percentiles
P5 · P50 · P95
Which percentiles to mark.
Also: P10 · P50 · P90 · P1 · P50 · P99 · P25 · P50 · P75

Pinned in the code

  • Raw draws are binned on equal-width edges (Sturges × 2, 30–80 bins); percentiles are type 7 (R default) on the draws. Pre-binned input is drawn as sent, with percentiles interpolated within bins.
  • P(value < target) counts draws strictly below the target. Draws come from the shared random stream, so Python and R simulations agree draw for draw.
# Monte Carlo distribution — Codesplash Chart Lab (recipe "mc-distribution")
# controls: target=0, percentiles=5-50-95
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("mc-distribution-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

V = "profit ($k)"
BL = None
BH = None
N = None
TARGET, PCTS = 0, [5, 50, 95]
fig, ax = plt.subplots(figsize=(8, 4.5))
if V:
    v = df[V].dropna().to_numpy()
    k = max(30, min(80, 2 * int(np.ceil(np.log2(len(v)) + 1))))
    w = np.full(len(v), 1 / len(v))
    counts, edges, _ = ax.hist(v, bins=k, weights=w, color=PALETTE[0], alpha=0.55)
    pv = np.percentile(v, PCTS)  # numpy's "linear" = type 7
else:
    b = df.dropna(subset=[BL, BH, N]).sort_values(BL)
    share = b[N] / b[N].sum()
    ax.bar(b[BL], share, width=b[BH] - b[BL], align="edge", color=PALETTE[0], alpha=0.55)
    edges, counts = np.r_[b[BL].to_numpy(), b[BH].iloc[-1]], share.to_numpy()
    cum = np.r_[0, np.cumsum(counts)]
    pv = np.interp(np.array(PCTS) / 100, cum, edges)
ax2 = ax.twinx()
ax2.plot(edges, np.r_[0, np.cumsum(counts)], color="black", linewidth=1.4)
ax2.set_ylim(0, 1.02)
ax2.set_ylabel("cumulative probability")
for p, x in zip(PCTS, pv):
    ax.axvline(x, color=PALETTE[2], linestyle="--", linewidth=1)
    ax.annotate(f"P{p}", (x, 1), xycoords=("data", "axes fraction"), ha="left", va="top", fontsize=8, color=PALETTE[2])
if TARGET is not None:
    ax.axvline(TARGET, color="#ce5342", linewidth=1.6)
ax.set_xlabel(V or "value")
ax.set_ylabel("share of draws")
plt.show()

Needs pandas, numpy, matplotlib · reads mc-distribution-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#efficient-frontier

Efficient frontier

Which portfolios give the most return for each level of risk, and where does the chosen one sit?

Demo data · seed 20261101 · 31 rows · default settings · 640 × 360

How to read it

  1. Read x as risk and y as return.
  2. The curve is the best return at each risk.
  3. Points below it are beatable; the marker is the chosen portfolio.
  1. Callout 1: The chosen portfolio.
  2. Callout 2: A frontier point: more return, more risk.
  3. Callout 3: An asset below the frontier: beatable.

Watch out

  • It's very sensitive to estimated returns, so small estimation errors move the frontier a lot.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Frontier rows are joined in order of risk; values within ±2 on both axes are shown as percentages.
# Efficient frontier — Codesplash Chart Lab (recipe "efficient-frontier")
# 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("efficient-frontier-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["frontier", "asset"])

R = "volatility"
RET = "expected return"
LABEL = "label"
CH = "chosen"
KIND = "kind"
d = df.dropna(subset=[R, RET])
asset = d[KIND].astype(str) == "asset" if KIND else pd.Series(False, index=d.index)
f, a = d[~asset].sort_values(R), d[asset]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(f[R], f[RET], marker="o", ms=3, color=PALETTE[0], linewidth=2, label="efficient frontier")
ax.scatter(a[R], a[RET], facecolors="none", edgecolors="grey", s=36, label="assets")
if LABEL:
    for _, r in a.iterrows():
        ax.annotate(str(r[LABEL]), (r[R], r[RET]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
if CH:
    ch = d[d[CH].astype(bool)]
    ax.scatter(ch[R], ch[RET], color=PALETTE[1], s=80, zorder=3, label="chosen")
ax.set_xlabel(R)
ax.set_ylabel(RET)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads efficient-frontier-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#regret-bands

Cumulative regret

Which bandit policy loses the least reward compared with always playing the best arm?

Demo data · seed 20261101 · 204 rows · default settings · 640 × 360

How to read it

  1. Read each line as how much reward a policy loses compared with always picking the best arm.
  2. A curve that flattens has stopped losing: it found the best arm.
  3. Read the band for replication spread.
  1. Callout 1: Thompson sampling flattens early.
  2. Callout 2: A fixed split keeps losing at the same rate.
  3. Callout 3: Band: the spread across runs.

Watch out

  • Lower regret may trade against slower learning: decide what you need the result for.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Regret_t = Σ (μ* − μ of the arm played) up to round t; the band spans the replication quantiles the engine sends. Replications share the random stream, so Python and R simulations match.
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("regret-bands-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

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 = "round"
Y = "cumulative regret"
LO = "p10"
HI = "p90"
G = "policy"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0)
    ax.plot(d[X], d[Y], color=col, linewidth=2, label=name or Y, linestyle=SERIES_DASHES[i % 8])  # dash per group, as in the app
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads regret-bands-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#arm-share

Arm shares

How quickly does each policy shift its plays toward the best arm?

Demo data · seed 20261101 · 408 rows · default settings · 640 × 360

How to read it

  1. Read each panel as one policy's share of plays per arm over rounds.
  2. A policy that shifts quickly to one arm is exploiting early.
  3. Compare how soon the best arm's band takes over.
  1. Callout 1: The best arm's share grows.
  2. Callout 2: Early: exploring all arms.

Watch out

  • Very fast convergence can lock on to a wrong arm if rewards change.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Shares are renormalized to sum to 1 at each round; long series are thinned to about 400 rounds per panel.
# Arm shares — Codesplash Chart Lab (recipe "arm-share")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("arm-share-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (4.0%)", "B (4.6%)", "C (5.1%)", "D (6.0%)"])
df["policy"] = pd.Categorical(df["policy"].astype("string"), categories=["UCB1", "Thompson sampling"])

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)))
T = "round"
S = "share of plays"
ARM = "arm"
POL = "policy"
policies = levels_of(df[POL]) if POL else [None]
arms = levels_of(df[ARM])
fig, axes = plt.subplots(1, len(policies), figsize=(4 * len(policies) + 1, 3.8), sharey=True, squeeze=False)
for ax, pol in zip(axes[0], policies):
    d = df if pol is None else df[df[POL].astype(str) == str(pol)]
    wide = d.pivot_table(index=T, columns=ARM, values=S, aggfunc="sum", observed=False).reindex(columns=arms).fillna(0)
    wide = wide.div(wide.sum(axis=1).replace(0, 1), axis=0)  # shares sum to 1
    ax.stackplot(wide.index, wide.T.values, colors=PALETTE[: len(arms)], labels=[str(a) for a in arms], alpha=0.85,
                 hatch=[SERIES_HATCHES[i % 8] for i in range(len(arms))], hatchcolor=HATCH_INK, linewidth=0)  # texture per arm, as in the app
    ax.set_title(str(pol) if pol is not None else "", fontsize=10, loc="left")
    ax.set_xlabel(T)
axes[0, 0].set_ylabel("share of plays")
axes[0, 0].legend(fontsize=8, loc="lower left")
plt.show()

Needs pandas, numpy, matplotlib · reads arm-share-demo.csv · app theme from the optional codesplash helper

Simulation, optimization & decisions

svg#group-metrics

Metrics by group (fairness)

Do a model's decisions or error rates differ across groups, and by how much?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Read one panel per metric with each group's value and interval.
  2. Check the largest gap in the title.
  3. Use the tolerance band: is a difference larger than you can accept?
  1. Callout 1: The largest gap on this metric.
  2. Callout 2: One group's value.
  3. Callout 3: The reference line.

Watch out

  • Fairness metrics can't all be equal at once when base rates differ: choose by purpose.

Defaults

Reference line (null = none)
0
Draw a line at a value you want to compare with.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Tolerance band lower (equal bounds = none)
0
The lower end of the differences you would accept.
Range -1,000,000,000 to 1,000,000,000, step 0.01
Tolerance band upper
0
The upper end of the differences you would accept.
Range -1,000,000,000 to 1,000,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Gap = largest minus smallest group value per metric (demographic parity difference for selection rate, equal-opportunity difference for TPR); the engine reports ratios and equalized-odds differences in its table.
  • Panels on [0, 1] when every value is a rate; intervals are the engine's bootstrap CIs (shared random stream).
# Metrics by group (fairness) — Codesplash Chart Lab (recipe "group-metrics")
# controls: reference=0, band_low=0, band_high=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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("group-metrics-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["Group A", "Group B", "Group C", "Group D"])
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["selection rate", "true positive rate", "false positive rate"])

_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)))
G = "group"
M = "metric"
V = "value"
LO = "ci_low"
HI = "ci_high"
REFERENCE, BAND = 0, (0, 0)
metrics, groups = levels_of(df[M]), levels_of(df[G])
fig, axes = plt.subplots(1, len(metrics), figsize=(3.2 * len(metrics) + 1.5, 3.6), sharey=True, squeeze=False)
for ax, m in zip(axes[0], metrics):
    d = df[df[M].astype(str) == str(m)]
    d = d.set_index(d[G].astype(str)).reindex([str(g) for g in groups])
    y = np.arange(len(groups))[::-1]
    if None not in BAND and BAND[1] > BAND[0]: ax.axvspan(*BAND, color="#19966e", alpha=0.1, lw=0)
    if REFERENCE is not None: ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
    if LO and HI: ax.hlines(y, d[LO], d[HI], colors=PALETTE[: len(groups)], linewidth=2)
    for j in range(len(groups)):  # marker shape per group, as in the app
        ax.scatter(d[V].iloc[j], y[j], color=PALETTE[j % len(PALETTE)], marker=SERIES_MARKERS[j % 8], s=36, zorder=3)
    ax.set_title(f"{m} · gap {d[V].max() - d[V].min():.3f}", fontsize=10, loc="left")
axes[0, 0].set_yticks(np.arange(len(groups))[::-1], [str(g) for g in groups])
plt.show()

Needs pandas, numpy, matplotlib · reads group-metrics-demo.csv · app theme from the optional codesplash helper

Advanced models

Specification curves, random effects (caterpillar), recurrent events, item response curves, parallel analysis, decision curves, prediction intervals and drift.

12

Advanced models

svg#spec-curve

Specification curve

Does the conclusion survive every reasonable way of specifying the analysis?

Demo data · seed 20261101 · 144 rows · default settings · 640 × 360

How to read it

  1. Read the top panel as estimates across every specification, ranked by size.
  2. Read the dots below for which choices each specification uses.
  3. Look for choices that line up at one end: they drive the result.
  1. Callout 1: Estimates sorted by size.
  2. Callout 2: The choices behind each specification.
  3. Callout 3: The median and the share with the same sign.

Watch out

  • The specifications aren't independent, and the set you list shapes the picture.

Defaults

Null value
0
The value that means no effect.
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.
  • Input has one row per specification × choice dimension; specifications are drawn in the order of `spec` (the engine ranks them by estimate).
  • The summary counts significant specifications and those sharing the median's sign; Simonsohn et al.'s permutation inference is reported by the engine when run.
# Specification curve — Codesplash Chart Lab (recipe "spec-curve")
# controls: null=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("spec-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["dimension"] = pd.Categorical(df["dimension"].astype("string"), categories=["covariates", "outliers", "outcome", "sample"])

SPEC = "specification"
E = "effect (SD)"
LO = "ci_low"
HI = "ci_high"
SIG = "significant"
DIM = "dimension"
OPT = "option"
NULL = 0
specs = df.drop_duplicates(SPEC).sort_values(SPEC)
rows = df[[DIM, OPT]].astype(str).drop_duplicates().values.tolist()
fig, (ax, bx) = plt.subplots(2, 1, figsize=(8, 6), sharex=True, gridspec_kw=dict(height_ratios=[2, 1.3]))
col = np.where(specs[SIG].astype(bool), PALETTE[0], "grey")
if LO and HI: ax.vlines(specs[SPEC], specs[LO], specs[HI], colors=col, alpha=0.35)
ax.scatter(specs[SPEC], specs[E], c=col, s=12)
ax.axhline(NULL, color="grey", linewidth=0.8)
ax.axhline(specs[E].median(), color=PALETTE[1], linestyle="--", linewidth=1)
ax.set_ylabel(E)
for k, (dim, opt) in enumerate(rows):
    used = df[(df[DIM].astype(str) == dim) & (df[OPT].astype(str) == opt)][SPEC]
    bx.scatter(used, [k] * len(used), color="black", s=6)
bx.set_yticks(range(len(rows)), [f"{d}: {o}" for d, o in rows], fontsize=7)
bx.invert_yaxis()
bx.set_xlabel("specifications, ranked by estimate")
plt.show()

Needs pandas, numpy, matplotlib · reads spec-curve-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#caterpillar

Caterpillar plot

How much do groups differ in a mixed model, and which deviate clearly from the average?

Demo data · seed 20261101 · 36 rows · default settings · 640 × 360

How to read it

  1. Read each row as one group's estimated deviation from average.
  2. Rows are sorted by size.
  3. Intervals that stay away from zero mark groups that differ from average.
  1. Callout 1: A group above average.
  2. Callout 2: A group below average.
  3. Callout 3: Reference: the average group.

Watch out

  • These are shrunken estimates: small groups get pulled towards the average.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Groups are sorted by estimate within each term (largest at the top); with many groups, labels are hidden and marks shrink. Intervals are the engine's conditional (posterior) intervals.
# Caterpillar plot — Codesplash Chart Lab (recipe "caterpillar")
# 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("caterpillar-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["term"] = pd.Categorical(df["term"].astype("string"), categories=["(Intercept)", "Days"])

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)))
G = "subject"
E = "random effect (ms)"
LO = "ci_low"
HI = "ci_high"
TERM = "term"
terms = levels_of(df[TERM]) if TERM else [None]
fig, axes = plt.subplots(1, len(terms), figsize=(4 * len(terms) + 1, 5), squeeze=False)
for ax, term in zip(axes[0], terms):
    d = (df if term is None else df[df[TERM].astype(str) == str(term)]).sort_values(E)
    y = np.arange(len(d))
    out = (d[LO] > 0) | (d[HI] < 0) if LO and HI else pd.Series(False, index=d.index)
    col = np.where(out, PALETTE[0], "grey")
    if LO and HI: ax.hlines(y, d[LO], d[HI], colors=col)
    ax.scatter(d[E], y, c=col, s=14, zorder=3)
    ax.axvline(0, color="grey", linewidth=0.8)
    ax.set_yticks(y, d[G].astype(str), fontsize=7)
    ax.set_title(str(term) if term is not None else "", fontsize=10, loc="left")
    ax.set_xlabel(E)
plt.show()

Needs pandas, numpy, matplotlib · reads caterpillar-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#mcf-plot

Mean cumulative function

For repeated events (readmissions, failures, purchases), how many events per subject accumulate over time?

Demo data · seed 20261101 · 71 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the mean number of events per subject by time.
  2. Compare the curves between groups.
  3. A straight line suggests a constant event rate; bending up, an increasing one.
  1. Callout 1: Placebo accumulates more events.
  2. Callout 2: Treatment accumulates fewer.
  3. Callout 3: Band: uncertainty.

Watch out

  • Unlike survival curves, it can go above 1, because it counts repeat events.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Steps hold the value until the next event time (right-continuous); bands are the engine's (Lawless–Nadeau robust variance by default).
# Mean cumulative function — Codesplash Chart Lab (recipe "mcf-plot")
# 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("mcf-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["placebo", "treatment"])

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 = "months"
Y = "mean recurrences per patient"
LO = "ci_low"
HI = "ci_high"
G = "arm"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
    d = df if name is None else df[df[G].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    col = PALETTE[i % len(PALETTE)]
    if LO and HI:
        ax.fill_between(d[X], d[LO], d[HI], color=col, alpha=0.15, lw=0, step="post")
    ax.step(d[X], d[Y], color=col, linewidth=2, label=name or Y, where="post")
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G: ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads mcf-plot-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#item-curves

Item characteristic curves

How does the probability of each response change with the latent trait, item by item?

Demo data · seed 20261101 · 405 rows · default settings · 640 × 360

How to read it

  1. Read each curve as the probability of a correct response at each ability.
  2. Curves further right are harder items.
  3. Steeper curves separate people better.
  1. Callout 1: An easier item.
  2. Callout 2: A harder item.
  3. Callout 3: A steep curve: a discriminating item.

Watch out

  • Item parameters assume the model fits: check item fit before you trust the curves.

Defaults

Curves
Characteristic (probability)
Show one curve per item or one per response category.
Also: Information

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Without a category role every item is a curve in one panel; with one, each item is a panel and each category a curve (graded or partial-credit models).
# Item characteristic curves — Codesplash Chart Lab (recipe "item-curves")
# controls: kind=icc
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("item-curves-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["item"] = pd.Categorical(df["item"].astype("string"), categories=["Q1 (easy)", "Q2", "Q3", "Q4", "Q5 (hard)"])

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)))
TH = "ability θ"
P = "P(correct)"
ITEM = "item"
CAT = None
items = levels_of(df[ITEM])
panels = items if CAT else [None]
fig, axes = plt.subplots(1, len(panels), figsize=(min(16, 3.4 * len(panels) + 1), 3.8), sharey=True, squeeze=False)
for ax, item in zip(axes[0], panels):
    d = df if item is None else df[df[ITEM].astype(str) == str(item)]
    key = CAT if CAT else ITEM
    for i, lv in enumerate(levels_of(d[key])):
        s = d[d[key].astype(str) == str(lv)].sort_values(TH)
        ax.plot(s[TH], s[P], color=PALETTE[i % len(PALETTE)], linestyle=SERIES_DASHES[i % 8], linewidth=1.8, label=str(lv))  # dash per curve, as in the app
    ax.set_title(str(item) if item is not None else "", fontsize=10, loc="left")
    ax.set_xlabel(TH)
axes[0, 0].set_ylabel("P(response)")
axes[0, 0].legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads item-curves-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#test-information

Test information

Over which range of the trait does the test measure precisely?

Demo data · seed 20261101 · 81 rows · default settings · 640 × 360

How to read it

  1. Read the solid curve as how precisely the test measures at each ability.
  2. Read the dashed curve as the standard error on the right axis.
  3. Precise where the solid curve is high and the dashed is low.
  1. Callout 1: Most precise at this ability.
  2. Callout 2: The standard error is large at the extremes.

Watch out

  • A single reliability number hides this: precision varies across people.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Information is the sum of item informations; SE(θ) = 1/√I(θ) when the engine sends it.
# Test information — Codesplash Chart Lab (recipe "test-information")
# 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("test-information-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

TH = "ability θ"
INFO = "test information"
SE = "standard error"
d = df.dropna(subset=[TH, INFO]).sort_values(TH)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(d[TH], d[INFO], color=PALETTE[0], linewidth=2, label="test information")
ax.set_xlabel(TH)
ax.set_ylabel(INFO)
if SE:
    ax2 = ax.twinx()
    ax2.plot(d[TH], d[SE], color=PALETTE[1], linestyle="--", linewidth=1.6)
    ax2.set_ylabel(SE)
plt.show()

Needs pandas, numpy, matplotlib · reads test-information-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#parallel-analysis

Parallel analysis

How many factors stand out above what random data would produce?

Demo data · seed 20261101 · 24 rows · default settings · 640 × 360

How to read it

  1. Read the solid line as your data's eigenvalues.
  2. Read the dashed line as those of random data of the same size.
  3. Keep factors where the solid line stays above the dashed one.
  1. Callout 1: The first factor stands far above random.
  2. Callout 2: The last factor above random.
  3. Callout 3: Below random: noise.

Watch out

  • It's a guide: factor interpretation still decides what to keep.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Retained = the leading run of factors whose observed eigenvalue exceeds the simulated one (the 95th percentile or the mean of the simulations, as the engine sends). The Kaiser line is shown for reference only — it over-extracts.
# Parallel analysis — Codesplash Chart Lab (recipe "parallel-analysis")
# 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("parallel-analysis-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["observed", "simulated (95th percentile)"])

F = "factor"
E = "eigenvalue"
K = "kind"
fig, ax = plt.subplots(figsize=(8, 4.5))
for name, d in df.dropna(subset=[F, E]).sort_values(F).groupby(K, observed=True, sort=False):
    sim = any(w in str(name).lower() for w in ("sim", "random", "parallel"))
    ax.plot(d[F], d[E], marker="o", ms=4, color="grey" if sim else PALETTE[0], linestyle="--" if sim else "-", linewidth=1.6 if sim else 2, label=str(name))
ax.axhline(1, color="grey", linestyle=":", linewidth=1)
ax.set_xlabel(F)
ax.set_ylabel(E)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads parallel-analysis-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#decision-curve

Decision curve

Across the range of risk thresholds a clinician might use, does acting on the model do more good than treating everyone or no one?

Demo data · seed 20261101 · 200 rows · default settings · 640 × 360

How to read it

  1. Read x as the risk threshold you'd act on.
  2. Read y as net benefit: true positives minus false positives weighted by the threshold.
  3. A model is useful where it's above treat-all and treat-none.
  1. Callout 1: The model above the treat-all line.
  2. Callout 2: Treat none: zero benefit.
  3. Callout 3: Treat all: benefit falls as the threshold rises.

Watch out

  • Only thresholds you'd really use matter, so ignore the rest of the curve.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Net benefit = TP/n − FP/n · pₜ/(1 − pₜ). Strategies named all/treat all and none/treat none are drawn dashed; the y axis is clipped at −5% of the maximum so the treat-all line does not dominate (as in dcurves).
# Decision curve — Codesplash Chart Lab (recipe "decision-curve")
# 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("decision-curve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["strategy"] = pd.Categorical(df["strategy"].astype("string"), categories=["Full model", "Clinical score", "Treat all", "Treat none"])

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)))
T = "threshold probability"
NB = "net benefit"
S = "strategy"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values(T)))
top = df[NB].max()
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(0, color="grey", linewidth=0.8)
k = 0
for name, d in series:
    low = str(name).lower()
    if "all" in low or "none" in low:
        ax.plot(d[T], d[NB], color="grey" if "all" in low else "black", linestyle="--", linewidth=1.2, label=name)
    else:
        ax.plot(d[T], d[NB], color=PALETTE[k % len(PALETTE)], linewidth=2, label=name)
        k += 1
ax.set_ylim(-0.05 * top, top * 1.08)  # clip the treat-all line, as dcurves does
ax.set_xlabel(T)
ax.set_ylabel(NB)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads decision-curve-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#interval-coverage

Interval coverage

Do prediction intervals contain the truth as often as they promise?

Demo data · seed 20261101 · 18 rows · default settings · 640 × 360

How to read it

  1. Read x as the promised coverage, y as what was achieved.
  2. On the diagonal: honest intervals.
  3. Below the diagonal: intervals are too narrow.
  1. Callout 1: On the diagonal: honest intervals.
  2. Callout 2: Below the diagonal: overconfident.
  3. Callout 3: The perfect-calibration line.

Watch out

  • Overall coverage can hide subgroups that are badly covered.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Points below the diagonal under-cover (intervals too narrow); split-conformal intervals guarantee at least nominal coverage on exchangeable data. Compare widths only between methods with adequate coverage.
# Interval coverage — Codesplash Chart Lab (recipe "interval-coverage")
# 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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("interval-coverage-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["method"] = pd.Categorical(df["method"].astype("string"), categories=["Split conformal", "CQR", "Gaussian (model SD)"])

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)))
N = "nominal coverage"
C = "empirical coverage"
W = "mean width ($100k)"
M = "method"
groups = levels_of(df[M]) if M else [None]
series = []
for name in groups:
    d = df if name is None else df[df[M].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[N]).sort_values(N)))
fig, ax = plt.subplots(figsize=(6, 5))
lo = max(0, min(df[N].min(), df[C].min()) - 0.05)
ax.plot([lo, 1], [lo, 1], color="grey", linestyle="--", linewidth=1, label="perfect calibration")
for i, (name, d) in enumerate(series):
    ax.plot(d[N], d[C], marker=SERIES_MARKERS[i % 8], linestyle=SERIES_DASHES[i % 8], ms=5, color=PALETTE[i % len(PALETTE)], linewidth=1.8, label=name or C)  # dash + marker per method, as in the app
ax.set_xlim(lo, 1)
ax.set_ylim(lo, 1)
ax.set_xlabel(N)
ax.set_ylabel(C)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads interval-coverage-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#interval-plot

Prediction intervals

Which observations fall outside their prediction intervals, and how wide are the intervals?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read each bar as a row's prediction interval.
  2. Dots are the actual values.
  3. Red dots fall outside: are they at some part of the range or evenly scattered?
  1. Callout 1: One row's interval.
  2. Callout 2: A value outside its interval.
  3. Callout 3: The share covered.

Watch out

  • Width matters too: wide intervals are easy to keep correct but tell you little.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • Observations are ordered by `index` as sent (often sorted by the prediction or by time). Coverage counts actuals within [lower, upper].
# Prediction intervals — Codesplash Chart Lab (recipe "interval-plot")
# 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("interval-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

I = "sale (sorted by prediction)"
A = "price ($100k)"
P = "predicted"
LO = "lower"
HI = "upper"
d = df.dropna(subset=[I, LO, HI]).sort_values(I)
inside = (d[A] >= d[LO]) & (d[A] <= d[HI])
fig, ax = plt.subplots(figsize=(8, 4.5))
if len(d) > 400:
    ax.fill_between(d[I], d[LO], d[HI], color=PALETTE[0], alpha=0.25, lw=0)
else:
    ax.vlines(d[I], d[LO], d[HI], color=PALETTE[0], alpha=0.45, linewidth=3)
ax.plot(d[I], d[P], color=PALETTE[0], linewidth=1.2, label="prediction")
ax.scatter(d.loc[inside, I], d.loc[inside, A], color="black", s=8, label=f"actual inside ({inside.mean():.1%} covered)")
ax.scatter(d.loc[~inside, I], d.loc[~inside, A], color="#ce5342", s=14, label="actual outside")
ax.set_xlabel(I)
ax.set_ylabel(A)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads interval-plot-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#drift-timeline

Drift over time

Which features of the scoring data are drifting away from the training data, and since when?

Demo data · seed 20261101 · 208 rows · default settings · 640 × 360

How to read it

  1. Read each line as one feature's drift statistic over scoring runs.
  2. Compare with the alert threshold.
  3. A sudden rise suggests a data change; a slow rise, gradual drift.
  1. Callout 1: This feature crossed the alert threshold.
  2. Callout 2: The threshold.
  3. Callout 3: The stable features.

Watch out

  • Input drift doesn't always hurt the model. Check performance too.

Defaults

Alert threshold (null = none)
0.25
Draw a line at the level that should raise an alert.
Range 0 to 1,000,000, step 0.01

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
  • The six features with the largest value keep a colour; others are grey. PSI rule of thumb: < 0.1 stable, 0.1–0.25 moderate, > 0.25 major shift (the default alert).
# Drift over time — Codesplash Chart Lab (recipe "drift-timeline")
# controls: threshold=0.25
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("drift-timeline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["scoring week"] = pd.to_datetime(df["scoring week"])

T = "scoring week"
V = "PSI"
F = "feature"
THRESHOLD = 0.25
d = df.dropna(subset=[T, V]).sort_values(T)
top = d.groupby(F, observed=True)[V].max().sort_values(ascending=False).index[:6]
fig, ax = plt.subplots(figsize=(8, 4.5))
for name, g in d.groupby(F, observed=True):
    k = list(top).index(name) if name in top else None
    ax.plot(g[T], g[V], color=PALETTE[k] if k is not None else "grey", alpha=1 if k is not None else 0.45, linewidth=1.8 if k is not None else 1,
            linestyle=SERIES_DASHES[k] if k is not None else "-", label=str(name) if k is not None else None)  # highlighted features also differ by dash, as in the app
if THRESHOLD is not None:
    ax.axhline(THRESHOLD, color="#ce5342", linestyle="--", linewidth=1)
    hot = d[d[V] > THRESHOLD]
    ax.scatter(hot[T], hot[V], color="#ce5342", s=16, zorder=3)
ax.set_xlabel(T)
ax.set_ylabel(V)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads drift-timeline-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#changepoint-timeline

Change-points on a timeline

When did this monitored metric shift, and which detectors noticed?

Demo data · seed 20261101 · 40 rows · default settings · 640 × 360

How to read it

  1. Read the line as one metric across monitor runs, oldest on the left.
  2. A dashed line marks a run where a detector signalled; its label says which one, or how many.
  3. Online detectors signal a little after a shift, so look at the runs just before a mark.
  1. Callout 1: A detector signalled at this run.
  2. Callout 2: The stable level before the shift.

Watch out

  • A signal is a reason to look, not proof that something changed: stable series still false-alarm a few percent of the time.
  • With fewer than 8 runs the detectors stay silent, which says nothing about whether the metric moved.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the host's numbers as given; the chart computes nothing statistical.
  • Online detectors (Page–Hinkley, CUSUM) mark the run at which they first noticed, a little after the shift; Pettitt marks the first run after its single shift; ADWIN marks the run at which it dropped older runs.
  • A signal is a reason to look, not proof: over 50 stable runs Page–Hinkley and CUSUM still false-alarm a few percent of the time.
# Change-points on a timeline — Codesplash Chart Lab (recipe "changepoint-timeline")
# 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("changepoint-timeline-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["run"] = pd.to_datetime(df["run"])

T = "run"
V = "PSI of tenure"
M = "detectors"
d = df.dropna(subset=[T, V]).sort_values(T)
fig, ax = plt.subplots(figsize=(8, 4))
if M:
    for _, row in d[d[M].fillna("").astype(str).str.len() > 0].iterrows():
        ax.axvline(row[T], color="#c0392b", linestyle="--", linewidth=1)
        ax.annotate(str(row[M]), (row[T], 1), xycoords=("data", "axes fraction"), xytext=(3, -10), textcoords="offset points", fontsize=8, color="#c0392b")
ax.plot(d[T], d[V], marker="o", markersize=3)
ax.set_xlabel(T)
ax.set_ylabel(V)
plt.show()

Needs pandas, numpy, matplotlib · reads changepoint-timeline-demo.csv · app theme from the optional codesplash helper

Advanced models

svg#noninferiority-forest

Non-inferiority to the champion

Is the candidate no worse than the champion by more than the margin we accept?

Demo data · seed 20261101 · 3 rows · default settings · 640 × 360

How to read it

  1. Each row is one metric: the dot is candidate minus champion, the bar its 95% paired interval.
  2. Right favours the candidate on every row; a lower-is-better metric is flipped first.
  3. The dashed line is the margin. The gate passes when the whole bar stays to its right.
  1. Callout 1: The whole interval clears the margin: non-inferior.
  2. Callout 2: Dashed line: the largest loss you accept.
  3. Callout 3: This interval reaches past the margin, so the gate holds.

Watch out

  • Passing means no worse than the margin, not better than the champion: read the dot and the zero line for that.
  • Widening the margin after a failure defeats the gate; choose it before you look.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the host's numbers as given; the chart computes nothing statistical.
  • Differences are oriented so right favours the candidate; a lower-is-better metric such as RMSE is flipped first.
  • Two-sided 95% paired bootstrap on the same held-out rows (2,000 resamples of rows on the shared generator), which is a one-sided 97.5% non-inferiority test at the margin.
# Non-inferiority to the champion — Codesplash Chart Lab (recipe "noninferiority-forest")
# 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("noninferiority-forest-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

L = "metric"
E = "difference"
LO = "low"
HI = "high"
MG = "margin"
d = df.dropna(subset=[E, LO, HI, MG]).reset_index(drop=True)
fig, ax = plt.subplots(figsize=(8, max(2.5, 0.7 * len(d) + 1)))
ax.axvline(0, color="#888888", linewidth=1)
for i, row in d.iterrows():
    color = "#2e8b57" if row[LO] > -row[MG] else "#c0392b"
    ax.plot([-row[MG], -row[MG]], [i - 0.4, i + 0.4], color="#c0392b", linestyle="--", linewidth=1)
    ax.plot([row[LO], row[HI]], [i, i], color=color, linewidth=2)
    ax.plot(row[E], i, "o", color=color)
ax.set_yticks(range(len(d)), d[L].astype(str))
ax.invert_yaxis()
ax.set_xlabel("candidate minus champion (right = candidate better)")
plt.show()

Needs pandas, numpy, matplotlib · reads noninferiority-forest-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

Top terms and n-grams, and how synthetic data compares with real data: densities, category shares and distances to the closest record.

10

Text & synthetic data

svg#ngram-bars

Top terms

Which words or phrases appear most in a text column, overall or by group?

Demo data · seed 20261101 · 20 rows · default settings · 640 × 360

How to read it

  1. Read bars as the most frequent terms per group.
  2. Compare panels: what's distinctive to each group?
  3. Use TF-IDF to look past words common to all groups.
  1. Callout 1: The most frequent term in this group.
  2. Callout 2: The other group's top term.
  3. Callout 3: Rarer terms.

Watch out

  • Frequency isn't importance, and terms lose their context.

Defaults

Terms per panel
20
How many terms each panel shows.
Range 3 to 50, step 1

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
  • Counts of the same term within a group are summed; ties are broken alphabetically. Tokenization (lowercasing, stop words, n-gram length) is the engine's — see the method's options.
# Top terms — Codesplash Chart Lab (recipe "ngram-bars")
# controls: top=20
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("ngram-bars-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["rating"] = pd.Categorical(df["rating"].astype("string"), categories=["1–2 stars", "4–5 stars"])

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)))
TERM = "bigram"
N = "count"
G = "rating"
TOP = 20
groups = levels_of(df[G]) if G else [None]
fig, axes = plt.subplots(1, len(groups), figsize=(4 * len(groups) + 1, 5), squeeze=False)
for i, (ax, g) in enumerate(zip(axes[0], groups)):
    d = (df if g is None else df[df[G].astype(str) == str(g)]).groupby(TERM, observed=True)[N].sum().reset_index()
    d = d.sort_values([N, TERM], ascending=[False, True]).head(TOP).iloc[::-1]  # largest on top
    ax.barh(d[TERM].astype(str), d[N], color=PALETTE[i % len(PALETTE)])
    ax.set_title(str(g) if g is not None else "", fontsize=10, loc="left")
    ax.set_xlabel(N)
plt.show()

Needs pandas, numpy, matplotlib · reads ngram-bars-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#density-compare

Real vs synthetic distribution

Does the synthetic data reproduce the shape of a numeric column?

Demo data · seed 20261101 · 152 rows · default settings · 640 × 360

How to read it

  1. Read the fill as the real data, the line as the synthetic.
  2. They should overlap closely.
  3. Look at the humps and tails: synthetic methods often smooth these away.
  1. Callout 1: Synthetic is lower at this peak.
  2. Callout 2: A good match on the second hump.

Watch out

  • Matching each column alone doesn't mean relationships between columns are kept.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
  • Both densities are evaluated on the same grid with the same bandwidth (the scorecard pins it), so differences are in the data, not the smoothing. The KS complement for the column is in the scorecard table.
# Real vs synthetic distribution — Codesplash Chart Lab (recipe "density-compare")
# 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("density-compare-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["source"] = pd.Categorical(df["source"].astype("string"), categories=["real", "synthetic (copula)"])

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 = "age"
D = "density"
S = "source"
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
    d = df if name is None else df[df[S].astype(str) == str(name)]
    series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, d) in enumerate(series):
    if i == 0:
        ax.fill_between(d[X], d[D], color=PALETTE[0], alpha=0.2, lw=0)
    ax.plot(d[X], d[D], color=PALETTE[i % len(PALETTE)], linewidth=1.6 if i == 0 else 2, label=name)
ax.set_xlabel(X)
ax.set_ylabel("density")
ax.set_ylim(bottom=0)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads density-compare-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#share-compare

Real vs synthetic category shares

Does the synthetic data keep the category proportions of the real data?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Compare the two bars per category.
  2. Sorted by the real share.
  3. Read total variation distance in the legend: lower is closer.
  1. Callout 1: A close match.
  2. Callout 2: Small categories: often lost or over-sampled.
  3. Callout 3: The overall distance.

Watch out

  • Rare categories matter most for privacy and fairness; check them directly.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
  • Total variation distance = ½ Σ |p − q| over all categories of the first two sources (1 − TVD is the scorecard's TV complement); at most 20 categories are drawn.
# Real vs synthetic category shares — Codesplash Chart Lab (recipe "share-compare")
# 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("share-compare-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["source"] = pd.Categorical(df["source"].astype("string"), categories=["real", "synthetic (CART)"])

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)))
L = "employment"
SH = "share"
S = "source"
sources = levels_of(df[S])
wide = df.pivot_table(index=L, columns=S, values=SH, aggfunc="sum", observed=False).reindex(columns=sources).fillna(0)
wide = wide.sort_values(sources[0]).tail(20)  # largest real share on top
h = 0.8 / len(sources)
fig, ax = plt.subplots(figsize=(8, 4.5))
y = np.arange(len(wide))
for j, s in enumerate(sources):
    ax.barh(y + (len(sources) - 1 - j) * h - 0.4 + h / 2, wide[s], height=h * 0.95, color=PALETTE[j % len(PALETTE)], label=str(s))
ax.set_yticks(y, wide.index.astype(str))
if len(sources) >= 2:
    ax.set_title(f"total variation distance {0.5 * (wide[sources[0]] - wide[sources[1]]).abs().sum():.3f}", fontsize=9, loc="left")
ax.set_xlabel(SH)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads share-compare-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#dcr-histogram

Distance to closest record

Are synthetic rows suspiciously close to (copies of) real training rows?

Demo data · seed 20261101 · 3,000 rows · default settings · 640 × 360

How to read it

  1. Read one histogram as synthetic rows' distance to their nearest training row.
  2. Read the other as held-out real rows' distance to training.
  3. Synthetic should not be closer: closer suggests copying.
  1. Callout 1: Distances near zero would suggest copies.
  2. Callout 2: The median distances to compare.

Watch out

  • Passing this check isn't a privacy guarantee: it tests only one kind of leak.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the run's numbers as given (computed by the Python/R engine or the host's scorecard); the chart computes nothing statistical.
  • Both histograms share edges over the joint range; dashed lines are medians. Privacy rule of thumb: the synthetic→train distribution should not sit left of holdout→train (the 5th percentiles are in the scorecard), and exact copies (distance 0) should be absent.
# Distance to closest record — Codesplash Chart Lab (recipe "dcr-histogram")
# 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("dcr-histogram-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["pair"] = pd.Categorical(df["pair"].astype("string"), categories=["synthetic → train", "holdout → train"])

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)))
D = "Gower distance"
P = "pair"
pairs = levels_of(df[P])
edges = np.linspace(df[D].min(), df[D].max(), 31)  # shared edges
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, p in enumerate(pairs):
    v = df.loc[df[P].astype(str) == str(p), D].dropna()
    ax.hist(v, bins=edges, weights=np.full(len(v), 1 / len(v)), histtype="stepfilled", alpha=0.28, color=PALETTE[i], edgecolor=PALETTE[i], linewidth=1.5, label=f"{p} · median {v.median():.3f}")
    ax.axvline(v.median(), color=PALETTE[i], linestyle="--", linewidth=1)
ax.set_xlabel(D)
ax.set_ylabel("share of rows")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads dcr-histogram-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#timestep-loss

Diffusion loss by step

At which noise levels does a diffusion model still struggle to denoise?

Demo data · seed 20261101 · 40 rows · default settings · 640 × 360

How to read it

  1. Read x as how much noise was added: small steps are nearly clean rows, large steps nearly pure noise.
  2. Read y as how far the model's denoising guess is from the truth at that step.
  3. High loss at small steps means the fine detail of the rows isn't learned yet; high loss at large steps is expected for categories.
  1. Callout 1: Small t: fine-detail denoising.
  2. Callout 2: Large t: almost pure noise.
  3. Callout 3: The categories' part.

Watch out

  • The two parts are on different scales (squared error vs KL), so compare each line's shape, not their heights.
  • A flat, low curve can also mean memorization; check the scorecard's distance to closest record.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the engine's numbers as given (codesplash ↔ codesplashr torch twins); the chart computes nothing statistical.
  • Each point is the loss on the same (up to 256) training rows with fixed shared-stream noise at one step t.
  • The Gaussian part is the mean squared error of the predicted noise; the multinomial part is the KL between the true and predicted reverse steps (−log p(x₀ | x₁) at t = 1).
# Diffusion loss by step — Codesplash Chart Lab (recipe "timestep-loss")
# 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("timestep-loss-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["part"] = pd.Categorical(df["part"].astype("string"), categories=["Gaussian (numbers)", "multinomial (categories)"])

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)))
T = "diffusion step t"
V = "loss"
C = "part"
d = df.dropna(subset=[T, V])
fig, ax = plt.subplots(figsize=(8, 4))
for name in levels_of(d[C]):
    s = d[d[C].astype(str) == name].sort_values(T)
    ax.plot(s[T], s[V], marker="o", markersize=3, label=name)
ax.set_ylim(bottom=min(0, d[V].min()))
ax.set_xlabel(f"{T} (more noise →)")
ax.set_ylabel(V)
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads timestep-loss-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#topic-sizes

Topic sizes

How large is each topic, and how many documents fit no topic at all?

Demo data · seed 20261101 · 6 rows · default settings · 640 × 360

How to read it

  1. Read each bar as one topic: its length is how many documents fell into it, and its label lists the words that set it apart.
  2. Topics are ordered from largest to smallest; the grey bar at the end holds the documents that fit no topic.
  3. Check the grey bar first: a long one means many documents were left unassigned by the settings.
  1. Callout 1: The largest topic and its distinctive words.
  2. Callout 2: Outliers: documents in no dense group.
  3. Callout 3: Class-based TF-IDF words: frequent here, rare in other topics.

Watch out

  • Topic sizes depend on the smallest topic size and the seed; rerun with other settings before trusting a small topic.
  • Distinctive words describe the topic, not every document in it.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws what the Python or R engine computed; the chart computes nothing statistical.
  • Topics are ordered by size; the outlier group (HDBSCAN noise, topic −1) is drawn grey and last whatever its size.
  • Bar labels are the topic's highest class-based TF-IDF words — words frequent in this topic and rare in the others.
  • A large outlier bar means the density clustering left many documents unassigned; it is a property of the settings (smallest topic size), not of the documents alone.
# Topic sizes — Codesplash Chart Lab (recipe "topic-sizes")
# 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("topic-sizes-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")
TOPIC = "topic"
DOCS = "documents"
TERMS = "top terms"
OUT = "outliers"
d = df.dropna(subset=[DOCS]).copy()
d["_out"] = d[OUT].astype(bool) if OUT else d[TOPIC].astype(str).str.fullmatch(r"(?i)outliers?|-1|noise")
d = d.sort_values(["_out", DOCS], ascending=[True, False], kind="stable").reset_index(drop=True)  # outliers last
fig, ax = plt.subplots(figsize=(8, 0.45 * len(d) + 1.2))
y = np.arange(len(d))[::-1]
ax.barh(y, d[DOCS], color=[GREY if o else PALETTE[0] for o in d["_out"]])
if TERMS:
    for yi, n, t in zip(y, d[DOCS], d[TERMS].fillna("")):
        ax.annotate(str(t), (n, yi), xytext=(4, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_yticks(y, d[TOPIC].astype(str))
ax.set_xlabel(DOCS)
ax.set_title("Documents per topic (outliers last)")
plt.show()

Needs pandas, numpy, matplotlib · reads topic-sizes-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#image-quality

Image brightness and sharpness

Which images are too dark, washed out, blurry or duplicated?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read each dot as one image: brightness across, sharpness up on a log scale.
  2. The shaded edges are too dark or too bright; dots under the dashed horizontal line are softer than the blur threshold.
  3. Colours give the method's flag, so you can open the flagged files in the table below the chart.
  1. Callout 1: The dark band: mean brightness below the threshold.
  2. Callout 2: The blur line: sharpness below it is flagged.
  3. Callout 3: The bright band: washed-out images.

Watch out

  • Plain images (sky, walls, product shots on white) have little detail and score as blurry without being out of focus.
  • Sharpness falls with image size, so compare images of similar size.

Defaults

Dark below
0.15
Brightness threshold drawn on the left; the method's own setting is sent with the result.
Range 0 to 1, step 0.05
Bright above
0.85
Brightness threshold drawn on the right.
Range 0 to 1, step 0.05
Blurry below
100
Sharpness threshold drawn as the horizontal line.
Range 0 to 100,000, step 10

Pinned in the code

  • Draws what the Python or R engine computed; the chart computes nothing statistical.
  • Brightness is the mean ITU-R BT.601 luma on 0–1; sharpness is the variance of the 4-neighbour Laplacian, on a log10(1 + v) axis so small and large values both show.
  • Flags follow the method's order: Duplicate first, then Dark, Bright and Blurry; an image gets one flag.
  • Sharpness falls with image size and with plain content (sky, walls): a low value is a reason to look, not proof of blur.
# Image brightness and sharpness — Codesplash Chart Lab (recipe "image-quality")
# controls: dark=0.15, bright=0.85, blur=100
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("image-quality-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["flag"] = pd.Categorical(df["flag"].astype("string"), categories=["OK", "Dark", "Bright", "Blurry", "Duplicate"])

_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")
B = "brightness"
S = "sharpness"
FLAG = "flag"
LABEL = "file"
DARK, BRIGHT, BLUR = 0.15, 0.85, 100
FLAGS = ["OK", "Dark", "Bright", "Blurry", "Duplicate"]
d = df.dropna(subset=[B, S])
flags = d[FLAG].astype(str) if FLAG else pd.Series("OK", index=d.index)
order = [f for f in FLAGS if (flags == f).any()] + sorted(set(flags) - set(FLAGS))
fig, ax = plt.subplots(figsize=(7, 5))
if LABEL:  # name the flagged files
    for _, r in d[flags != "OK"].iterrows():
        ax.annotate(str(r[LABEL]), (r[B], 1 + r[S]), xytext=(4, 3), textcoords="offset points", fontsize=7)
for i, f in enumerate(order):
    m = flags == f
    ax.scatter(d.loc[m, B], 1 + d.loc[m, S], s=24, color=GREY if f == "OK" else PALETTE[(i - ("OK" in order)) % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=f, alpha=0.8)  # marker shape per flag, as in the app
ax.set_yscale("log")  # the app plots log10(1 + sharpness)
for x in (DARK, BRIGHT):
    ax.axvline(x, color=REF, linestyle="--", linewidth=0.9)
ax.axhline(1 + BLUR, color=REF, linestyle="--", linewidth=0.9)
ax.set_xlim(0, 1)
ax.set_xlabel("brightness (mean luma, 0–1)")
ax.set_ylabel("1 + sharpness (variance of the Laplacian)")
ax.legend(fontsize=8)
ax.set_title("Brightness and sharpness of each image")
plt.show()

Needs pandas, numpy, matplotlib · reads image-quality-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#image-sizes

Image pixel sizes

Are the images a consistent size and shape, or a mix of resolutions and orientations?

Demo data · seed 20261101 · 48 rows · default settings · 640 × 360

How to read it

  1. Read each dot as one image placed by its width and height in pixels; both axes are logarithmic and share one scale.
  2. Dashed rays mark common shapes: on the diagonal images are square, below it landscape, above it portrait.
  3. Clusters of dots show the handful of resolutions in the collection; scattered dots show a mix.
  1. Callout 1: The 1:1 ray: square images.
  2. Callout 2: A landscape cluster on the 4:3 ray.
  3. Callout 3: Portrait images above the diagonal.

Watch out

  • Sizes are as stored: a phone photo with a rotation flag can land on the mirrored ray.
  • Resizing images to one size for a model hides this spread; check it before you resize.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws what the Python or R engine computed; the chart computes nothing statistical.
  • Both axes share one log domain, so equal shapes lie on the same ray and the 1:1 ray is the diagonal; landscape images fall below it, portrait above.
  • Sizes are as stored: EXIF orientation is not applied, so a rotated photo can appear on the mirrored ray.
# Image pixel sizes — Codesplash Chart Lab (recipe "image-sizes")
# 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("image-sizes-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["format"] = pd.Categorical(df["format"].astype("string"), categories=["JPEG", "PNG"])

_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)))
W = "width"
H = "height"
G = "format"
RATIOS = {"1:1": 1, "4:3": 4 / 3, "3:2": 3 / 2, "16:9": 16 / 9, "3:4": 3 / 4, "2:3": 2 / 3, "9:16": 9 / 16}
d = df[(df[W] > 0) & (df[H] > 0)]
lo, hi = max(1, min(d[W].min(), d[H].min()) / 1.5), max(d[W].max(), d[H].max()) * 1.5  # one shared log domain
fig, ax = plt.subplots(figsize=(6.5, 6))
for name, r in RATIOS.items():
    w0, w1 = max(lo, lo * r), min(hi, hi * r)
    if w1 > w0:
        ax.plot([w0, w1], [w0 / r, w1 / r], color=REF, linestyle="--", linewidth=0.8, alpha=0.5 if r == 1 else 0.3)
        ax.annotate(name, (w1, w1 / r), fontsize=7, ha="right", va="top", color=REF)
groups = levels_of(d[G]) if G else [None]
for i, k in enumerate(groups):
    m = (d[G].astype(str) == str(k)) if G else np.ones(len(d), bool)
    ax.scatter(d.loc[m, W], d.loc[m, H], s=24, color=PALETTE[i % len(PALETTE)], alpha=0.72, label=k)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(lo, hi)
ax.set_ylim(lo, hi)
ax.set_xlabel("width (px)")
ax.set_ylabel("height (px)")
if G:
    ax.legend(title=G, fontsize=8)
ax.set_title("Pixel size of each image")
plt.show()

Needs pandas, numpy, matplotlib · reads image-sizes-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#text-metric-scores

Generated-text scores per row

How do overlap scores spread across rows, metric by metric (and system by system)?

Demo data · seed 20261101 · 400 rows · default settings · 640 × 360

How to read it

  1. Read each column as one metric: dots are rows, the box spans the middle half and the thick line is the median.
  2. Compare systems side by side within a metric; the spread shows how uneven the outputs are.
  3. Look for rows scoring near zero: they often hold a correct answer worded differently, or a real failure worth reading.
  1. Callout 1: A box: the middle half of the rows for one metric and system.
  2. Callout 2: Low-scoring rows worth reading.
  3. Callout 3: Systems side by side within a metric.

Watch out

  • Corpus BLEU pools counts across rows, so it is not the median or mean of these dots.
  • Overlap metrics reward wording, not meaning; read a sample of the outputs before deciding.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws what the Python or R engine computed; the chart computes nothing statistical.
  • Row-level BLEU uses the effective n-gram order and exponential smoothing (sacreBLEU's sentence_bleu); corpus BLEU pools n-gram counts and is not the mean of these dots.
  • Boxes show the type-7 quartiles and the median; horizontal jitter is a fixed hash of the row, so the picture is the same every time.
  • Overlap metrics reward shared wording: a correct paraphrase can score low, so read the spread beside a human or LLM-as-judge review.
# Generated-text scores per row — Codesplash Chart Lab (recipe "text-metric-scores")
# 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("text-metric-scores-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["BLEU", "chrF", "ROUGE-1", "ROUGE-2", "ROUGE-L"])
df["system"] = pd.Categorical(df["system"].astype("string"), categories=["baseline", "fine-tuned"])

_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)))
M = "metric"
SCORE = "score"
SYS = "system"
d = df.dropna(subset=[M, SCORE])
metrics = levels_of(d[M])
systems = levels_of(d[SYS]) if SYS else [None]
rng = np.random.default_rng(1)  # the app uses a fixed hash; any fixed jitter shows the same spread
fig, ax = plt.subplots(figsize=(8, 4.5))
slot = 0.8 / len(systems)
for j, s in enumerate(systems):
    for i, m in enumerate(metrics):
        v = d.loc[(d[M].astype(str) == m) & ((d[SYS].astype(str) == str(s)) if SYS else True), SCORE].to_numpy()
        if not len(v):
            continue
        x = i - 0.4 + slot * (j + 0.5)
        ax.scatter(x + (rng.random(len(v)) - 0.5) * slot * 0.7, v, s=8, alpha=0.35, color=PALETTE[j % len(PALETTE)], label=s if i == 0 else None)
        ax.boxplot([v], positions=[x], widths=slot * 0.5, showfliers=False, whis=0, medianprops=dict(color="black"))
ax.set_xticks(range(len(metrics)), metrics)
ax.set_ylim(0, 100)
ax.set_ylabel("score (0–100)")
if SYS:
    ax.legend(title=SYS, fontsize=8)
ax.set_title("Score of each row, by metric")
plt.show()

Needs pandas, numpy, matplotlib · reads text-metric-scores-demo.csv · app theme from the optional codesplash helper

Text & synthetic data

svg#text-metric-ci

Corpus scores with intervals

Which system scores higher on each metric, and is the gap larger than the resampling noise?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read each row as one metric: the dot is the corpus score and the bar its bootstrap interval.
  2. Compare dots of different colours within a metric to see which system scores higher.
  3. Use the method's paired p-value to judge the gap; intervals that overlap can still differ significantly.
  1. Callout 1: A corpus score with its interval.
  2. Callout 2: A second system on the same metric.
  3. Callout 3: A wide interval: few rows or very uneven outputs.

Watch out

  • The interval reflects which rows happened to be tested, not how well the references capture good answers.
  • A higher BLEU is not a better system unless people or a judge agree.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws what the Python or R engine computed; the chart computes nothing statistical.
  • Intervals are paired bootstrap percentile intervals over rows (Koehn 2004) on the shared Wichmann–Hill stream: every replicate resamples the same rows for every system.
  • Corpus BLEU and chrF pool n-gram counts over rows before forming the score; ROUGE is the mean of row F1 values. None is a mean of the row-level dots.
  • Overlapping intervals do not by themselves mean no difference; the method's paired p-value against the first system answers that.
# Corpus scores with intervals — Codesplash Chart Lab (recipe "text-metric-ci")
# 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("text-metric-ci-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["metric"] = pd.Categorical(df["metric"].astype("string"), categories=["BLEU", "chrF", "ROUGE-1", "ROUGE-2", "ROUGE-L"])
df["system"] = pd.Categorical(df["system"].astype("string"), categories=["baseline", "fine-tuned"])

_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)))
M = "metric"
EST = "score"
LO = "lower"
HI = "upper"
SYS = "system"
d = df.dropna(subset=[M, EST])
metrics = levels_of(d[M])
systems = levels_of(d[SYS]) if SYS else [None]
fig, ax = plt.subplots(figsize=(7, 0.6 * len(metrics) * max(1, len(systems)) + 1.2))
for j, s in enumerate(systems):
    for i, m in enumerate(metrics):
        r = d[(d[M].astype(str) == m) & ((d[SYS].astype(str) == str(s)) if SYS else True)]
        if r.empty:
            continue
        y = len(metrics) - 1 - i + 0.8 * ((j + 0.5) / len(systems) - 0.5)
        r = r.iloc[0]
        ax.errorbar(r[EST], y, xerr=[[r[EST] - r[LO]], [r[HI] - r[EST]]], fmt="o", color=PALETTE[j % len(PALETTE)], capsize=3, label=s if i == 0 else None)
ax.set_yticks(range(len(metrics)), metrics[::-1])
ax.set_xlabel("score (0–100)")
if SYS:
    ax.legend(title=SYS, fontsize=8)
ax.set_title("Corpus scores with bootstrap intervals")
plt.show()

Needs pandas, numpy, matplotlib · reads text-metric-ci-demo.csv · app theme from the optional codesplash helper

  • Intervals are the engine's paired bootstrap percentiles; the emitted code draws them as given.

Evidence synthesis

Meta-analysis and combined evidence: forest and funnel plots, heterogeneity, influence and p-value distributions.

15

Evidence synthesis

svg#forest-meta

Meta-analysis forest plot

How do the studies' effects compare, and what is the pooled effect and its spread?

Demo data · seed 20261101 · 11 rows · default settings · 640 × 360

How to read it

  1. Read each row as a study: square for estimate (larger means more weight), line for interval.
  2. Read the diamond at the bottom as the pooled estimate.
  3. Compare the rows' scatter with their intervals: more scatter than expected means heterogeneity.
  1. Callout 1: One study: square and interval.
  2. Callout 2: The diamond: the pooled estimate.
  3. Callout 3: Reference line: no effect.

Watch out

  • A pooled number can hide real differences between studies. Read the prediction interval too.

Defaults

Reference (null) value
0
Where 'no effect' sits: 0 for differences, 1 for ratios.
Range -1,000 to 1,000, step 0.1
Log scale (ratios)
Off
Ratios on a log axis so equal ratios look equally far from 1.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Studies keep the engine's order; the pooled row (kind = summary) is drawn as a diamond spanning its confidence interval.
  • Marker area ∝ the study's weight in the pooled estimate (inverse variance, including τ² for random effects).
  • The dashed line through the diamond is the prediction interval (engine controls piLow/piHigh): where a new study's true effect is expected.
  • Ratios are back-transformed from the log scale and drawn on a log axis with the reference at 1.
# Meta-analysis forest plot — Codesplash Chart Lab (recipe "forest-meta")
# controls: reference=0, log=false
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("forest-meta-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["study"] = pd.Categorical(df["study"].astype("string"), categories=["Aronson 1948", "Ferguson 1949", "Rosenthal 1960", "Hart 1977", "Frimodt 1973", "Stein 1953", "Vandiviere 1973", "Madras 1980", "Coetzee 1968", "Rosenthal 1961", "Pooled (RE)"])
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["study", "summary"])

_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 fmt(v):
    """Number on a forest row, as in the app."""
    if v is None or not np.isfinite(v):
        return "—"
    return f"{v:.0f}" if abs(v) >= 100 else f"{v:.1f}" if abs(v) >= 10 else f"{v:.2f}"
LABEL = "study"
EST = "risk ratio"
LOW = "low"
HIGH = "high"
WEIGHT = "weight %"
KIND = "row"
LOG, REFERENCE = False, 0  # the "no effect" value: 0 for differences, 1 for ratios
d = df.dropna(subset=[EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1]  # first row at the top
summary = d[KIND].astype(str).eq("summary") if KIND else pd.Series(False, index=d.index)
w = pd.to_numeric(d[WEIGHT], errors="coerce") if WEIGHT else pd.Series(np.nan, index=d.index)
PI_LOW, PI_HIGH = None, None  # the prediction interval, when the result has one
w_max = w[~summary].max()
fig, ax = plt.subplots(figsize=(8.5, max(3, 0.34 * len(d) + 1.2)))
ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
for i, row in d.iterrows():
    yi = y[i]
    note = f"{fmt(row[EST])} [{fmt(row[LOW])}, {fmt(row[HIGH])}]"
    if summary[i]:
        if PI_LOW is not None:
            ax.plot([PI_LOW, PI_HIGH], [yi, yi], color=REF, linestyle=":", linewidth=1.4)
        ax.fill([row[LOW], row[EST], row[HIGH], row[EST]], [yi, yi + 0.32, yi, yi - 0.32], color=plt.rcParams["text.color"], zorder=3)
    else:
        ax.plot([row[LOW], row[HIGH]], [yi, yi], color=PALETTE[0], linewidth=1.4)
        size = 4 + 10 * np.sqrt(max(0, w[i]) / w_max) if np.isfinite(w[i]) and w_max > 0 else 7
        ax.plot(row[EST], yi, marker="s", markersize=size, color=PALETTE[0], linestyle="none", zorder=3)
        if np.isfinite(w[i]):
            note += f"  {w[i]:.1f}%"
    ax.text(1.01, yi, note, transform=ax.get_yaxis_transform(), va="center", fontsize=8, fontweight="bold" if summary[i] else "normal")
if LOG:
    ax.set_xscale("log")
ax.set_yticks(y, d[LABEL].astype(str))
ax.set_ylim(-0.7, len(d) - 0.3)
ax.set_xlabel(EST)
fig.tight_layout()
fig.subplots_adjust(right=0.74)
plt.show()

Needs pandas, numpy, matplotlib · reads forest-meta-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#meta-funnel

Funnel plot (contour-enhanced)

Are small studies' effects distributed symmetrically around the pooled effect?

Demo data · seed 20261101 · 16 rows · default settings · 640 × 360

How to read it

  1. Read y as precision: large studies at the top.
  2. Without bias, points form a symmetric funnel around the pooled effect.
  3. Look for a missing corner: small studies with unfavourable results may be absent.
  1. Callout 1: Precise studies at the top.
  2. Callout 2: Imputed studies fill the gap.
  3. Callout 3: A missing corner.

Watch out

  • Asymmetry isn't only publication bias: true heterogeneity and small-study differences produce it too.

Defaults

Significance contours
On
Shade where a study would be significant at p < .10, .05 and .01 (two-sided, against zero).

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • The y axis is the standard error, reversed so the most precise studies sit at the top (Sterne & Egger 2001).
  • Dashed lines: the pooled estimate ± 1.96·SE (engine control `center`). Shaded wedges: |effect| ≥ z·SE for p = .10, .05, .01 around zero (Peters et al. 2008).
  • Open circles are studies imputed by trim-and-fill; the dotted vertical line is the adjusted estimate. The solid coloured line is Egger's regression (effect = intercept + slope·SE).
# Funnel plot (contour-enhanced) — Codesplash Chart Lab (recipe "meta-funnel")
# controls: contours=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("meta-funnel-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")
EST = "log risk ratio"
SE = "standard error"
KIND = "study"
CENTER, ADJUSTED, CONTOURS = None, None, True
EGGER_B0, EGGER_B1 = None, None
d = df.dropna(subset=[EST, SE])
imputed = d[KIND].astype(str).eq("imputed") if KIND else pd.Series(False, index=d.index)
se_max = d[SE].max() * 1.08
fig, ax = plt.subplots(figsize=(7, 5.5))
if CONTOURS:  # where a study would be significant against zero (p 0.10–0.05, 0.05–0.01, < 0.01)
    z = stats.norm.ppf([0.95, 0.975, 0.995])
    span = max(d[EST].abs().max(), z[2] * se_max) * 1.05
    for lo, hi, alpha in ((z[0], z[1], 0.10), (z[1], z[2], 0.18), (z[2], None, 0.28)):
        outer = [span, span] if hi is None else [0, hi * se_max]
        for side in (-1, 1):
            ax.fill_betweenx([0, se_max], [0, side * lo * se_max], [side * v for v in outer], color=REF, alpha=alpha, lw=0)
if CENTER is not None:
    z95 = stats.norm.ppf(0.975)
    ax.plot([CENTER - z95 * se_max, CENTER, CENTER + z95 * se_max], [se_max, 0, se_max], color=REF, linestyle="--", linewidth=1)
    ax.axvline(CENTER, color=REF, linewidth=1)
if ADJUSTED is not None:
    ax.axvline(ADJUSTED, color=PALETTE[1], linestyle=":", linewidth=1.2, label="adjusted")
if EGGER_B0 is not None and EGGER_B1 is not None:
    ax.plot([EGGER_B0, EGGER_B0 + EGGER_B1 * se_max], [0, se_max], color=PALETTE[2], linewidth=1.2, label="Egger line")
ax.scatter(d.loc[~imputed, EST], d.loc[~imputed, SE], s=28, color=PALETTE[0], zorder=3, label="study")
if imputed.any():
    ax.scatter(d.loc[imputed, EST], d.loc[imputed, SE], s=28, facecolors="none", edgecolors=PALETTE[0], zorder=3, label="imputed")
ax.set_ylim(se_max, 0)  # the most precise studies at the top
ax.set_xlabel(EST)
ax.set_ylabel(SE)
ax.legend(fontsize=8, loc="lower right")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads meta-funnel-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#galbraith

Galbraith (radial) plot

Which studies fall outside what one common effect would predict?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Read x as precision and y as the standardized estimate.
  2. Under a common effect, points fall within ±2 of the line.
  3. Points outside the band are the studies driving heterogeneity.
  1. Callout 1: The pooled slope.
  2. Callout 2: A study outside the band.
  3. Callout 3: The ±2 band.

Watch out

  • With few studies the band says little about what's typical.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • The line's slope is the common-effect estimate (engine control `slope`); the dashed lines are ±2 standard units, where ~95% of studies fall without heterogeneity.
  • Studies outside the band are coloured and labelled.
# Galbraith (radial) plot — Codesplash Chart Lab (recipe "galbraith")
# 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("galbraith-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")
Z = "standardized estimate"
PREC = "precision (1/SE)"
LABEL = "study"
SLOPE = 0  # the common-effect estimate
d = df.dropna(subset=[Z, PREC])
x_max = d[PREC].max() * 1.08
outside = (d[Z] - SLOPE * d[PREC]).abs() > 2
fig, ax = plt.subplots(figsize=(7, 5.5))
ax.fill_between([0, x_max], [2, SLOPE * x_max + 2], [-2, SLOPE * x_max - 2], color=GREY, alpha=0.35, lw=0)
ax.plot([0, x_max], [0, SLOPE * x_max], color=REF, linewidth=1)
ax.scatter(d[PREC], d[Z], s=28, c=[PALETTE[1] if o else PALETTE[0] for o in outside], zorder=3)
if LABEL:
    for _, r in d[outside].iterrows():
        ax.annotate(str(r[LABEL]), (r[PREC], r[Z]), fontsize=8, xytext=(4, 4), textcoords="offset points")
ax.set_xlabel(PREC)
ax.set_ylabel(Z)
plt.show()

Needs pandas, numpy, matplotlib · reads galbraith-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#labbe

L'Abbé plot

Does the treatment's benefit depend on the baseline risk?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read x as the control arm's risk, y as the treatment arm's.
  2. On the diagonal: no effect.
  3. Below the diagonal: treatment has fewer events; bubble size is the study's size.
  1. Callout 1: Larger study, near the diagonal.
  2. Callout 2: Below the diagonal: favours treatment.
  3. Callout 3: The no-difference line.

Watch out

  • A trend here doesn't prove baseline risk changes the effect: arm risks share measurement error.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • x = control (group 2) risk, y = treatment (group 1) risk, equal axes; marker area ∝ participants.
  • The diagonal is no difference; a constant risk ratio is a line through the origin.
# L'Abbé plot — Codesplash Chart Lab (recipe "labbe")
# 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("labbe-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")
R1 = "risk, treatment"
R2 = "risk, control"
WEIGHT = "participants"
LABEL = "study"
d = df.dropna(subset=[R1, R2])
hi = min(1.0, max(0.05, d[[R1, R2]].to_numpy().max()) * 1.1)
w = d[WEIGHT] if WEIGHT else pd.Series(1.0, index=d.index)
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot([0, hi], [0, hi], color=REF, linestyle="--", linewidth=1)  # equal risk in both arms
ax.scatter(d[R2], d[R1], s=20 + 280 * w / w.max(), color=PALETTE[0], alpha=0.65, edgecolors=PALETTE[0])
if LABEL:
    for _, r in d.iterrows():
        ax.annotate(str(r[LABEL]), (r[R2], r[R1]), fontsize=7, xytext=(4, 3), textcoords="offset points")
ax.set_xlim(0, hi)
ax.set_ylim(0, hi)
ax.set_aspect("equal")
ax.set_xlabel(R2)
ax.set_ylabel(R1)
plt.show()

Needs pandas, numpy, matplotlib · reads labbe-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#baujat

Baujat plot

Which studies both create heterogeneity and pull the pooled result?

Demo data · seed 20261101 · 13 rows · default settings · 640 × 360

How to read it

  1. Read x as a study's contribution to heterogeneity.
  2. Read y as its influence on the pooled result.
  3. Top-right studies do both: check them first.
  1. Callout 1: This study both adds heterogeneity and moves the pooled result.
  2. Callout 2: Most studies cluster here.

Watch out

  • Don't remove a study because it sits here. Find out why it differs.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • x = (yᵢ − θ̂_FE)²/vᵢ; y = (θ̂ − θ̂₍₋ᵢ₎)² / Var(θ̂₍₋ᵢ₎) from leave-one-out fits.
  • The four studies furthest from the origin (on axes scaled to their maxima) are labelled.
# Baujat plot — Codesplash Chart Lab (recipe "baujat")
# 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("baujat-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")
X = "contribution to Q"
Y = "influence on the pooled estimate"
LABEL = "study"
d = df.dropna(subset=[X, Y]).copy()
d["_reach"] = d[X] / d[X].max() + d[Y] / d[Y].max()  # distance from the origin on normalized axes
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(d[X], d[Y], s=30, color=PALETTE[0])
for _, r in d.nlargest(4, "_reach").iterrows():
    ax.annotate(str(r[LABEL]), (r[X], r[Y]), fontsize=8, xytext=(5, 3), textcoords="offset points")
ax.set_xlim(0, d[X].max() * 1.1)
ax.set_ylim(0, d[Y].max() * 1.1)
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib · reads baujat-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#cumulative-forest

Cumulative meta-analysis

When did the evidence become clear, and has it drifted as studies accumulated?

Demo data · seed 20261101 · 12 rows · default settings · 640 × 360

How to read it

  1. Read rows top down as studies get added.
  2. Watch when the interval stops crossing the reference.
  3. A drifting estimate suggests earlier studies differ from later ones.
  1. Callout 1: With the first study alone.
  2. Callout 2: All studies: the final pooled estimate.
  3. Callout 3: The reference line.

Watch out

  • Looking repeatedly inflates false positives, as with interim analyses in a trial.

Defaults

Reference (null) value
0
The value that means no effect, such as 0 for a difference or 1 for a ratio.
Range -1,000 to 1,000, step 0.1
Log scale (ratios)
Off
Use a log axis, the natural scale for ratios: 2 and ½ sit the same distance from 1.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Row i is the meta-analysis of the first i studies in the engine's order; intervals narrow as evidence accumulates.
  • Repeated looks inflate false positives: a cumulative plot describes history, it is not a sequential test.
# Cumulative meta-analysis — Codesplash Chart Lab (recipe "cumulative-forest")
# controls: reference=0, log=false
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("cumulative-forest-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["added study"] = pd.Categorical(df["added study"].astype("string"), categories=["+ Aronson 1948", "+ Ferguson 1949", "+ Rosenthal 1960", "+ Hart 1977", "+ Frimodt 1973", "+ Stein 1953", "+ Vandiviere 1973", "+ Madras 1980", "+ Coetzee 1968", "+ Rosenthal 1961", "+ Comstock 1974", "+ Comstock 1969"])

_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 = "added study"
EST = "risk ratio"
LOW = "low"
HIGH = "high"
LOG, REFERENCE = False, 0  # the "no effect" value: 0 for differences, 1 for ratios
d = df.dropna(subset=[EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1]  # first row at the top
fig, ax = plt.subplots(figsize=(8, max(3, 0.32 * len(d) + 1.2)))
ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
ax.hlines(y, d[LOW], d[HIGH], color=PALETTE[0], linewidth=1.4)
ax.plot(d[EST], y, "o", color=PALETTE[0], markersize=5)
if LOG:
    ax.set_xscale("log")
ax.set_yticks(y, d[LABEL].astype(str))
ax.set_xlabel(EST + " (each row pools the studies so far)")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads cumulative-forest-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#influence-panel

Influence panel (leave one out)

Is any study an outlier, and how much does the result change without it?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read rows as studies, across three panels.
  2. Left: residuals beyond ±1.96 lines are outliers.
  3. Middle: Cook's distance. Right: the pooled estimate without that study.
  1. Callout 1: Outlier: a large residual.
  2. Callout 2: A large Cook's distance.
  3. Callout 3: The estimate without this study.

Watch out

  • Influence isn't a verdict: a very large and good trial may also look influential.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Residuals beyond ±1.96 are coloured; the dashed line in the third panel is the estimate from all studies (engine control `pooled`).
  • Ratios are drawn on a log scale (engine control `log`).
# Influence panel (leave one out) — Codesplash Chart Lab (recipe "influence-panel")
# 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("influence-panel-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["study"] = pd.Categorical(df["study"].astype("string"), categories=["Study 1", "Study 2", "Study 3", "Study 4", "Study 5", "Study 6", "Study 7", "Study 8", "Study 9", "Study 10"])

_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 = "study"
RS = "studentized residual"
COOKS = "Cook's distance"
EST = "risk ratio without the study"
LOW = "low"
HIGH = "high"
d = df.dropna(subset=[RS, EST]).reset_index(drop=True)
y = np.arange(len(d))[::-1]
fig, axes = plt.subplots(1, 3, figsize=(10, max(3, 0.3 * len(d) + 1.2)), sharey=True)
axes[0].axvline(-1.96, color=REF, linestyle="--", linewidth=1)
axes[0].axvline(1.96, color=REF, linestyle="--", linewidth=1)
axes[0].plot(d[RS], y, "o", color=PALETTE[0], markersize=5)
axes[0].set_xlabel(RS)
axes[1].hlines(y, 0, d[COOKS], color=PALETTE[0], linewidth=1.4)
axes[1].plot(d[COOKS], y, "o", color=PALETTE[0], markersize=4)
axes[1].set_xlabel(COOKS)
if LOW and HIGH:
    axes[2].hlines(y, d[LOW], d[HIGH], color=PALETTE[0], linewidth=1.2)
axes[2].plot(d[EST], y, "o", color=PALETTE[0], markersize=4)
axes[2].set_xlabel(EST)
axes[0].set_yticks(y, d[LABEL].astype(str))
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads influence-panel-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#metareg-bubble

Meta-regression bubble plot

Does the study effect change with a study-level moderator?

Demo data · seed 20261101 · 13 rows · default settings · 640 × 360

How to read it

  1. Read x as the moderator, y as the effect.
  2. Bubble size shows weight.
  3. Read the line's slope and band for how the effect changes.
  1. Callout 1: A study at low latitude.
  2. Callout 2: Effects grow with latitude.
  3. Callout 3: Heavier studies count more.

Watch out

  • It's ecological: a study-level trend need not hold for individuals inside studies.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • The line is b₀ + b₁·x from the engine (controls intercept, slope); the band is ± crit·√(v₀₀ + 2x·v₀₁ + x²·v₁₁) from the engine's coefficient covariance and critical value.
  • Weights are 1/(vᵢ + τ²) — larger bubbles pull the line harder.
# Meta-regression bubble plot — Codesplash Chart Lab (recipe "metareg-bubble")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("metareg-bubble-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")
X = "absolute latitude"
Y = "log risk ratio"
WEIGHT = "weight"
B0, B1 = None, None  # the fit the engine published
V00, V01, V11, CRIT = None, None, None, None
d = df.dropna(subset=[X, Y])
w = d[WEIGHT] if WEIGHT else pd.Series(1.0, index=d.index)
fig, ax = plt.subplots(figsize=(7.5, 5))
if B0 is not None and B1 is not None:
    pad = (d[X].max() - d[X].min()) * 0.05
    xs = np.linspace(d[X].min() - pad, d[X].max() + pad, 65)
    fit = B0 + B1 * xs
    if V00 is not None and V01 is not None and V11 is not None:
        se = np.sqrt(np.maximum(0, V00 + 2 * xs * V01 + xs ** 2 * V11))  # Var(b0 + b1·x) from the coefficient covariance
        crit = CRIT if CRIT is not None else stats.norm.ppf(0.975)
        ax.fill_between(xs, fit - crit * se, fit + crit * se, color=PALETTE[0], alpha=0.15, lw=0)
    ax.plot(xs, fit, color=PALETTE[0], linewidth=1.5)
ax.scatter(d[X], d[Y], s=20 + 300 * w / w.max(), facecolors="none", edgecolors=REF)
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads metareg-bubble-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#pvalue-qq

p-value Q–Q plot

Are there more small p-values than chance alone would give?

Demo data · seed 20261101 · 30 rows · default settings · 640 × 360

How to read it

  1. Read x as the expected p-value on a log scale, y as the observed one.
  2. On the diagonal: as expected under the null.
  3. Above the band: more small p-values than chance would give.
  1. Callout 1: These tests stand out above the band.
  2. Callout 2: Most p-values are on the diagonal.
  3. Callout 3: The band under the null.

Watch out

  • Correlated tests can look inflated; check for shared samples.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the p-values as given; the band is the Beta(i, k + 1 − i) 2.5% and 97.5% quantiles of the i-th smallest of k null uniforms (pointwise, not simultaneous).
  • Points above the band are coloured: more small p-values than the null predicts.
# p-value Q–Q plot — Codesplash Chart Lab (recipe "pvalue-qq")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("pvalue-qq-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")
P = "p"
p = pd.to_numeric(df[P], errors="coerce").dropna()
p = np.sort(p[(p > 0) & (p <= 1)].to_numpy())
k = len(p)
i = np.arange(1, k + 1)
expected = -np.log10(i / (k + 1))
observed = -np.log10(p)
band_low = -np.log10(stats.beta.ppf(0.975, i, k + 1 - i))  # order statistics of uniform p-values
band_high = -np.log10(stats.beta.ppf(0.025, i, k + 1 - i))
hi = max(1, expected.max(), observed.max(), band_high.max()) * 1.06
fig, ax = plt.subplots(figsize=(6, 6))
ax.fill_between(expected, band_low, band_high, color=GREY, alpha=0.5, lw=0, label="95% band under the null")
ax.plot([0, hi], [0, hi], color=REF, linestyle="--", linewidth=1)
ax.plot(expected, observed, "o", color=PALETTE[0], markersize=4)
ax.set_xlim(0, hi)
ax.set_ylim(0, hi)
ax.set_xlabel("Expected −log10 p")
ax.set_ylabel("Observed −log10 p")
ax.legend(fontsize=8, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads pvalue-qq-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#pvalue-histogram

p-value histogram

Do the p-values pile up near zero, or spread flat as under the null?

Demo data · seed 20261101 · 72 rows · default settings · 640 × 360

How to read it

  1. Read bars as how many p-values fall in each bin.
  2. A flat histogram matches a global null.
  3. A spike near zero suggests real signals; other shapes suggest a problem with the tests.
  1. Callout 1: A spike near zero: more small p-values than chance.
  2. Callout 2: The dashed line: expected under the null.

Watch out

  • A bump near 1 or a U-shape hints at a miscalibrated test, or a bias, rather than signal.

Defaults

Bins
10
How many bins to divide the range into.
Range 2 to 50, step 1

Pinned in the code

  • Bins are left-closed [a, b) except the last, which includes 1; the first bin is highlighted.
  • Under the global null with valid p-values the bars are flat at k / bins (dashed line).
# p-value histogram — Codesplash Chart Lab (recipe "pvalue-histogram")
# controls: bins=10
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("pvalue-histogram-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")
P = "p"
BINS = 10
p = pd.to_numeric(df[P], errors="coerce").dropna()
p = p[(p >= 0) & (p <= 1)]
fig, ax = plt.subplots(figsize=(7, 4.5))
counts, edges, patches = ax.hist(p, bins=np.linspace(0, 1, BINS + 1), color=PALETTE[0], alpha=0.55, edgecolor="white")
patches[0].set_alpha(1.0)  # the first bin is where real effects pile up
ax.axhline(len(p) / BINS, color=REF, linestyle="--", linewidth=1, label="expected under the global null")
ax.set_xlabel("p")
ax.set_ylabel("tests")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads pvalue-histogram-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#combine-compare

Combination methods compared

Would other combination methods have reached a different answer on these p-values?

Demo data · seed 20261101 · 11 rows · default settings · 640 × 360

How to read it

  1. Read each bar as one method's combined p-value, on a scale where longer means smaller.
  2. Find the highlighted method: the one you fixed in advance.
  3. If the methods disagree, say so: they are sensitive to different patterns of evidence.

Watch out

  • This is a sensitivity check. Picking the method with the smallest p after looking is p-hacking.

Defaults

Reference p
0.05
Draws a reference line. The conclusion rests on the method fixed in advance.
Range 0.001 to 0.2, step 0.005

Pinned in the code

  • Rows keep the engine's order; only the method fixed before results counts as the test.
  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta in Python ≡ codesplashr in R); the chart computes nothing statistical.
# Combination methods compared — Codesplash Chart Lab (recipe "combine-compare")
# controls: alpha=0.05
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("combine-compare-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")
METHOD = "method"
P = "p"
CHOSEN = "chosen"
ALPHA = 0.05
d = df.dropna(subset=[METHOD, P]).reset_index(drop=True)
d["_chosen"] = d[CHOSEN].astype(str).eq("chosen") if CHOSEN else False
d["_sig"] = -np.log10(d[P].clip(lower=1e-300))
y = np.arange(len(d))[::-1]  # the app's order: the rows as given
fig, ax = plt.subplots(figsize=(7.5, max(3, 0.34 * len(d) + 1.2)))
ax.axvline(-np.log10(ALPHA), color=REF, linestyle="--", linewidth=1, label=f"p = {ALPHA:g}")
ax.hlines(y, 0, d["_sig"], color=GREY, linewidth=1.2)
ax.scatter(d["_sig"], y, s=[60 if x else 30 for x in d["_chosen"]], c=[PALETTE[0] if x else REF for x in d["_chosen"]], zorder=3)
ax.set_yticks(y, d[METHOD].astype(str))
ax.set_xlabel("−log10 p (the highlighted method was fixed in advance)")
ax.legend(fontsize=8, loc="lower right")
fig.tight_layout()
plt.show()

Needs pandas, numpy, matplotlib · reads combine-compare-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#gosh

GOSH plot (all study subsets)

Does the pooled result depend on which studies are included, and do the subsets fall into clusters?

Demo data · seed 20261101 · 1,023 rows · default settings · 640 × 360

How to read it

  1. Read each point as one subset of the studies: x is its pooled estimate, y its I².
  2. A single compact cloud means the answer barely depends on which studies are in.
  3. Separate clouds, or a colour that sits apart, point to a study (or group) that differs from the rest.
  1. Callout 1: Marginal histogram of the subsets' estimates.
  2. Callout 2: Subsets without the flagged study.
  3. Callout 3: Subsets with it: shifted and more heterogeneous.

Watch out

  • Clusters suggest where to look; they are not a test, and a flagged study is a reason to reread it, not to drop it.
  • With few studies there are few subsets, and the cloud has little structure to read.

Defaults

All-studies estimate
0
The estimate from all studies, drawn as a solid vertical line.
Range -1,000,000 to 1,000,000, step 0.01
Null value
0
Where 'no effect' sits on the analysis scale (dashed).
Range -1,000,000 to 1,000,000, step 0.1

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta_lab in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • x is the subset's pooled estimate on the analysis scale (log for ratios), y its I² = (Q − df)/Q in percent; single-study subsets sit at I² = 0.
  • When 2^k − 1 exceeds the method's limit the engine fits a seeded random sample of subsets; very large clouds are thinned evenly for drawing (the result says so).
  • Colour marks the subsets that contain the study whose inclusion shifts the subsets' mean estimate most (engine column `group`).
# GOSH plot (all study subsets) — Codesplash Chart Lab (recipe "gosh")
# controls: center=0, reference=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("gosh-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["subset"] = pd.Categorical(df["subset"].astype("string"), categories=["with Study 7", "without Study 7"])

_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")
EST = "log odds ratio"
I2 = "I² (%)"
GROUP = "subset"
CENTER, REFERENCE = 0, 0  # all-studies estimate; null value
d = df.dropna(subset=[EST, I2])
groups = sorted(d[GROUP].astype(str).unique(), key=lambda g: not g.startswith("with ")) if GROUP else [None]
fig = plt.figure(figsize=(7, 6))
grid = fig.add_gridspec(2, 2, width_ratios=(5, 1), height_ratios=(1, 5), hspace=0.05, wspace=0.05)
ax = fig.add_subplot(grid[1, 0])
top = fig.add_subplot(grid[0, 0], sharex=ax)
side = fig.add_subplot(grid[1, 1], sharey=ax)
for i, g in enumerate(groups):
    s = d if g is None else d[d[GROUP].astype(str) == g]
    ax.scatter(s[EST], s[I2], s=4, alpha=0.5, color=PALETTE[i], label=g or "subset", linewidths=0)
    top.hist(s[EST], bins=40, color=PALETTE[i], alpha=0.45)
    side.hist(s[I2], bins=40, range=(0, 100), orientation="horizontal", color=PALETTE[i], alpha=0.45)
ax.axvline(REFERENCE, color=REF, linestyle="--", linewidth=1)
ax.axvline(CENTER, color="black", linewidth=1.2, label="all studies")
ax.set_ylim(0, 100)
ax.set_xlabel(EST)
ax.set_ylabel(I2)
top.axis("off")
side.axis("off")
ax.legend(frameon=False, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib · reads gosh-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#drapery

Drapery plot (p-value functions)

At every confidence level at once, which effects are compatible with each study and with the pooled result?

Demo data · seed 20261101 · 648 rows · default settings · 640 × 360

How to read it

  1. Read each curve as a p-value function: it peaks at p = 1 at the estimate and falls away on both sides.
  2. Where a curve crosses a horizontal level α, the two crossings are its (1 − α) confidence interval.
  3. Compare the bold pooled curve with the shaded prediction curve: the second shows where a new study's true effect may land.
  1. Callout 1: The pooled estimate: p = 1.
  2. Callout 2: The p = .05 line: crossings give the 95% CI.
  3. Callout 3: One study's p-value function.

Watch out

  • A narrow pooled curve doesn't mean the studies agree; check the prediction curve and the spread of the study curves.
  • The p at the null line is not the probability that there is no effect.

Defaults

Log scale (ratios)
Off
Ratios on a log axis so equal ratios look equally far from 1.
Null value
0
Where 'no effect' sits: 0 for differences, 1 for ratios (dashed).
Range -1,000,000 to 1,000,000, step 0.1
Level line (α)
0.05
Draws p = α; where the pooled curve crosses it is the (1 − α) confidence interval.
Range 0.001 to 0.5, step 0.005

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta_lab in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Each curve is p(θ) = P(|T| ≥ |estimate − θ| / SE): 1 at the estimate, falling on both sides. Studies use the normal distribution; the pooled curve uses z or Knapp–Hartung t; the prediction curve uses SE² + τ² with t on k − 2 df.
  • The horizontal dashed line is p = α; the bold segment on it is the pooled (1 − α) interval read off the curve.
# Drapery plot (p-value functions) — Codesplash Chart Lab (recipe "drapery")
# controls: log=false, reference=0, alpha=0.05
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]

df = pd.read_csv("drapery-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["study", "pooled", "prediction"])

_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")
X = "risk ratio"
P = "p-value"
CURVE = "curve"
KIND = "kind"
LOG, REFERENCE, ALPHA = False, 0, 0.05
d = df.dropna(subset=[X, P])
kind_of = (lambda s: s[KIND].astype(str)) if KIND else (lambda s: pd.Series("study", index=s.index))
fig, ax = plt.subplots(figsize=(7.5, 5))
for name, s in d.groupby(d[CURVE].astype(str), sort=False):
    s = s.sort_values(X)
    k = kind_of(s).iloc[0]
    if k == "prediction":
        ax.fill_between(s[X], 0, s[P], color=PALETTE[2], alpha=0.18, lw=0, label="prediction")
        ax.plot(s[X], s[P], color=PALETTE[2], alpha=0.6, linewidth=1, linestyle=SERIES_DASHES[2])  # dotted outline, as in the app
    elif k == "pooled":
        ax.plot(s[X], s[P], color="black", linewidth=2.2, label="pooled", zorder=4)
    else:
        ax.plot(s[X], s[P], color=PALETTE[0], alpha=0.55, linewidth=1)
ax.axhline(ALPHA, color=REF, linestyle="--", linewidth=1)
ax.text(1.01, ALPHA, f"{100 * (1 - ALPHA):g}% CI", transform=ax.get_yaxis_transform(), va="center", fontsize=8)
ax.axvline(REFERENCE, color=REF, linestyle=":", linewidth=1)
if LOG:
    ax.set_xscale("log")
ax.set_ylim(0, 1)
ax.set_xlabel(X)
ax.set_ylabel("p-value")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads drapery-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#pcurve

p-curve

Do the significant results look like they come from real effects (right-skewed) or from selective reporting of null effects (flat or left-skewed)?

Demo data · seed 20261101 · 5 rows · default settings · 640 × 360

How to read it

  1. Read only the significant results: each point is the share of their p-values in one .01-wide bin.
  2. A curve that falls from left to right (many very small p-values) is right-skewed, as real effects produce.
  3. A flat curve near 20% looks like no effect; a curve rising towards .05 suggests p-hacking.
  1. Callout 1: Many p-values below .01: right skew.
  2. Callout 2: The flat 20% line: no true effect.
  3. Callout 3: The 33%-power curve: weak evidence.

Watch out

  • p-curve says whether the significant results carry evidential value, not how large the effect is.
  • With only a handful of significant results the bins are coarse; trust the Stouffer tests over the picture.

Defaults

Significant results
0
Number of significant results behind the curve, shown in the legend (0 hides it).
Range 0 to 100,000, step 1

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta_lab in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Bins are (0, .01], (.01, .02], … (.04, .05] of two-sided p-values from results significant in the favoured direction.
  • With no true effect p-values are uniform below .05, so every bin holds 20%. The 33%-power curve is what studies with power 1/3 would give (z tests, as χ²(1)).
# p-curve — Codesplash Chart Lab (recipe "pcurve")
# controls: k=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("pcurve-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

BIN = "p-value"
OBS = "observed %"
NULL = "no effect %"
P33 = "33% power %"
K = 0  # significant results behind the curve (0 = not shown)
d = df.dropna(subset=[BIN, OBS]).sort_values(BIN)
ticks = [f"{b:.2f}".lstrip("0") for b in d[BIN]]
x = np.arange(len(d))
fig, ax = plt.subplots(figsize=(6.5, 4.5))
if NULL:
    ax.plot(x, d[NULL], color=PALETTE[3], linestyle=":", linewidth=1.4, label="no effect")
if P33:
    ax.plot(x, d[P33], color=PALETTE[2], linestyle="--", linewidth=1.4, label="33% power")
ax.plot(x, d[OBS], color=PALETTE[0], linewidth=2.2, marker="o", label=f"observed ({K:g} significant)" if K else "observed")
for xi, v in zip(x, d[OBS]):
    ax.annotate(f"{v:.0f}%", (xi, v), textcoords="offset points", xytext=(0, 7), ha="center", fontsize=8)
ax.set_xticks(x, ticks)
ax.set_ylim(0, 100)
ax.set_xlabel(f"p-value (bin upper edge; {BIN})")
ax.set_ylabel(f"share of significant results (%; {OBS})")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads pcurve-demo.csv · app theme from the optional codesplash helper

Evidence synthesis

svg#selection-weights

Selection-model weight function

How much more likely were studies to be published when their one-sided p-value fell in each interval?

Demo data · seed 20261101 · 4 rows · default settings · 640 × 360

How to read it

  1. Read each step as the relative chance that a study with a one-sided p-value in that interval was published.
  2. The first interval is fixed at 1; a step at 0.4 means 40% as likely to be published as a study in the first interval.
  3. Steps near 1 everywhere mean no selection; steps that drop after .025 are what publication bias looks like.
  1. Callout 1: Significant results: weight fixed at 1.
  2. Callout 2: Non-significant results published less often.
  3. Callout 3: Reference line: no selection.

Watch out

  • The weights assume selection acted only on p-values; heterogeneity or small-study effects can mimic them.
  • Wide bands are common with fewer than about 20 studies; compare with fixed Vevea–Woods weights then.

Defaults

Log p axis
On
Log-scaled p axis from .001 to 1 so the .025 and .05 intervals are visible.
Reference weight
1
Horizontal reference: 1 means as likely to be published as the first interval.
Range 0 to 100, step 0.1

Pinned in the code

  • Draws the meta-analysis engine's numbers as given (codesplash.stats.meta_lab in Python ≡ codesplashr in R); the chart computes nothing statistical.
  • Weights are relative to the first interval (fixed at 1). A weight of 0.5 means half as likely to be published as a study in the first interval.
  • Bands are Wald 95% intervals truncated at 0; fixed (a priori) weight functions have no band.
# Selection-model weight function — Codesplash Chart Lab (recipe "selection-weights")
# controls: logP=true, reference=1
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("selection-weights-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")
LO = "p from"
HI = "p to"
W = "weight"
CL = "CI low"
CH = "CI high"
N = "studies"
LOG_P, REFERENCE = True, 1
d = df.dropna(subset=[LO, HI, W]).sort_values(LO)
x_min = min(0.001, d[HI][d[HI] > 0].min() / 2) if LOG_P else 0
left = d[LO].clip(lower=x_min)
fig, ax = plt.subplots(figsize=(7, 4.5))
if CL and CH:
    for l, h, a, b in zip(left, d[HI], d[CL], d[CH]):
        if np.isfinite(a) and np.isfinite(b):
            ax.fill_between([l, h], a, b, color=PALETTE[0], alpha=0.18, lw=0)
ax.hlines(d[W], left, d[HI], color=PALETTE[0], linewidth=2.4)
if N:
    for l, h, w, n in zip(left, d[HI], d[W], d[N]):
        ax.annotate(f"k = {n:.0f}", (np.sqrt(l * h) if LOG_P else (l + h) / 2, w), textcoords="offset points", xytext=(0, 5), ha="center", fontsize=8)
ax.axhline(REFERENCE, color=REF, linestyle="--", linewidth=1)
if LOG_P:
    ax.set_xscale("log")
ax.set_xlim(x_min, 1)
ax.set_ylim(0, None)
ax.set_xlabel(f"one-sided p-value ({LO} to {HI})")
ax.set_ylabel(f"relative chance of publication ({W})")
plt.show()

Needs pandas, numpy, matplotlib · reads selection-weights-demo.csv · app theme from the optional codesplash helper

Multivariate tests

Many outcomes at once: confidence ellipses, canonical plots, Mahalanobis Q–Q, ordinations with group centroids and distance diagnostics.

7

Multivariate tests

svg#confidence-ellipse

Confidence and data ellipses

Where do two variables' means sit, how precisely, and do the groups' clouds differ in shape?

Demo data · seed 20261101 · 150 rows · default settings · 640 × 360

How to read it

  1. Read points as rows, colour as group.
  2. Small ellipses: the region for each group's mean. Larger ones: where most rows lie.
  3. Means whose ellipses don't overlap are well apart.
  1. Callout 1: The ellipse around one group's mean.
  2. Callout 2: Tilt: how the two variables move together inside the group.
  3. Callout 3: Group colours and sizes.

Watch out

  • Ellipses assume near-normal data, and comparing two variables hides what happens on the others.

Defaults

Ellipse
Confidence ellipse of the mean
The mean's confidence region shrinks with n; the data ellipse shows the spread and correlation of the rows (compare shapes for Box's M).
Also: Data ellipse (covariance)
Level
0.95
Coverage of the ellipse (0.68 ≈ one standard deviation for data ellipses).
Range 0.5 to 0.999, step 0.01
Show the rows
On
Draw every row as well as the ellipses.

Pinned in the code

  • Each group's mean and covariance use the n − 1 denominator; ellipse axes come from the covariance's eigen decomposition.
  • Confidence ellipse of the mean: (x̄ − μ)' S⁻¹ (x̄ − μ) ≤ 2(n − 1) F₂,ₙ₋₂(level) / (n(n − 2)) — Hotelling's exact region for two variables.
  • Data ellipse: (x − x̄)' S⁻¹ (x − x̄) ≤ χ²₂(level), covering `level` of a bivariate normal population; at 68% it is the one-standard-deviation contour.
  • Two means whose confidence ellipses do not overlap differ in the joint test, but overlapping ellipses do not prove equality (as with univariate intervals).
# Confidence and data ellipses — Codesplash Chart Lab (recipe "confidence-ellipse")
# controls: kind=mean, level=0.95, points=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("confidence-ellipse-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica"])

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 ellipse(xy, kind, level):
    """data: radius √χ²₂(level). mean: Hotelling's region, √[2(n−1)F₂,ₙ₋₂(level) / (n(n−2))]."""
    n, m = len(xy), xy.mean(axis=0)
    if n <= 2:
        return np.empty((0, 2)), m
    c = np.sqrt(stats.chi2.ppf(level, 2)) if kind == "data" else np.sqrt(2 * (n - 1) * stats.f.ppf(level, 2, n - 2) / (n * (n - 2)))
    vals, vecs = np.linalg.eigh(np.cov(xy.T))
    t = np.linspace(0, 2 * np.pi, 73)
    return m + (c * vecs @ (np.sqrt(np.maximum(vals, 0))[:, None] * np.vstack([np.cos(t), np.sin(t)]))).T, m
X = "petal length (cm)"
Y = "petal width (cm)"
G = "species"
d = df.dropna(subset=[X, Y] + ([G] if G else []))
fig, ax = plt.subplots(figsize=(7, 5))
ks = levels_of(d[G]) if G else ["all rows"]
many = len(ks) > 1  # several groups: marker shape and ellipse dash per group, as in the app
for i, k in enumerate(ks):
    xy = (d[d[G].astype(str) == str(k)] if G else d)[[X, Y]].to_numpy(float)
    col = PALETTE[i % len(PALETTE)]
    ax.scatter(xy[:, 0], xy[:, 1], s=12, color=col, alpha=0.45, marker=SERIES_MARKERS[i % 8] if many else "o")
    path, m = ellipse(xy, "mean", 0.95)
    ax.plot(path[:, 0], path[:, 1], color=col, linewidth=1.8, linestyle=SERIES_DASHES[i % 8] if many else "-", label=f"{k} (n = {len(xy)})")
    ax.scatter([m[0]], [m[1]], marker="+", s=60, color=col)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads confidence-ellipse-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#canonical-plot

Canonical discriminant plot

Along which combinations of the outcomes do the groups separate, and which outcomes drive it?

Demo data · seed 20261101 · 157 rows · default settings · 640 × 360

How to read it

  1. Read points as rows on the combinations that best separate the groups.
  2. Read circles as confidence regions for each group's mean.
  3. Read arrows as outcomes: the direction each one drives.
  1. Callout 1: A group's mean and confidence circle.
  2. Callout 2: An outcome's direction.
  3. Callout 3: How much group separation this axis carries.

Watch out

  • The display only captures two dimensions. Check how much each axis explains.

Defaults

Show structure coefficients
On
Draw arrows for how each outcome relates to the canonical axes.

Pinned in the code

  • Draws the engine's canonical scores as given: coefficients scale each dimension to unit pooled within-group variance, so groups' clouds are circular and a circle of radius √(χ²(level)/nⱼ) is the confidence region of a group mean.
  • Both axes share one scale, so distances read directly as standardized (Mahalanobis) distances.
  • Arrows are structure coefficients — correlations of each outcome with the canonical scores — multiplied by one factor so the longest reaches 80% of the plot (the angle, not the length, carries meaning).
  • With one canonical dimension (two groups or a one-df effect) groups are stacked on separate lines.
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")
# controls: vectors=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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("canonical-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica", ""])

_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 = "Can1 (r = 0.98)"
Y = "Can2 (r = 0.47)"
G = "species"
KIND = "kind"
LAB = "label"
RAD = "95% radius of the mean"
kind = df[KIND].astype(str).str.lower()
points, means, struct = df[~kind.str.startswith("struct") & (kind != "mean")], df[kind == "mean"], df[kind.str.startswith("struct")]
fig, ax = plt.subplots(figsize=(7, 5))
for i, k in enumerate(levels_of(points[G])):
    g, col = points[points[G].astype(str) == str(k)], PALETTE[i % len(PALETTE)]
    ax.scatter(g[X], g[Y] if Y else 0 * g[X], s=12, color=col, alpha=0.5, marker=SERIES_MARKERS[i % 8], label=k)  # shape per group, as in the app
    for _, m in means[means[G].astype(str) == str(k)].iterrows():
        my = m[Y] if Y else 0
        ax.scatter([m[X]], [my], marker=SERIES_MARKERS[i % 8], s=50, color=col, edgecolors="white")
        if RAD and pd.notna(m[RAD]):
            ax.add_patch(plt.Circle((m[X], my), m[RAD], fill=False, color=col))
for _, s in struct.iterrows():
    sy = s[Y] if Y else 0
    ax.annotate("", xy=(s[X], sy), xytext=(0, 0), arrowprops=dict(arrowstyle="->", color=REF))
    ax.text(s[X], sy, s[LAB] if LAB else "", fontsize=8)
    ax.update_datalim([(s[X], sy)])
ax.autoscale_view()
ax.axhline(0, color=REF, linewidth=0.6, linestyle=":")
ax.axvline(0, color=REF, linewidth=0.6, linestyle=":")
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads canonical-plot-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#mahalanobis-qq

χ² Q–Q plot of Mahalanobis distances

Are the rows (or residuals) multivariate normal, and which rows are multivariate outliers?

Demo data · seed 20261101 · 120 rows · default settings · 640 × 360

How to read it

  1. Read points as rows' squared distance from the centre, sorted.
  2. Under multivariate normality they follow the dashed line.
  3. Points above the horizontal cutoff are candidate outliers.
  1. Callout 1: Rows above the cutoff: candidate multivariate outliers.
  2. Callout 2: On the line: consistent with normality.
  3. Callout 3: The χ² 97.5% cutoff.

Watch out

  • Outliers pull the mean and covariance towards themselves, which can mask other outliers.

Defaults

Degrees of freedom (number of variables)
2
The χ² reference: the number of variables behind the distances.
Range 1 to 50, step 1
Show the 95% envelope
On
Shade the range a multivariate normal sample would stay inside.

Pinned in the code

  • Plotting positions (i − ½)/n against the χ² distribution with df = number of variables; under multivariate normality the points follow the dashed identity line.
  • The shaded band is a pointwise 95% envelope: the 2.5% and 97.5% quantiles of the i-th uniform order statistic, Beta(i, n − i + 1), mapped through the χ² quantile function.
  • Distances come from the engine (rows centred on their group mean, the pooled covariance); with estimated means and covariance the exact reference is a scaled beta, so the χ² line is an approximation for small n.
  • Upward curvature in the right tail signals heavy tails (high multivariate kurtosis); isolated points above the χ² 97.5% line are candidate outliers, not proof.
# χ² Q–Q plot of Mahalanobis distances — Codesplash Chart Lab (recipe "mahalanobis-qq")
# controls: df=2, envelope=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("mahalanobis-qq-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")
D = "D² of each row"
K = 2  # degrees of freedom: the number of variables
obs = np.sort(df[D].dropna().to_numpy(float))
n = len(obs)
r = np.arange(1, n + 1)
theo = stats.chi2.ppf((r - 0.5) / n, K)  # plotting positions (i − ½)/n
lo = stats.chi2.ppf(stats.beta.ppf(0.025, r, n - r + 1), K)  # order-statistic quantiles
hi = stats.chi2.ppf(stats.beta.ppf(0.975, r, n - r + 1), K)
cut = stats.chi2.ppf(0.975, K)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.fill_between(theo, lo, hi, color=PALETTE[0], alpha=0.12, label="95% pointwise envelope")
ax.plot(theo, theo, color=REF, linestyle="--", linewidth=1)
ax.axhline(cut, color=REF, linestyle=":", linewidth=1)
ax.scatter(theo[obs <= cut], obs[obs <= cut], s=14, color=PALETTE[0], label="rows")
ax.scatter(theo[obs > cut], obs[obs > cut], s=16, color=PALETTE[1], label=f"beyond χ² 97.5% ({(obs > cut).sum()})")
ax.set_xlabel("χ² quantile")
ax.set_ylabel("Squared Mahalanobis distance")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads mahalanobis-qq-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#profile-plot

Profile plot

Do the groups' mean profiles run parallel across the measures, at the same level, and is the common profile flat?

Demo data · seed 20261101 · 15 rows · default settings · 640 × 360

How to read it

  1. Read each line as a group's means across measures.
  2. Parallel lines: the same shape, possibly at different levels.
  3. Non-parallel lines: the groups change differently.
  1. Callout 1: Lines run roughly parallel here.
  2. Callout 2: The vertical gap: the level difference.
  3. Callout 3: Measures need a common scale.

Watch out

  • Measures on different scales make the shapes meaningless.

Defaults

Show intervals
On
Add confidence intervals at each point.

Pinned in the code

  • Draws the engine's group means as given, in the measures' order; intervals are each mean's own t interval (not simultaneous, and not the test).
  • Groups are dodged slightly so overlapping intervals stay visible; lines connect consecutive measures only.
  • Profile analysis tests parallelism (equal successive differences), levels (equal group averages) and flatness (equal measure averages) — the plot shows all three at once.
# Profile plot — Codesplash Chart Lab (recipe "profile-plot")
# controls: intervals=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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("profile-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["measure"] = pd.Categorical(df["measure"].astype("string"), categories=["hour 1", "hour 2", "hour 3", "hour 4", "hour 5"])
df["treatment"] = pd.Categorical(df["treatment"].astype("string"), categories=["control", "A", "B"])

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)))
M = "measure"
V = "mean score"
G = "treatment"
LO = "CI low"
HI = "CI high"
measures = levels_of(df[M])
pos = {m: i for i, m in enumerate(measures)}
fig, ax = plt.subplots(figsize=(7, 4.5))
ks = levels_of(df[G]) if G else ["all"]
many = len(ks) > 1  # several groups: dash and marker shape per profile, as in the app
for i, k in enumerate(ks):
    g = (df[df[G].astype(str) == str(k)] if G else df).copy()
    g["_x"] = g[M].astype(str).map(pos)
    g, col = g.sort_values("_x"), PALETTE[i % len(PALETTE)]
    ax.plot(g["_x"], g[V], marker=SERIES_MARKERS[i % 8] if many else "o", linestyle=SERIES_DASHES[i % 8] if many else "-", color=col, label=str(k))
    if LO and HI:
        ax.vlines(g["_x"], g[LO], g[HI], color=col, alpha=0.6)
ax.set_xticks(range(len(measures)), measures)
ax.set_xlabel(M)
ax.set_ylabel(V)
if G:
    ax.legend(title=G, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads profile-plot-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#pcoa-centroids

Principal coordinates by group

Do the groups separate in the dissimilarity space, and do they differ in where they sit or in how spread out they are?

Demo data · seed 20261101 · 54 rows · default settings · 640 × 360

How to read it

  1. Read points as rows placed so that distances match their dissimilarities.
  2. Read diamonds as group centres.
  3. Separated centres suggest different locations; different hull sizes suggest different spreads.
  1. Callout 1: A group centre.
  2. Callout 2: Hull: the group's spread.
  3. Callout 3: How much dissimilarity this axis carries.

Watch out

  • PERMANOVA reacts to spread as well as location. Check PERMDISP before you read the separation.

Defaults

Group centre
Centroid
The marker drawn for each group; PERMDISP's default centre is the spatial median.
Also: Spatial median
Spokes to the centre
Off
Lines from each row to its group's centre — the distances PERMDISP compares.
Convex hulls
On
Outline each group with the smallest shape enclosing its points.

Pinned in the code

  • Principal coordinates (classical scaling): the eigenvectors of −½ J D² J scaled by √λ; the axis labels give each axis's share of the positive eigenvalues.
  • Axes are drawn with equal units, so distances on the plot are comparable in both directions.
  • Centres are computed in the plotted two dimensions for display; the test (PERMDISP) uses all axes, including those of negative eigenvalues for non-Euclidean dissimilarities.
  • Two axes show only part of the dissimilarity structure — a test can find a difference the first two axes do not show.
# Principal coordinates by group — Codesplash Chart Lab (recipe "pcoa-centroids")
# controls: center=centroid, spokes=false, hulls=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("pcoa-centroids-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["management"] = pd.Categorical(df["management"].astype("string"), categories=["grazed", "mown", "natural"])

_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 centre(xy, how):
    """Centroid, or the spatial median by Weiszfeld's iterations from the mean (as in the app)."""
    y = xy.mean(axis=0)
    if how != "median":
        return y
    for _ in range(1000):
        d = np.hypot(*(xy - y).T)
        keep = d > 1e-15
        if not keep.any():
            return y
        w = 1 / d[keep]
        nxt = (xy[keep] * w[:, None]).sum(axis=0) / w.sum()
        if np.hypot(*(nxt - y)) <= 1e-10 * (1 + np.hypot(*y)):
            return nxt
        y = nxt
    return y
X = "PCoA 1 (31.4%)"
Y = "PCoA 2 (17.9%)"
G = "management"
CENTER, SPOKES, HULLS = "centroid", False, True
d = df.dropna(subset=[X, Y] + ([G] if G else []))
groups = levels_of(d[G]) if G else ["All rows"]
fig, ax = plt.subplots(figsize=(7, 6))
for i, k in enumerate(groups):
    g = d[d[G].astype(str) == str(k)] if G else d
    xy, col = g[[X, Y]].to_numpy(float), PALETTE[i % len(PALETTE)]
    ctr = centre(xy, CENTER)
    if HULLS and len(xy) >= 3:
        try:
            h = ConvexHull(xy).vertices
            ax.fill(xy[h, 0], xy[h, 1], color=col, alpha=0.07, edgecolor=col, linewidth=1)
        except Exception:  # collinear points have no hull
            pass
    if SPOKES:
        for px, py in xy:
            ax.plot([ctr[0], px], [ctr[1], py], color=col, alpha=0.3, linewidth=0.8)
    ax.scatter(xy[:, 0], xy[:, 1], s=14, color=col, marker=SERIES_MARKERS[i % 8], alpha=0.6, label=f"{k} (n = {len(xy)})")  # shape per group, as in the app
    if G:
        ax.scatter([ctr[0]], [ctr[1]], marker="D", s=60, color=col, edgecolors="white", linewidths=1.2, zorder=3)
ax.set_aspect("equal", adjustable="datalim")  # equal units: distances read the same both ways
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(title=G, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads pcoa-centroids-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#distance-distance

Dissimilarity–dissimilarity plot

Do pairs of rows that differ more in one set of variables also differ more in another (the Mantel test's question)?

Demo data · seed 20261101 · 435 rows · default settings · 640 × 360

How to read it

  1. Read each point as a pair of rows: its distance in one matrix against the other.
  2. A rising cloud means pairs that differ in one set also differ in the other.
  3. Read r in the legend, then the Mantel test's p.
  1. Callout 1: A rising line: distances agree.
  2. Callout 2: Each point: one pair of rows.

Watch out

  • Pairs aren't independent. A usual correlation test is wrong: use the permutation p-value.

Defaults

Least-squares line
On
Add the fitted straight line.

Pinned in the code

  • One point per pair of rows (n(n − 1)/2 points); the engines send at most 5000 evenly spaced pairs.
  • The line is the least-squares fit of the first matrix's dissimilarity on the second's; its correlation is the (Pearson) Mantel statistic.
  • The pairs are not independent, so the line's ordinary standard errors are wrong — the Mantel test's permutation p-value is the valid test.
# Dissimilarity–dissimilarity plot — Codesplash Chart Lab (recipe "distance-distance")
# controls: line=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("distance-distance-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")
X = "geographic distance (km)"
Y = "Bray–Curtis dissimilarity"
LINE = True
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(float), d[Y].to_numpy(float)
fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(x, y, s=8 if len(x) > 2000 else 14, alpha=0.25 if len(x) > 2000 else 0.45, color=PALETTE[0])
if LINE and len(x) > 1:
    slope, intercept = np.polyfit(x, y, 1)  # least squares; its r is the (Pearson) Mantel statistic
    r = np.corrcoef(x, y)[0, 1]
    xs = np.array([x.min(), x.max()])
    ax.plot(xs, intercept + slope * xs, color=REF, linewidth=2, label=f"least squares, r = {r:.3f}")
    ax.legend(fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
ax.set_title("Every pair of rows")
plt.show()

Needs pandas, numpy, matplotlib · reads distance-distance-demo.csv · app theme from the optional codesplash helper

Multivariate tests

svg#mantel-correlogram

Mantel correlogram

Over what distances are rows more alike (or less alike) than average?

Demo data · seed 20261101 · 10 rows · default settings · 640 × 360

How to read it

  1. Read x as distance classes, y as Mantel r in each class.
  2. Filled points are significant.
  3. Positive at short distances and falling suggests rows close together are alike.
  1. Callout 1: At short distances: rows are alike.
  2. Callout 2: No association here.
  3. Callout 3: Hollow: not significant.

Watch out

  • Each class is one test: use the corrected p-values shown.

Defaults

Significance level
0.05
The α below which a point counts as significant.
Range 0.001 to 0.2, step 0.005

Pinned in the code

  • For each distance class the model matrix is 0 for pairs in the class and 1 otherwise, so r > 0 means pairs that close together are more similar than average (positive autocorrelation).
  • Filled points are significant at α after the progressive Bonferroni correction (class c's p times c, kept monotone), reading from the shortest distances outwards.
  • Classes beyond about half the largest distance contain few, edge-biased pairs; read them with care (Legendre & Legendre 2012).
# Mantel correlogram — Codesplash Chart Lab (recipe "mantel-correlogram")
# controls: alpha=0.05
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("mantel-correlogram-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")
MID = "distance class (m)"
R = "Mantel r"
P = "progressive p"
PAIRS = "pairs"
ALPHA = 0.05  # filled points: corrected p below α
d = df.dropna(subset=[MID, R]).sort_values(MID)
sig = (d[P] < ALPHA).to_numpy() if P else np.zeros(len(d), bool)
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.axhline(0, color=GREY, linestyle="--", linewidth=1)
ax.plot(d[MID], d[R], color=PALETTE[0], linewidth=1.6)
ax.scatter(d[MID][sig], d[R][sig], s=40, color=PALETTE[0], zorder=3, label=f"significant (p < {ALPHA:g})")
ax.scatter(d[MID][~sig], d[R][~sig], s=40, facecolors="white", edgecolors=REF, zorder=3, label="not significant")
if PAIRS:  # how many pairs each class holds (few pairs: read with care)
    for xv, yv, nv in zip(d[MID], d[R], d[PAIRS]):
        ax.annotate(f"{nv:.0f}", (xv, yv), xytext=(0, 7), textcoords="offset points", ha="center", fontsize=7, color=REF)
lim = max(0.05, d[R].abs().max()) * 1.15
ax.set_ylim(-lim, lim)
ax.set_xlabel(MID)
ax.set_ylabel("Mantel r")
ax.legend(fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads mantel-correlogram-demo.csv · app theme from the optional codesplash helper

Directions & cycles

Angles, hours and seasons on the circle: rose diagrams, circular dot plots, densities and wind roses.

6

Directions & cycles

svg#rose-diagram

Rose diagram

Which directions or times of day are most common?

Demo data · seed 20261101 · 66 rows · default settings · 640 × 360

How to read it

  1. Read petals as how many angles fall in each sector.
  2. Read petal area as frequency (radius grows as the square root).
  3. Read the arrow as the mean direction, its length as how concentrated.
  1. Callout 1: A large petal: a common direction.
  2. Callout 2: Mean direction arrow.
  3. Callout 3: Zero direction.

Watch out

  • Sector edges matter, so check other sector counts. Area-true and radius-true petals look different.

Defaults

Angles are in
Degrees
How the column measures direction; the dial is labelled to match.
Also: Radians · Hours of the day · Weekday (1 = Mon) · Month (1–12) · Day of year
Zero and direction
Top, clockwise (compass, clock)
Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
Also: Right, counter-clockwise (maths)
Sectors
16
How many sectors divide the circle.
Range 4 to 72, step 1
Area-true petals (√ radius)
On
Radius ∝ √count so a petal's area, not its length, is proportional to the count.
Mean direction arrow
On
Arrow toward the mean direction with length R̄ (1 = all angles identical).

Pinned in the code

  • Sector i covers [i·360/k, (i + 1)·360/k) in the chosen unit, starting at angle 0 (north, midnight, Monday, January).
  • Petal radius ∝ √count by default (area-true, Fisher 1993 §2.2); a linear radius exaggerates large counts.
  • Groups stack outward within each petal; the petal's outer edge is the sector total.
  • Arrow: mean direction θ̄ = atan2(Σ sin θ, Σ cos θ), length R̄ (the dial radius is R̄ = 1).

Use with care

Sector boundaries change the picture with few angles; compare with the circular dot plot.

# Rose diagram — Codesplash Chart Lab (recipe "rose-diagram")
# controls: units=degrees, orientation=compass, bins=16, area=true, mean=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("rose-diagram-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["control", "magnet", "anosmic"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "degrees", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
    ax.set_theta_zero_location("N" if COMPASS else "E")
    ax.set_theta_direction(-1 if COMPASS else 1)
    ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
    ax.grid(True, linewidth=0.5, alpha=0.6)
def circ_stats(t):
    C, S = np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()
    n = len(t)
    return (np.arctan2(S, C) / (2 * np.pi)) % 1, (np.hypot(C, S) / n if n else np.nan)
def grouped_turns(df, A, G, k):
    d = df.dropna(subset=[A])
    if not G:
        return [("", to_turn(d[A]))]
    return [(g, to_turn(d.loc[d[G].astype(str) == g, A])) for g in freq_levels(d[G], k)]
A = "bearing"
G = "group"
BINS, AREA, MEAN = 16, True, True  # area-true petals: radius ∝ √count
groups = grouped_turns(df, A, G, 8)
counts = np.array([np.bincount(np.minimum(BINS - 1, np.floor(t * BINS).astype(int)), minlength=BINS) for _, t in groups], dtype=float)  # sector i = [i/BINS, (i+1)/BINS)
top = counts.sum(axis=0).max() or 1
radius = (lambda n: np.sqrt(n / top)) if AREA else (lambda n: n / top)
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
acc = np.zeros(BINS)
for i, (name, _) in enumerate(groups):  # groups stack outward within a petal
    r0, r1 = radius(acc), radius(acc + counts[i])
    ax.bar(2 * np.pi * np.arange(BINS) / BINS, r1 - r0, bottom=r0, width=2 * np.pi / BINS, align="edge", color=PALETTE[i % len(PALETTE)],
           edgecolor="white", linewidth=0.5, hatch=SERIES_HATCHES[i % 8] if G else "", hatchcolor=HATCH_INK, label=name or None)  # texture per group, as in the app
    acc += counts[i]
if MEAN:  # arrow toward the mean direction, length R̄
    for i, (name, t) in enumerate(groups):
        mu, rbar = circ_stats(t)
        ax.annotate("", xy=(2 * np.pi * mu, rbar), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=PALETTE[i % len(PALETTE)] if G else REF, lw=1.8, linestyle=SERIES_DASHES[i % 8] if G else "-"))  # dash per group
fr = [0.25, 0.5, 0.75, 1]
ax.set_ylim(0, 1)
ax.set_yticks(fr, [str(round(top * f * f)) if AREA else str(round(top * f)) for f in fr], fontsize=8)  # ring labels are counts
if G:
    ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.18, 1.1))
plt.show()

Needs pandas, numpy, matplotlib · reads rose-diagram-demo.csv · app theme from the optional codesplash helper

Directions & cycles

svg#circular-dot

Circular dot plot

Where does each individual angle fall, and how do groups compare?

Demo data · seed 20261101 · 66 rows · default settings · 640 × 360

How to read it

  1. Read each dot as one angle, stacked outward from its ring.
  2. Each ring is one group.
  3. Read inner arrows as group mean directions.
  1. Callout 1: A group's dots: clustered around this direction.
  2. Callout 2: Mean direction arrow.
  3. Callout 3: A ring per group.

Watch out

  • Don't compute a usual mean on angles: the mean of 350° and 10° is 0°, not 180°.

Defaults

Angles are in
Degrees
How the column measures direction; the dial is labelled to match.
Also: Radians · Hours of the day · Weekday (1 = Mon) · Month (1–12) · Day of year
Zero and direction
Top, clockwise (compass, clock)
Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
Also: Right, counter-clockwise (maths)
Stacking resolution (sectors)
72
How finely angles are binned before stacking.
Range 12 to 360, step 6

Pinned in the code

  • Each angle is placed at the centre of its sector (resolution 360/k) and stacked outward; nothing is smoothed.
  • One ring per group, inner to outer in level order; inner arrows: mean direction and R̄ per group (scaled to the inner disc).
# Circular dot plot — Codesplash Chart Lab (recipe "circular-dot")
# controls: units=degrees, orientation=compass, bins=72
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("circular-dot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["control", "magnet", "anosmic"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "degrees", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
    ax.set_theta_zero_location("N" if COMPASS else "E")
    ax.set_theta_direction(-1 if COMPASS else 1)
    ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
    ax.grid(True, linewidth=0.5, alpha=0.6)
def circ_stats(t):
    C, S = np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()
    n = len(t)
    return (np.arctan2(S, C) / (2 * np.pi)) % 1, (np.hypot(C, S) / n if n else np.nan)
def grouped_turns(df, A, G, k):
    d = df.dropna(subset=[A])
    if not G:
        return [("", to_turn(d[A]))]
    return [(g, to_turn(d.loc[d[G].astype(str) == g, A])) for g in freq_levels(d[G], k)]
A = "bearing"
G = "group"
BINS = 72  # stacking resolution (sectors)
groups = grouped_turns(df, A, G, 6)
gap = 0.55 / len(groups)  # one ring per group, inner to outer
stacked = []
for i, (name, t) in enumerate(groups):
    b = np.minimum(BINS - 1, np.floor(t * BINS).astype(int))
    level = pd.Series(b).groupby(b).cumcount().to_numpy()  # dots stack outward in their sector
    stacked.append(((b + 0.5) / BINS, level))
max_level = max([lv.max() + 1 for _, lv in stacked if len(lv)] or [1])
step = min(0.024, gap * 0.9 / max_level, 2 * np.pi * 0.45 / BINS)
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
ring = np.linspace(0, 2 * np.pi, 361)
for i, ((name, t), (tc, level)) in enumerate(zip(groups, stacked)):
    base = 0.4 + i * gap
    col = PALETTE[i % len(PALETTE)] if G else REF
    ax.plot(ring, np.full_like(ring, base), color=GREY, linewidth=0.8)
    ax.scatter(2 * np.pi * tc, base + 0.42 * step + level * step, s=12, color=col, marker=SERIES_MARKERS[i % 8] if G else "o", label=name or None, zorder=3)  # shape per group, as in the app
    mu, rbar = circ_stats(t)  # inner arrows: mean direction and R̄, scaled to the inner disc
    ax.annotate("", xy=(2 * np.pi * mu, 0.36 * rbar), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=col, lw=1.6, linestyle=SERIES_DASHES[i % 8] if G else "-"))
ax.set_ylim(0, 1)
ax.set_yticks([])
if G:
    ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.18, 1.1))
plt.show()

Needs pandas, numpy, matplotlib · reads circular-dot-demo.csv · app theme from the optional codesplash helper

Directions & cycles

svg#circular-density

Circular density

What shape does the distribution of directions have — one peak, two, or none?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read distance from the ring as density at that direction.
  2. Count the humps: one peak, two, or none.
  3. Compare with the fitted von Mises curve, if on.
  1. Callout 1: A peak at this time of day.
  2. Callout 2: Another group's peak.
  3. Callout 3: Rug: the angles themselves.

Watch out

  • A von Mises assumes one peak: two peaks make its mean direction meaningless.

Defaults

Angles are in
Hours of the day
How the column measures direction; the dial is labelled to match.
Also: Degrees · Radians · Weekday (1 = Mon) · Month (1–12) · Day of year
Zero and direction
Top, clockwise (compass, clock)
Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
Also: Right, counter-clockwise (maths)
Kernel concentration ν (0 = automatic)
0
Higher ν = narrower kernel = wigglier curve. Automatic uses Taylor's (2008) rule of thumb.
Range 0 to 200, step 1
Fitted von Mises curve
On
The von Mises distribution with the sample's mean direction and maximum-likelihood κ.

Pinned in the code

  • Density f(θ) = Σ exp(ν cos(θ − θᵢ)) / (2π n I₀(ν)) on 180 points, drawn as radius = base + density; the inner circle is density 0.
  • Automatic ν: Taylor (2008) rule of thumb from the von Mises κ̂ of the sample (bounded to [0.5, 500]).
  • Fitted curve: von Mises(θ̄, κ̂), κ̂ the exact MLE solving A₁(κ) = R̄ (same algorithm as circular.describe).
# Circular density — Codesplash Chart Lab (recipe "circular-density")
# controls: units=hours, orientation=compass, bandwidth=0, fit=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.special import ive

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("circular-density-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["channel"] = pd.Categorical(df["channel"].astype("string"), categories=["store", "web"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "hours", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 24, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
    ax.set_theta_zero_location("N" if COMPASS else "E")
    ax.set_theta_direction(-1 if COMPASS else 1)
    ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
    ax.grid(True, linewidth=0.5, alpha=0.6)
def circ_stats(t):
    C, S = np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()
    n = len(t)
    return (np.arctan2(S, C) / (2 * np.pi)) % 1, (np.hypot(C, S) / n if n else np.nan)
def grouped_turns(df, A, G, k):
    d = df.dropna(subset=[A])
    if not G:
        return [("", to_turn(d[A]))]
    return [(g, to_turn(d.loc[d[G].astype(str) == g, A])) for g in freq_levels(d[G], k)]
def kappa_mle(r):
    if not np.isfinite(r) or r <= 0:
        return 0.0
    if r >= 1:
        return np.inf
    k = 2 * r + r**3 + 5 * r**5 / 6 if r < 0.53 else (-0.4 + 1.39 * r + 0.43 / (1 - r) if r < 0.85 else 1 / (r**3 - 4 * r**2 + 3 * r))
    for _ in range(200):
        a = ive(1, k) / ive(0, k)
        slope = 1 - a / k - a * a
        if not slope > 0:
            break
        nxt = k - (a - r) / slope
        nxt = k / 2 if nxt <= 0 else nxt
        done = abs(nxt - k) < 1e-12 * max(1, k)
        k = nxt
        if done:
            break
    return k

def kde_concentration(t):
    n = len(t)
    k = min(kappa_mle(np.hypot(np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()) / n if n else np.nan), 50)
    if not k > 0 or n < 2:
        return 2.0
    nu = (3 * n * k * k * ive(2, 2 * k) / ive(0, k) ** 2 / (4 * np.sqrt(np.pi))) ** 0.4  # I2(2k) / I0(k)^2
    return float(min(max(nu, 0.5), 500))

def vm_density(grid, mu, kappa):
    if not (kappa > 0 and np.isfinite(kappa)):
        return np.full_like(grid, 1 / (2 * np.pi))
    return np.exp(kappa * (np.cos(2 * np.pi * (grid - mu)) - 1)) / (2 * np.pi * ive(0, kappa))

def circular_kde(t, nu, grid):
    s = np.exp(nu * (np.cos(2 * np.pi * (grid[:, None] - t[None, :])) - 1)).sum(axis=1)
    return s / (len(t) * 2 * np.pi * ive(0, nu))
A = "hour"
G = "channel"
NU, FIT = 0, True  # kernel concentration (0 = automatic); fitted von Mises curve
grid = np.linspace(0, 1, 181)
curves = []
for name, t in grouped_turns(df, A, G, 6):
    mu, rbar = circ_stats(t)
    kde = circular_kde(t, NU if NU > 0 else kde_concentration(t), grid)
    curves.append((name, t, kde, vm_density(grid, mu, kappa_mle(rbar))))
top = max(max(k.max(), f.max() if FIT else 0) for _, _, k, f in curves) or 1
BASE = 0.35  # densities grow outward from the inner circle
radius = lambda dens: BASE + (1 - BASE) * dens / top
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
theta = 2 * np.pi * grid
ax.plot(theta, np.full_like(theta, BASE), color=GREY, linewidth=0.8)
for i, (name, t, kde, fit) in enumerate(curves):
    col = PALETTE[i % len(PALETTE)]
    ax.fill_between(theta, BASE, radius(kde), color=col, alpha=0.18, lw=0)
    ax.plot(theta, radius(kde), color=col, linewidth=1.6, label=name or "kernel density")
    if FIT:
        ax.plot(theta, radius(fit), color=col if G else REF, linewidth=1, linestyle="--", label=None if G else "von Mises fit")
    ax.vlines(2 * np.pi * t, BASE - 0.05, BASE, color=col, linewidth=0.5, alpha=0.6)  # rug
ax.set_ylim(0, 1)
ax.set_yticks([])
ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.2, 1.1))
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads circular-density-demo.csv · app theme from the optional codesplash helper

Directions & cycles

svg#circular-ecdf

Circular ECDF vs uniform

How far are the angles from being spread evenly round the circle?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read the curve as the cumulative share going round from 0.
  2. A diagonal line means an even spread round the circle.
  3. Read the largest gaps as Kuiper's statistic.
  1. Callout 1: The largest gap from uniform.
  2. Callout 2: The uniform diagonal.

Watch out

  • The starting point is arbitrary; that's why Kuiper's test uses both gaps.

Defaults

Angles are in
Hours of the day
How the column measures direction; the dial is labelled to match.
Also: Degrees · Radians · Weekday (1 = Mon) · Month (1–12) · Day of year

Pinned in the code

  • x = position round the circle from angle 0; y = share of angles at or before it; the dashed diagonal is a uniform circle.
  • Kuiper's V = D⁺ + D⁻ (largest gaps above and below the diagonal) does not depend on where the circle is cut; Stephens' V* = V(√n + 0.155 + 0.24/√n).

Use with care

The curve itself depends on the starting point 0; only D⁺ + D⁻ is rotation invariant.

# Circular ECDF vs uniform — Codesplash Chart Lab (recipe "circular-ecdf")
# controls: units=hours
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("circular-ecdf-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")
UNITS, COMPASS = "hours", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 24, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def kuiper(t):
    u = np.sort(t)
    n = len(u)
    F = np.arange(1, n + 1) / n
    plus, minus = F - u, u - (F - 1 / n)
    ip, im = int(np.argmax(plus)), int(np.argmax(minus))  # first largest gaps, as the app
    return u, F, max(plus[ip], 0), u[ip], max(minus[im], 0), u[im], ip, im
A = "hour"
t = to_turn(df[A].dropna())
u, F, d_plus, at_plus, d_minus, at_minus, ip, im = kuiper(t)
n = len(u)
vstar = (d_plus + d_minus) * (np.sqrt(n) + 0.155 + 0.24 / np.sqrt(n))  # Kuiper's modified V*
fig, ax = plt.subplots(figsize=(7, 5))
ax.plot([0, 1], [0, 1], color=REF, linestyle="--", linewidth=1, label="uniform")
ax.step(np.concatenate([[0], u, [1]]), np.concatenate([[0], F, [1]]), where="post", color=PALETTE[0], linewidth=2, label=A)
ax.plot([at_plus, at_plus], [at_plus, F[ip]], color=PALETTE[3], linewidth=2.5, label=f"Kuiper D+ and D- (V* = {vstar:.2f})")
ax.plot([at_minus, at_minus], [F[im] - 1 / n, at_minus], color=PALETTE[3], linewidth=2.5)
ax.set_xticks(TICK_T, TICK_LABELS)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_xlabel(A)
ax.set_ylabel("cumulative share")
ax.legend(fontsize=8, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib · reads circular-ecdf-demo.csv · app theme from the optional codesplash helper

Directions & cycles

svg#wind-rose

Wind rose

From which directions does it come, and how strong is it from each?

Demo data · seed 20261101 · 280 rows · default settings · 640 × 360

How to read it

  1. Read each spoke's length as the share of observations from that direction.
  2. Read colours as magnitude classes.
  3. Longer dark spokes mean frequent and strong.
  1. Callout 1: The dominant direction.
  2. Callout 2: A spoke of strong values.
  3. Callout 3: Magnitude classes.

Watch out

  • Direction is where it comes from in meteorology: check the units setting.

Defaults

Angles are in
Degrees
How the column measures direction; the dial is labelled to match.
Also: Radians · Hours of the day · Weekday (1 = Mon) · Month (1–12) · Day of year
Zero and direction
Top, clockwise (compass, clock)
Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
Also: Right, counter-clockwise (maths)
Sectors
16
How many sectors divide the circle.
Range 4 to 36, step 4
Magnitude classes
5
How many strength classes to colour.
Range 2 to 8, step 1
Show percentages
On
Label the rings with percentages.

Pinned in the code

  • Sectors are centred on the compass points (N covers 348.75°–11.25° with 16 sectors); length ∝ count (linear, the meteorological convention).
  • Magnitude classes have equal, rounded widths from 0 to the maximum; the last class is open-ended.
# Wind rose — Codesplash Chart Lab (recipe "wind-rose")
# controls: units=degrees, orientation=compass, bins=16, classes=5, percent=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("wind-rose-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")
UNITS, COMPASS = "degrees", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
    ax.set_theta_zero_location("N" if COMPASS else "E")
    ax.set_theta_direction(-1 if COMPASS else 1)
    ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
    ax.grid(True, linewidth=0.5, alpha=0.6)
def speed_breaks(s, classes):
    """Breaks from 0 in rounded steps (1, 2, 2.5, 5, 10 × 10^k) covering the maximum."""
    mx = float(np.nanmax(s)) if len(s) else 0.0
    if not mx > 0:
        return np.array([0.0, 1.0])
    raw = mx / classes
    mag = 10 ** np.floor(np.log10(raw))
    step = next((m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw), raw)
    return np.round(np.arange(classes + 1) * step, 6)

def class_of(v, breaks):
    """Class index (last class open-ended)."""
    return np.clip(np.searchsorted(breaks[:-1], v, side="right") - 1, 0, len(breaks) - 2)
A = "direction"
MAG = "speed"
BINS, CLASSES, PERCENT = 16, 5, True
d = df.dropna(subset=[A, MAG])
t, s = to_turn(d[A]), d[MAG].to_numpy(float)
breaks = speed_breaks(s, CLASSES)
K = len(breaks) - 1
cls = class_of(s, breaks)
b = np.minimum(BINS - 1, np.floor(((t + 0.5 / BINS) % 1) * BINS).astype(int))  # sectors centred on the compass points
counts = np.zeros((K, BINS))
np.add.at(counts, (cls, b), 1)
n, top = len(t), counts.sum(axis=0).max() or 1
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(6.6, 6.6), subplot_kw={"projection": "polar"})
dial(ax)
start = 2 * np.pi * (np.arange(BINS) - 0.5) / BINS
acc = np.zeros(BINS)
for k in range(K):  # magnitude classes stack outward; length = share of observations
    label = f"{breaks[k]:g}–{breaks[k + 1]:g}" if k < K - 1 else f"≥ {breaks[k]:g}"
    ax.bar(start, counts[k] / top, bottom=acc / top, width=0.92 * 2 * np.pi / BINS, align="edge", color=cmap(0.18 + 0.82 * k / max(1, K - 1)),
           edgecolor="white", linewidth=0.5, label=label)
    acc += counts[k]
fr = [0.25, 0.5, 0.75, 1]
ax.set_ylim(0, 1)
ax.set_yticks(fr, [f"{100 * round(top * f) / n:.1f}%" if PERCENT else str(round(top * f)) for f in fr], fontsize=8)
ax.legend(title=MAG, fontsize=8, loc="upper right", bbox_to_anchor=(1.22, 1.1))
plt.show()

Needs pandas, numpy, matplotlib · reads wind-rose-demo.csv · app theme from the optional codesplash helper

Directions & cycles

svg#radial-heatmap

Radial heatmap

How does activity vary round the clock (or the year), for each day, store or segment?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360

How to read it

  1. Read rings as categories and sectors as times.
  2. Find the dark sectors: when each category peaks.
  3. Compare between rings for different rhythms.
  1. Callout 1: A dark sector: a busy time.
  2. Callout 2: Ring labels: categories.
  3. Callout 3: Time starts at the top.

Watch out

  • Outer rings look larger for the same sector. Compare colour, not area.

Defaults

Angles are in
Hours of the day
How the column measures direction; the dial is labelled to match.
Also: Degrees · Radians · Weekday (1 = Mon) · Month (1–12) · Day of year
Zero and direction
Top, clockwise (compass, clock)
Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
Also: Right, counter-clockwise (maths)
Sectors
24
How many sectors divide the circle.
Range 4 to 96, step 1
Cell value
Count of rows
What each cell's colour shows, such as a count, a sum or a mean.
Also: Sum of value · Mean of value

Pinned in the code

  • Sector i covers [i/k, (i + 1)/k) of the cycle from angle 0; rings run inner to outer in level order.
  • Sequential colour from the lowest to the highest cell (count, sum or mean); empty cells are drawn dim.

Use with care

Outer rings are larger than inner ones; read colour, not area.

# Radial heatmap — Codesplash Chart Lab (recipe "radial-heatmap")
# controls: units=hours, orientation=compass, bins=24, stat=count
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

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("radial-heatmap-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["weekday"] = pd.Categorical(df["weekday"].astype("string"), categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "hours", True  # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 24, 0  # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
def to_turn(v):
    return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
    ax.set_theta_zero_location("N" if COMPASS else "E")
    ax.set_theta_direction(-1 if COMPASS else 1)
    ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
    ax.grid(True, linewidth=0.5, alpha=0.6)
A = "hour"
RING = "weekday"
V = "spend"
BINS, STAT = 24, "count"  # cell value: count, sum or mean
d = df.dropna(subset=[A] + ([V] if V else []))
rings = freq_levels(d[RING], 12) if RING else ["all"]  # inner to outer
ri = d[RING].astype(str).map({r: i for i, r in enumerate(rings)}) if RING else pd.Series(0, index=d.index)
d, ri = d[ri.notna()], ri[ri.notna()].astype(int).to_numpy()
b = np.minimum(BINS - 1, np.floor(to_turn(d[A]) * BINS).astype(int))
x = d[V].to_numpy(float) if V else np.ones(len(d))
total, count = np.zeros((len(rings), BINS)), np.zeros((len(rings), BINS))
np.add.at(total, (ri, b), x)
np.add.at(count, (ri, b), 1)
with np.errstate(invalid="ignore", divide="ignore"):
    cell = count if STAT == "count" else total if STAT == "sum" else np.where(count > 0, total / count, np.nan)
finite = cell[np.isfinite(cell)]
lo, hi = min(finite.min(), 0), max(finite.max(), 1)
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
INNER = 0.22
w = (1 - INNER) / len(rings)
fig, ax = plt.subplots(figsize=(6.8, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
start = 2 * np.pi * np.arange(BINS) / BINS
for i in range(len(rings)):
    colours = [cmap((v - lo) / (hi - lo)) if np.isfinite(v) else GREY for v in cell[i]]
    ax.bar(start, w * 0.97, bottom=INNER + i * w, width=2 * np.pi / BINS, align="edge", color=colours, edgecolor="white", linewidth=0.3)
ax.set_ylim(0, 1)
ax.set_yticks([INNER + (i + 0.5) * w for i in range(len(rings))], rings if RING else [""], fontsize=7)
fig.colorbar(plt.cm.ScalarMappable(norm=plt.Normalize(lo, hi), cmap=cmap), ax=ax, shrink=0.7, pad=0.1, label=STAT if STAT == "count" or not V else f"{STAT} of {V}")
plt.show()

Needs pandas, numpy, matplotlib · reads radial-heatmap-demo.csv · app theme from the optional codesplash helper

Maps & spatial

Points, regions and spatial patterns: choropleths, hot spots, Moran scatterplots, Ripley envelopes and variograms.

11

Maps & spatial

svgpreview#choropleth

Choropleth map

How does a rate or share vary across regions?

Demo data · seed 20261101 · 161 rows · default settings · 640 × 360

How to read it

  1. Read colour as the value in each region; check the legend's classes.
  2. Look for clusters of similar colours.
  3. Light grey regions have no data.
  1. Callout 1: The darkest class: the highest values.
  2. Callout 2: Legend: classes and their ranges.
  3. Callout 3: A large region.

Watch out

  • Large regions dominate visually whatever their population, so map rates rather than counts.
  • Class breaks change the story: try another classification.

Defaults

Boundaries
World countries
Which set of regions to draw and join your data to.
Also: World countries (detailed) · US states · US counties
Classes
Quantiles (equal counts)
Quantiles put the same number of regions in each class; equal intervals keep the scale even.
Also: Equal intervals · Continuous ramp
Number of classes
5
How many colour classes to divide the range into.
Range 3 to 9, step 1

Pinned in the code

  • Rows match regions by id, then by name — case, accents, punctuation and leading zeros are ignored ("6", "06" and "California" all match California).
  • Quantile breaks are type-7 quantiles of the mapped values; equal intervals split the range evenly; a value on a break goes to the upper class.
  • Map rates or averages, not counts: a count map mostly shows where regions are large or populous.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
  • Boundaries: Natural Earth (public domain) for countries, US Census Bureau 2017 (public domain) for states and counties; or a project map layer.

Use with care

Large, empty regions draw the eye; consider a cartogram or dot map when area and importance differ.

# Choropleth map — Codesplash Chart Lab (recipe "choropleth")
# controls: boundaries=world-countries-110m, breaks=quantile, classes=5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("choropleth-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def class_breaks(values, k, method):
    """k − 1 thresholds: type-7 quantiles or equal widths; a value on a break goes to the upper class."""
    v = np.sort(np.asarray(values, dtype=float))
    if method == "quantile":
        return [float(np.quantile(v, i / k)) for i in range(1, k)]
    return [float(v[0] + (v[-1] - v[0]) * i / k) for i in range(1, k)]

def ramp(t, lo=SEQ[0], hi=SEQ[-1]):
    """Blend the sequential ramp's two ends in sRGB (the app mixes them in OKLab)."""
    a, b = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (lo, hi)]
    return "#%02x%02x%02x" % tuple(int(round(x)) for x in a + (b - a) * float(t))
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
REGION = "country"
VALUE = "index (simulated)"
BOUNDARIES = "choropleth-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE, METHOD, K = "world", "quantile", 5
d = df.dropna(subset=[REGION, VALUE])
features, project = load_map(BOUNDARIES, SCOPE)
value_at = {}
if features is not None:
    for fi, v in zip(match_regions(features, d[REGION].tolist()), d[VALUE]):
        if fi is not None:
            value_at[fi] = float(v)
values = list(value_at.values()) if value_at else d[VALUE].astype(float).tolist()
lo, hi = min(values), max(values)
breaks = [] if METHOD == "continuous" else class_breaks(values, K, METHOD)
def tone(v):
    if METHOD == "continuous":
        return (v - lo) / (hi - lo) if hi > lo else 0.5
    return sum(v >= b for b in breaks) / max(1, len(breaks))
NO_DATA = GREY
fig, ax = plt.subplots(figsize=(8, 5))
if features is None:
    d = d.sort_values(VALUE).tail(40)
    ax.hlines(d[REGION].astype(str), lo, d[VALUE], color=GREY)
    ax.scatter(d[VALUE], d[REGION].astype(str), c=[ramp(tone(float(v))) for v in d[VALUE]], zorder=3)
    ax.set_xlabel(VALUE)
else:
    draw_regions(ax, features, project, lambda i: ramp(0.12 + 0.88 * tone(value_at[i])) if i in value_at else NO_DATA, "white")
    edges = [lo, *breaks, hi]
    if breaks:
        handles = [PathPatch(Path([(0, 0), (1, 0), (1, 1), (0, 0)]), facecolor=ramp(0.12 + 0.88 * i / len(breaks))) for i in range(len(edges) - 1)]
        ax.legend(handles, [f"{edges[i]:.3g} to {edges[i + 1]:.3g}" for i in range(len(edges) - 1)], title=VALUE, loc="lower left", frameon=False, fontsize=8)
    ax.set_title(f"{VALUE} by {REGION}")
plt.show()

Needs pandas, numpy, matplotlib · reads choropleth-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svgpreview#point-map

Point map

Where are the observations?

Demo data · seed 20261101 · 420 rows · default settings · 640 × 360

How to read it

  1. Read each dot as one row at its location.
  2. Look for clusters, and for places with none.
  3. Compare the colours between places.
  1. Callout 1: A dense cluster.
  2. Callout 2: Another.
  3. Callout 3: Colour legend.

Watch out

  • Dots follow where people or stores are. Without a denominator, density mostly shows population.

Defaults

Outlines
US states
Which region outlines to draw behind the marks.
Also: None · World countries
Dot radius (px)
2.5
The size of each dot.
Range 1 to 6, step 0.5

Pinned in the code

  • Coordinates are WGS84 longitude/latitude degrees; rows with missing or out-of-range coordinates are not drawn.
  • Dots are semi-transparent so overlaps read darker; with thousands of points switch to the hex-bin map.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
  • Boundaries: Natural Earth (public domain) for countries, US Census Bureau 2017 (public domain) for states and counties; or a project map layer.
# Point map — Codesplash Chart Lab (recipe "point-map")
# controls: basemap=us-states, size=2.5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("point-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
LON = "longitude"
LAT = "latitude"
COLOR = "format"
BOUNDARIES = "point-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE = "us"
DRAW_OUTLINES = True
base, project = load_map(BOUNDARIES, SCOPE) if DRAW_OUTLINES else (None, None)
d = df.dropna(subset=[LON, LAT])
d = d[d[LAT].abs() <= 90]
if project is None:
    project = make_projection(d[LON].tolist(), d[LAT].tolist(), SCOPE)
xy = np.array([project(lon, lat) for lon, lat in zip(d[LON], d[LAT])])
SIZE = 2.5  # dot radius in points
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
    draw_regions(ax, base, project, lambda i: GREY + "55", "white")
groups = d[COLOR].astype(str).value_counts().index[:8] if COLOR else [None]
for k, g in enumerate(groups):
    mask = (d[COLOR].astype(str) == g).to_numpy() if COLOR else np.ones(len(d), bool)
    ax.scatter(xy[mask, 0], xy[mask, 1], s=(2 * SIZE) ** 2, alpha=0.75, color=PALETTE[k % len(PALETTE)], marker=SERIES_MARKERS[k % 8], linewidths=0, label=g)  # shape per group, as in the app
ax.set_aspect("equal")
ax.set_axis_off()
if COLOR:
    ax.legend(frameon=False, title=COLOR, loc="lower left")
plt.show()

Needs pandas, numpy, matplotlib · reads point-map-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svgpreview#bubble-map

Bubble map

How much happens where?

Demo data · seed 20261101 · 40 rows · default settings · 640 × 360

How to read it

  1. Read bubble area as the value at that location.
  2. Colour marks the group.
  3. Compare with the size legend.
  1. Callout 1: A large value here.
  2. Callout 2: Another group's large value.
  3. Callout 3: Size legend.

Watch out

  • Overlapping bubbles hide each other; check dense areas in a table.

Defaults

Outlines
US states
Which region outlines to draw behind the marks.
Also: None · World countries
Largest radius (px)
18
The radius of the largest bubble; the rest scale by area.
Range 6 to 40, step 1

Pinned in the code

  • Area ∝ value (square-root radius scale from 0); negative and missing values are not drawn.
  • Largest bubbles are drawn first so small ones stay visible on top.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
# Bubble map — Codesplash Chart Lab (recipe "bubble-map")
# controls: basemap=us-states, maxRadius=18
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("bubble-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
LON = "longitude"
LAT = "latitude"
SIZE = "orders (k)"
COLOR = "region"
BOUNDARIES = "bubble-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE = "us"
DRAW_OUTLINES = True
base, project = load_map(BOUNDARIES, SCOPE) if DRAW_OUTLINES else (None, None)
d = df.dropna(subset=[LON, LAT])
d = d[d[LAT].abs() <= 90]
if project is None:
    project = make_projection(d[LON].tolist(), d[LAT].tolist(), SCOPE)
xy = np.array([project(lon, lat) for lon, lat in zip(d[LON], d[LAT])])
R_MAX = 18  # largest radius in points; area ∝ value
v = d[SIZE].to_numpy(dtype=float)
r = R_MAX * np.sqrt(np.maximum(v, 0) / np.nanmax(v))
order = np.argsort(-np.nan_to_num(v))  # largest first, so small bubbles stay visible
labels = d[COLOR].astype(str).to_numpy() if COLOR else np.array(["all"] * len(d))
levels = list(pd.Series(labels).value_counts().index[:8])
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
    draw_regions(ax, base, project, lambda i: GREY + "55", "white")
# each group also gets its own marker shape (same area), as in the app; other levels stay grey circles
groups = [(g, labels == g, k, PALETTE[k % len(PALETTE)]) for k, g in enumerate(levels)] + [(None, ~np.isin(labels, levels), 0, GREY)]
for g, m, k, col in groups:
    idx = [i for i in order if m[i]]
    if idx:
        ax.scatter(xy[idx, 0], xy[idx, 1], s=(2 * r[idx]) ** 2, color=col, marker=SERIES_MARKERS[k % 8], alpha=0.55, linewidths=0.8, edgecolors=col)
    if COLOR and g is not None:
        ax.scatter([], [], color=col, marker=SERIES_MARKERS[k % 8], label=g)
ax.set_aspect("equal")
ax.set_axis_off()
if COLOR:
    ax.legend(frameon=False, title=COLOR, loc="lower left")
ax.set_title(f"{SIZE} at each location")
plt.show()

Needs pandas, numpy, matplotlib · reads bubble-map-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svgpreview#hexbin-map

Hex-bin map

Where are points dense, when there are too many to draw?

Demo data · seed 20261101 · 2,400 rows · default settings · 640 × 360

How to read it

  1. Read each hexagon's colour as points inside it.
  2. Find the darkest hexagons: the densest places.
  3. Use the legend: the scale is a square root.
  1. Callout 1: Darkest: the densest area.
  2. Callout 2: A cluster.
  3. Callout 3: Legend.

Watch out

  • Hexagon size changes the picture; try other radii.

Defaults

Outlines
US states
Which region outlines to draw behind the marks.
Also: None · World countries
Hexagon radius (px)
10
The size of each hexagon on the map: larger gives fewer bins and a smoother picture.
Range 4 to 30, step 1

Pinned in the code

  • Hexagons are equal on screen (after projection), so with an equal-area projection each covers the same ground area.
  • Colour ∝ √count (or √sum of the weight) so sparse cells stay visible; the legend shows the counts the colours stand for.
  • For analysis-grade bins in a dataset, use Prepare → Spatial join / aggregate (host hex bins in Web Mercator metres).
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")
# controls: basemap=us-states, radius=10
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("hexbin-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
def ramp(t, lo=SEQ[0], hi=SEQ[-1]):
    a, b = [np.array([int(x[j:j + 2], 16) for j in (1, 3, 5)]) for x in (lo, hi)]
    return "#%02x%02x%02x" % tuple(int(round(x)) for x in a + (b - a) * float(t))
def hexbin_points(xy, weights, r):
    """Pointy-top hexagon bins of radius r (d3-hexbin's layout): centres and summed weights."""
    dx, dy = r * 2 * math.sin(math.pi / 3), r * 1.5
    bins = {}
    for (x, y), w in zip(xy, weights):
        py = y / dy
        pj = round(py)
        px = x / dx - (pj & 1) / 2
        pi_ = round(px)
        py1 = py - pj
        if abs(py1) * 3 > 1:
            px1 = px - pi_
            pi2 = pi_ + (-1 if px < pi_ else 1) / 2
            pj2 = pj + (-1 if py < pj else 1)
            if px1 * px1 + py1 * py1 > (px - pi2) ** 2 + (py - pj2) ** 2:
                pi_ = pi2 + (1 if pj & 1 else -1) / 2
                pj = pj2
        key = (pi_, pj)
        cx, cy = (pi_ + (pj & 1) / 2) * dx, pj * dy
        bins[key] = (cx, cy, bins.get(key, (0, 0, 0))[2] + w)
    return np.array(list(bins.values()))

def hexagon(cx, cy, r):
    return [(cx + r * math.sin(k * math.pi / 3), cy - r * math.cos(k * math.pi / 3)) for k in range(6)]
LON = "longitude"
LAT = "latitude"
WEIGHT = None
BOUNDARIES = "hexbin-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE = "us"
DRAW_OUTLINES = True
base, project = load_map(BOUNDARIES, SCOPE) if DRAW_OUTLINES else (None, None)
d = df.dropna(subset=[LON, LAT])
d = d[d[LAT].abs() <= 90]
if project is None:
    project = make_projection(d[LON].tolist(), d[LAT].tolist(), SCOPE)
xy = np.array([project(lon, lat) for lon, lat in zip(d[LON], d[LAT])])
weights = d[WEIGHT].to_numpy(dtype=float) if WEIGHT else np.ones(len(d))
r = (xy[:, 0].max() - xy[:, 0].min()) * 0.0161290322581  # the control's radius at a 640 px chart
bins = hexbin_points(xy, weights, r)
peak = max(1.0, bins[:, 2].max())
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
    draw_regions(ax, base, project, lambda i: GREY + "55", "white")
for cx, cy, v in bins:  # colour ∝ √value, so sparse cells stay visible
    ax.fill(*zip(*hexagon(cx, cy, r * 0.96)), color=ramp(0.15 + 0.85 * math.sqrt(max(v, 0)) / math.sqrt(peak)), linewidth=0)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title(f"{WEIGHT or 'points'} per hexagon (colour on a square-root scale)")
plt.show()

Needs pandas, numpy, matplotlib · reads hexbin-map-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svgpreview#neighbor-graph

Neighbour graph

Which regions count as neighbours for a spatial analysis?

Demo data · seed 20261101 · 107 rows · default settings · 640 × 360

How to read it

  1. Read each line as a link between neighbouring regions.
  2. Check regions with very few or very many links.
  3. Islands, with no link, need a decision before you test.
  1. Callout 1: A link between two regions.
  2. Callout 2: Many links in a dense area.
  3. Callout 3: Few links at the edge.

Watch out

  • Every spatial test depends on this graph. Try another definition of neighbours to check robustness.

Defaults

Boundaries
US states
Which set of regions to draw and join your data to.
Also: World countries · World countries (detailed) · US counties

Pinned in the code

  • One row per link (region, neighbour); regions match boundaries by id or name like the choropleth.
  • Nodes sit at each region's projected centroid; regions with no links (islands) have no node.
  • Spatial methods build their weights on the host (Data → Map layers → Neighbours) so Python and R use identical neighbours.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.
# Neighbour graph — Codesplash Chart Lab (recipe "neighbor-graph")
# controls: boundaries=us-states
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("neighbor-graph-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
def centroid_of(feature, project):
    """Area-weighted centroid of the feature's largest ring, in projected coordinates."""
    best, best_area = None, -1.0
    for poly in polygons_of(feature["geometry"]):
        pts = [project(p[0], p[1]) for p in poly[0]]
        area = cx = cy = 0.0
        for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1]):
            cross = x0 * y1 - x1 * y0
            area += cross
            cx += (x0 + x1) * cross
            cy += (y0 + y1) * cross
        if area and abs(area) > best_area:
            best, best_area = (cx / (3 * area), cy / (3 * area)), abs(area)
    return best
FROM = "state"
TO = "neighbour"
BOUNDARIES = "neighbor-graph-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
features, project = load_map(BOUNDARIES, "us")
d = df.dropna(subset=[FROM, TO])
fig, ax = plt.subplots(figsize=(8, 5))
if features is None:
    counts = pd.concat([d[FROM], d[TO]]).astype(str).value_counts().sort_values().tail(40)
    ax.barh(counts.index, counts.values, color=PALETTE[0])
    ax.set_xlabel("neighbours")
else:
    draw_regions(ax, features, project, lambda i: GREY + "55", "white")
    centres = [centroid_of(f, project) for f in features]
    used = set()
    for a, b in zip(match_regions(features, d[FROM].tolist()), match_regions(features, d[TO].tolist())):
        if a is None or b is None or centres[a] is None or centres[b] is None:
            continue
        ax.plot([centres[a][0], centres[b][0]], [centres[a][1], centres[b][1]], color=PALETTE[0], linewidth=1, alpha=0.7)
        used |= {a, b}
    ax.scatter([centres[i][0] for i in used], [centres[i][1] for i in used], s=16, color=PALETTE[0], edgecolors="white", linewidths=0.6, zorder=3)
    ax.set_title("Which regions are neighbours")
plt.show()

Needs pandas, numpy, matplotlib · reads neighbor-graph-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#lisa-map

Local Moran cluster map (LISA)

Where are clusters of like values, and where are spatial outliers?

Demo data · seed 20261101 · 49 rows · default settings · 640 × 360

How to read it

  1. Read High-High and Low-Low as clusters: a site and its neighbours are alike.
  2. Read High-Low and Low-High as spatial outliers: a site unlike its neighbours.
  3. Grey sites did not pass the adjusted significance level; the faintest have no data.
  1. Callout 1: A High-High cluster: high values among high neighbours.
  2. Callout 2: A Low-Low cluster.
  3. Callout 3: Not significant after the correction.
  4. Callout 4: Legend, with the number of sites in each pattern.

Watch out

  • Local tests share neighbours, so they are dependent. Treat flagged sites as leads to look into, not as discoveries.
  • Change the neighbours or the regions and clusters can move: try another definition before you report one.

Defaults

Boundaries
US states
Used only when the result names no map layer.
Also: World countries · World countries (detailed) · US counties

Pinned in the code

  • The first word is the site's own value and the second the average of its neighbours, each relative to the mean: High-Low is a high site among low neighbours.
  • Only sites that pass the adjusted significance level take a pattern; the correction is chosen in the analysis (Benjamini–Hochberg by default).
  • Local tests share neighbours, so they are dependent: read flagged sites as leads to investigate, not as discoveries.
  • The site's region comes from the map layer the analysis used; sites with no matching feature are counted under the map, and regions without a site stay faint.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.

Use with care

A cluster map shows where a statistic stands out under the neighbours you chose. It does not explain why, and changing the neighbours or the regions can move it.

# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")
# controls: boundaries=us-states
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("lisa-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
ORDER = ["High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant"]
def blend(a, b, t):
    """Blend two #rrggbb colours in sRGB."""
    x, y = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (a, b)]
    return "#%02x%02x%02x" % tuple(int(round(v)) for v in x + (y - x) * t)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
PATTERN_COLOURS = {"High-High": DIV[0], "Hot spot": DIV[0], "High-Low": blend(DIV[1], DIV[0], 0.45), "Low-Low": DIV[-1], "Cold spot": DIV[-1],
                   "Low-High": blend(DIV[1], DIV[-1], 0.45), "High variability": PALETTE[3], "Not significant": GREY}
SITE = "state"
VALUE = "rate (simulated)"
LABEL = "pattern"
STAT = "local Moran's I"
P_ADJ = "adjusted p"
LON = None
LAT = None
BOUNDARIES = "lisa-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d = df.dropna(subset=[SITE, LABEL])
labels = d[LABEL].astype(str).tolist()
present = [p for p in ORDER if p in labels] + sorted(set(labels) - set(ORDER))
features, project = (None, None) if LON and LAT else load_map(BOUNDARIES, "us")
label_at = {}
if features is not None:
    for fi, lab in zip(match_regions(features, d[SITE].tolist()), labels):
        if fi is not None:
            label_at[fi] = lab
NO_DATA = blend(GREY, "#ffffff", 0.6)
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged = d[d[LABEL].astype(str) != "Not significant"][[k for k in (SITE, VALUE, STAT, P_ADJ, LABEL) if k]]
print((flagged.sort_values(P_ADJ) if P_ADJ else flagged).to_string(index=False))
fig, ax = plt.subplots(figsize=(8, 5))
handles = [PathPatch(Path([(0, 0), (1, 0), (1, 1), (0, 0)]), facecolor=PATTERN_COLOURS.get(p, GREY), label=f"{p} ({labels.count(p)})") for p in present]
if LON and LAT:
    pts = d.dropna(subset=[LON, LAT])
    proj = make_projection(pts[LON].tolist(), pts[LAT].tolist(), "other")
    xy = np.array([proj(a, b) for a, b in zip(pts[LON], pts[LAT])])
    ax.scatter(xy[:, 0], xy[:, 1], s=36, c=[PATTERN_COLOURS.get(str(v), GREY) for v in pts[LABEL]], edgecolors="white", linewidths=0.5)
    ax.set_aspect("equal")
    ax.set_axis_off()
elif features is None:
    v = d[VALUE].to_numpy(dtype=float)
    order = np.argsort(v)[-40:]
    ax.barh(d[SITE].astype(str).to_numpy()[order], v[order], color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order])
    ax.set_xlabel(VALUE)
else:
    draw_regions(ax, features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, "white")
ax.legend(handles=handles, frameon=False, loc="lower left", fontsize=8, ncol=2)
ax.set_title(f"Local spatial patterns of {VALUE}")
plt.show()

Needs pandas, numpy, matplotlib · reads lisa-map-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#hotspot-map

Hot-spot map

Where do high or low values concentrate, or where do neighbourhoods vary unusually much?

Demo data · seed 20261101 · 49 rows · default settings · 640 × 360

How to read it

  1. Read a hot spot as high values sitting together, and a cold spot as low values sitting together.
  2. Check the legend: LOSH marks high variability instead, which says nothing about the level.
  3. Grey sites did not pass the adjusted significance level; the faintest have no data.
  1. Callout 1: A hot spot: this area's values add up higher than chance.
  2. Callout 2: A cold spot.
  3. Callout 3: Not significant after the correction.
  4. Callout 4: Legend, with the number of sites in each pattern.

Watch out

  • A hot spot is where high values sit together, which isn't always where the highest values are.
  • Raw counts make hot spots of wherever many people live: map a rate.

Defaults

Boundaries
US states
Used only when the result names no map layer.
Also: World countries · World countries (detailed) · US counties

Pinned in the code

  • Gi* counts the site's own value with its neighbours and Gi leaves it out; a large positive z is a hot spot and a large negative z a cold spot.
  • LOSH flags neighbourhoods that vary unusually much, which says nothing about whether their values are high.
  • Only sites that pass the adjusted significance level take a pattern.
  • The site's region comes from the map layer the analysis used; sites with no matching feature are counted under the map, and regions without a site stay faint.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.

Use with care

A hot spot is where high values sit together, not necessarily where the highest values are.

# Hot-spot map — Codesplash Chart Lab (recipe "hotspot-map")
# controls: boundaries=us-states
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path

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("hotspot-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
ORDER = ["High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant"]
def blend(a, b, t):
    """Blend two #rrggbb colours in sRGB."""
    x, y = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (a, b)]
    return "#%02x%02x%02x" % tuple(int(round(v)) for v in x + (y - x) * t)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
PATTERN_COLOURS = {"High-High": DIV[0], "Hot spot": DIV[0], "High-Low": blend(DIV[1], DIV[0], 0.45), "Low-Low": DIV[-1], "Cold spot": DIV[-1],
                   "Low-High": blend(DIV[1], DIV[-1], 0.45), "High variability": PALETTE[3], "Not significant": GREY}
SITE = "state"
VALUE = "rate (simulated)"
LABEL = "pattern"
STAT = "Gi* z"
P_ADJ = "adjusted p"
LON = None
LAT = None
BOUNDARIES = "hotspot-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d = df.dropna(subset=[SITE, LABEL])
labels = d[LABEL].astype(str).tolist()
present = [p for p in ORDER if p in labels] + sorted(set(labels) - set(ORDER))
features, project = (None, None) if LON and LAT else load_map(BOUNDARIES, "us")
label_at = {}
if features is not None:
    for fi, lab in zip(match_regions(features, d[SITE].tolist()), labels):
        if fi is not None:
            label_at[fi] = lab
NO_DATA = blend(GREY, "#ffffff", 0.6)
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged = d[d[LABEL].astype(str) != "Not significant"][[k for k in (SITE, VALUE, STAT, P_ADJ, LABEL) if k]]
print((flagged.sort_values(P_ADJ) if P_ADJ else flagged).to_string(index=False))
fig, ax = plt.subplots(figsize=(8, 5))
handles = [PathPatch(Path([(0, 0), (1, 0), (1, 1), (0, 0)]), facecolor=PATTERN_COLOURS.get(p, GREY), label=f"{p} ({labels.count(p)})") for p in present]
if LON and LAT:
    pts = d.dropna(subset=[LON, LAT])
    proj = make_projection(pts[LON].tolist(), pts[LAT].tolist(), "other")
    xy = np.array([proj(a, b) for a, b in zip(pts[LON], pts[LAT])])
    ax.scatter(xy[:, 0], xy[:, 1], s=36, c=[PATTERN_COLOURS.get(str(v), GREY) for v in pts[LABEL]], edgecolors="white", linewidths=0.5)
    ax.set_aspect("equal")
    ax.set_axis_off()
elif features is None:
    v = d[VALUE].to_numpy(dtype=float)
    order = np.argsort(v)[-40:]
    ax.barh(d[SITE].astype(str).to_numpy()[order], v[order], color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order])
    ax.set_xlabel(VALUE)
else:
    draw_regions(ax, features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, "white")
ax.legend(handles=handles, frameon=False, loc="lower left", fontsize=8, ncol=2)
ax.set_title(f"Local spatial patterns of {VALUE}")
plt.show()

Needs pandas, numpy, matplotlib · reads hotspot-map-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#moran-scatter

Moran scatterplot

Do sites resemble their neighbours, and which sites break the pattern?

Demo data · seed 20261101 · 49 rows · default settings · 640 × 360

How to read it

  1. Read x as each site's standardized value and y as the average of its neighbours.
  2. Read the slope of the line as Moran's I: steeper means neighbours resemble each other more.
  3. Top right and bottom left hold sites like their neighbours; the other two corners hold outliers.
  1. Callout 1: High-High: high sites among high neighbours.
  2. Callout 2: Low-Low: low sites among low neighbours.
  3. Callout 3: Low-High: a low site among high neighbours.
  4. Callout 4: The slope: Moran's I with row-standardised weights.

Watch out

  • One or two far-out sites can set the slope. Look for them before you trust the number.
  • A trend across the map also tilts this line, and it isn't local resemblance. Remove the trend and look again.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • With row-standardised weights the least-squares slope of the spatial lag on the centred value is Moran's I; when the analysis reports I, the line has that slope.
  • Quadrant lines cross at the means. Top right and bottom left are sites like their neighbours; the other two quadrants are sites unlike them.
  • Both axes span the same range, so a steeper line means neighbours resemble each site more.
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")
# 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("moran-scatter-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")
ORDER = ["High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant"]
def blend(a, b, t):
    """Blend two #rrggbb colours in sRGB."""
    x, y = [np.array([int(c[j:j + 2], 16) for j in (1, 3, 5)]) for c in (a, b)]
    return "#%02x%02x%02x" % tuple(int(round(v)) for v in x + (y - x) * t)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
PATTERN_COLOURS = {"High-High": DIV[0], "Hot spot": DIV[0], "High-Low": blend(DIV[1], DIV[0], 0.45), "Low-Low": DIV[-1], "Cold spot": DIV[-1],
                   "Low-High": blend(DIV[1], DIV[-1], 0.45), "High variability": PALETTE[3], "Not significant": GREY}
def moran_line(x, y, given=None):
    """Least-squares line through the means, or the analysis's Moran's I as the slope."""
    cx, cy = x.mean(), y.mean()
    slope = float(given) if given is not None else float(((x - cx) * (y - cy)).sum() / ((x - cx) ** 2).sum())
    return cx, cy, slope
X = "rate (standardized)"
Y = "average of neighbours"
SITE = "state"
LABEL = "pattern"
d = df.dropna(subset=[X, Y])
x, y = d[X].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
cx, cy, slope = moran_line(x, y, None)
lim = 1.1 * max(np.abs(x - cx).max(), np.abs(y - cy).max())
fig, ax = plt.subplots(figsize=(7, 6))
ax.axvline(cx, color=REF, linestyle="--", linewidth=1)
ax.axhline(cy, color=REF, linestyle="--", linewidth=1)
if LABEL:
    labels = d[LABEL].astype(str).to_numpy()
    for p in [q for q in ORDER if q in labels] + sorted(set(labels) - set(ORDER)):
        mask = labels == p
        ax.scatter(x[mask], y[mask], s=30, color=REF if p == "Not significant" else PATTERN_COLOURS.get(p, GREY), label=f"{p} ({mask.sum()})")
    ax.legend(frameon=False, fontsize=8)
else:
    ax.scatter(x, y, s=30, alpha=0.65, color=PALETTE[0])
line_x = np.array([cx - lim, cx + lim])
ax.plot(line_x, cy + slope * (line_x - cx), linewidth=1.5, color=REF)
if SITE:  # Name the flagged sites or, without patterns, the five furthest from the centre.
    named = np.flatnonzero(d[LABEL].astype(str) != "Not significant") if LABEL else np.argsort(np.hypot(x - cx, y - cy))[-5:]
    for i in named:
        ax.annotate(str(d[SITE].iloc[i]), (x[i], y[i]), xytext=(4, 3), textcoords="offset points", fontsize=7, color=REF)
ax.set(xlim=(cx - lim, cx + lim), ylim=(cy - lim, cy + lim), xlabel=X, ylabel=Y, title=f"Slope {slope:.3f}")
for (tx, ty, ha, va, name) in [(1, 1, "right", "top", "High-High"), (0, 1, "left", "top", "Low-High"), (0, 0, "left", "bottom", "Low-Low"), (1, 0, "right", "bottom", "High-Low")]:
    ax.text(tx, ty, name, transform=ax.transAxes, ha=ha, va=va, fontsize=8, color=REF)
plt.show()

Needs pandas, numpy, matplotlib · reads moran-scatter-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#ripley-envelope

Ripley's L with envelopes

At what distances are points more clustered or more regular than random?

Demo data · seed 20261101 · 33 rows · default settings · 640 × 360

How to read it

  1. Read x as distance and y as how far the points are from random at that distance.
  2. Above the envelope, points are closer together than random; below it, more evenly spaced.
  3. Use the dashed global envelope to judge the whole curve, and the shaded band for one chosen distance.
  1. Callout 1: Above the global envelope: clustered at these distances.
  2. Callout 2: Pointwise envelope from random patterns.
  3. Callout 3: Global envelope: the test of the whole curve.
  4. Callout 4: A random pattern sits on this line.

Watch out

  • Reading the shaded band at every distance finds false signals: a pointwise envelope is left somewhere far more often than its level says.
  • Density that varies across the window also looks like clustering, so this alone doesn't show that points attract each other.

Defaults

Subtract r
On
Draw L(r) − r so a random pattern is the flat line at 0; off draws L(r) against the line L = r.
Significance level
0.05
The level the envelopes were simulated at; it labels the legend.
Range 0.001 to 0.2, step 0.005

Pinned in the code

  • L(r) = √(K(r)/π) stabilizes the variance of Ripley's K, and L(r) = r under complete spatial randomness.
  • Use the global envelope to test the whole curve. A pointwise envelope is exceeded somewhere far more often than its level suggests, so read it distance by distance only.
  • Results depend on the observation window; a window much larger than the points' range makes any pattern look clustered.

Use with care

Clustering at a distance can also come from density that varies across the window. It does not by itself mean points attract one another.

# Ripley's L with envelopes — Codesplash Chart Lab (recipe "ripley-envelope")
# controls: centred=true, alpha=0.05
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("ripley-envelope-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")
R = "distance r"
L = "L(r)"
LO = "pointwise low"
HI = "pointwise high"
LO_G = "global low"
HI_G = "global high"
CENTRED = True  # L(r) − r: a random pattern is the flat line at 0
d = df.dropna(subset=[R, L]).sort_values(R)
r = d[R].to_numpy(dtype=float)
shift = r if CENTRED else 0.0
fig, ax = plt.subplots(figsize=(8, 4.5))
if LO and HI:
    ax.fill_between(r, d[LO] - shift, d[HI] - shift, color=PALETTE[0], alpha=0.16, linewidth=0, label="pointwise envelope")
if LO_G and HI_G:
    ax.plot(r, d[HI_G] - shift, color=GREY, linestyle="--", linewidth=1, label="global envelope")
    ax.plot(r, d[LO_G] - shift, color=GREY, linestyle="--", linewidth=1)
ax.plot(r, np.zeros_like(r) if CENTRED else r, color=REF, linestyle=":", label="random pattern")
ax.plot(r, d[L] - shift, color=PALETTE[0], linewidth=1.8, label="observed")
ax.set(xlabel=R, ylabel="L(r) − r" if CENTRED else "L(r)")
ax.legend(frameon=False, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads ripley-envelope-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#variogram

Semivariogram

How far does resemblance reach before sites are no more alike than any two sites?

Demo data · seed 20261101 · 15 rows · default settings · 640 × 360

How to read it

  1. Read x as the distance between two sites and y as how much they differ on average.
  2. Follow the rise: near sites are more alike than far ones until the curve levels off at the sill.
  3. Read the distance where it levels off as the range, and the height at distance zero as the nugget.
  1. Callout 1: The nugget: difference between sites at almost no distance.
  2. Callout 2: The sill: pairs this far apart are no more alike than any two sites.
  3. Callout 3: Band from shuffled values: points inside it show no spatial structure.
  4. Callout 4: Larger points are classes with more pairs.

Watch out

  • A curve that keeps rising usually means a trend across the map, not a long range. Remove the trend and look at the residuals.
  • Classes with few pairs are noisy. Don't read much into small points.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Semivariance rises with distance when near sites are more alike than far ones. It levels off at the sill, near the variance, at about the practical range.
  • The jump at distance 0 is the nugget: measurement error or variation at scales below the closest sites.
  • Points inside the shuffled band are no more alike than random pairs. Classes with few pairs are noisy, so point area shows the pairs.

Use with care

A semivariance that keeps rising usually means a trend across the map, not a long range: remove the trend and look at its residuals.

# Semivariogram — Codesplash Chart Lab (recipe "variogram")
# 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("variogram-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")
H = "distance"
GAMMA = "semivariance"
PAIRS = "pairs"
LO = "shuffled low"
HI = "shuffled high"
FITTED = "fitted"
VARIANCE = None  # the data's variance, when the analysis reports it
d = df.dropna(subset=[H, GAMMA]).sort_values(H)
h = d[H].to_numpy(dtype=float)
area = d[PAIRS].to_numpy(dtype=float) / d[PAIRS].max() if PAIRS else np.full(len(d), 0.5)
fig, ax = plt.subplots(figsize=(8, 4.5))
if LO and HI:
    ax.fill_between(h, d[LO], d[HI], color=PALETTE[0], alpha=0.14, linewidth=0, label="shuffled values")
if VARIANCE is not None:
    ax.axhline(VARIANCE, color=REF, linestyle="--", linewidth=1, label="variance")
if FITTED:
    ax.plot(h, d[FITTED], color=PALETTE[1], linewidth=1.8, label="fitted model")
ax.scatter(h, d[GAMMA], s=20 + 120 * area, color=PALETTE[0], alpha=0.75, linewidths=0.7, edgecolors="white", label="semivariance (area = pairs)")
ax.set(xlim=(0, h.max() * 1.05), ylim=(0, None), xlabel=H, ylabel=GAMMA)
ax.legend(frameon=False, fontsize=8)
plt.show()

Needs pandas, numpy, matplotlib · reads variogram-demo.csv · app theme from the optional codesplash helper

Maps & spatial

svg#kde-map

Kernel density map

Where are points concentrated, as a smooth surface?

Demo data · seed 20261101 · 700 rows · default settings · 640 × 360

How to read it

  1. Read the darkest band as where points are most concentrated.
  2. Read the bands as shares of the map's own peak, so compare shapes between maps and not colours.
  3. Try another bandwidth: a smaller one shows more local detail and a larger one merges clusters.
  1. Callout 1: The peak: the densest area.
  2. Callout 2: A second concentration.
  3. Callout 3: The lowest band: few points.
  4. Callout 4: Legend: bands as a share of the peak.

Watch out

  • Points usually follow where people or stores are. For risk, compare with the population at risk.
  • The surface spreads past the points and over water or borders. It shows concentration, not where things can occur.

Defaults

Outlines
US states
Outlines drawn under the density. Choose the set that covers your points, or none.
Also: None · World countries
Bandwidth multiplier
0.5
1 is Silverman's rule, which blurs separate clusters together; smaller shows more local detail.
Range 0.25 to 3, step 0.25
Contour bands
6
How many density levels to shade between the lowest band and the peak.
Range 3 to 10, step 1

Pinned in the code

  • An isotropic Gaussian kernel on the projected map, so with an equal-area projection each contour's area is true ground area.
  • Bandwidth is Silverman's rule h = σ n^(−1/6), with σ² the average of the two coordinate variances, times the multiplier. The default of 0.5 keeps separate clusters apart, which the rule alone blurs.
  • Colour shows density relative to the map's peak, so maps with different data aren't comparable by colour alone.
  • Projection: Equal Earth for world maps, Albers USA (with Alaska and Hawaii insets) for US layers, a conic equal-area projection centred on the data otherwise — equal-area, so filled areas are not exaggerated toward the poles.

Use with care

A density surface of raw points mostly shows where people or stores are. For risk, compare with the population at risk.

# Kernel density map — Codesplash Chart Lab (recipe "kde-map")
# controls: basemap=us-states, bandwidth=0.5, bands=6
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path
import matplotlib.colors as mpl_colors

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("kde-map-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")
import json, math, os, re, unicodedata

def region_key(s):
    """Ignore case, accents, punctuation and leading zeros (as the app does when matching regions)."""
    if isinstance(s, float) and s.is_integer():
        s = int(s)
    t = "".join(ch for ch in unicodedata.normalize("NFKD", str(s)) if not unicodedata.combining(ch)).strip().lower()
    t = re.sub(r"[\s._-]+", " ", t)
    return str(int(t)) if t.isdigit() else t

def read_boundaries(path):
    """Features of a GeoJSON file as dicts of id, name and geometry."""
    with open(path, encoding="utf-8") as fh:
        fc = json.load(fh)
    out = []
    for i, f in enumerate(fc["features"]):
        props = f.get("properties") or {}
        fid = f.get("id", i + 1)
        out.append({"id": str(fid), "name": str(props.get("name", fid)), "geometry": f.get("geometry")})
    return out

def polygons_of(geometry):
    """Each polygon as its rings (outer first) in longitude and latitude."""
    if not geometry:
        return []
    if geometry["type"] == "Polygon":
        return [geometry["coordinates"]]
    if geometry["type"] == "MultiPolygon":
        return geometry["coordinates"]
    return []

def contiguous(features):
    """Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets)."""
    def inside(f):
        pts = [p for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
        return bool(pts) and -126 < sum(p[0] for p in pts) / len(pts) < -66 and 24 < sum(p[1] for p in pts) / len(pts) < 50
    return [f for f in features if inside(f)]

def match_regions(features, keys):
    """Each key's feature position: by id, else by name."""
    by = {}
    for i, f in enumerate(features):
        by.setdefault(region_key(f["id"]), i)
    for i, f in enumerate(features):
        by.setdefault(region_key(f["name"]), i)
    return [None if k is None or k != k else by.get(region_key(k)) for k in keys]

def make_projection(lons, lats, scope):
    """Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents."""
    span = max(lons) - min(lons)
    if scope == "world" or span > 120:
        def project(lon, lat):
            th = math.asin(math.sqrt(3) / 2 * math.sin(math.radians(lat)))
            t2 = th * th
            t6 = t2 * t2 * t2
            d = 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
            return (2 * math.sqrt(3) * math.radians(lon) * math.cos(th) / d, th * (0.003796 * t6 * t2 + 0.000893 * t6 + -0.081106 * t2 + 1.340264))
        return project
    lat0 = (min(lats) + max(lats)) / 2
    if span < 2:
        return lambda lon, lat: (lon * math.cos(math.radians(lat0)), lat)
    lon0 = -96.0 if scope == "us" else (min(lons) + max(lons)) / 2
    third = (max(lats) - min(lats)) / 3
    p1, p2 = (math.radians(29.5), math.radians(45.5)) if scope == "us" else (math.radians(min(lats) + third), math.radians(max(lats) - third))
    n = (math.sin(p1) + math.sin(p2)) / 2 or 1e-9
    c = math.cos(p1) ** 2 + 2 * n * math.sin(p1)
    def project(lon, lat):
        rho = math.sqrt(max(0.0, c - 2 * n * math.sin(math.radians(lat)))) / n
        theta = n * math.radians(lon - lon0)
        return (rho * math.sin(theta), -rho * math.cos(theta))
    return project

def feature_extent(features):
    pts = [p for f in features for poly in polygons_of(f["geometry"]) for ring in poly for p in ring]
    return [p[0] for p in pts], [p[1] for p in pts]

def load_map(path, scope):
    """Features and their projection, or (None, None) when the boundaries file isn't there."""
    if not os.path.exists(path):
        print(f"No boundaries file at {path}: drawing without the map. Point BOUNDARIES at a GeoJSON file for the regions.")
        return None, None
    features = read_boundaries(path)
    if scope == "us":
        features = contiguous(features)
    lons, lats = feature_extent(features)
    return features, make_projection(lons, lats, scope)
def draw_regions(ax, features, project, fill_of, edge, width=0.5):
    """Fill each region; fill_of(position) gives its colour."""
    for i, f in enumerate(features):
        verts, codes = [], []
        for poly in polygons_of(f["geometry"]):
            for ring in poly:
                pts = [project(p[0], p[1]) for p in ring]
                verts += pts + [pts[0]]
                codes += [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]
        if verts:
            ax.add_patch(PathPatch(Path(verts, codes), facecolor=fill_of(i), edgecolor=edge, linewidth=width))
    ax.set_aspect("equal")
    ax.autoscale_view()
    ax.set_axis_off()
def density_grid(xy, weights, adjust, nx=160):
    """Gaussian kernel density on a grid over the points, as a share of the peak. Silverman: h = σ n^(−1/6)."""
    sw = weights.sum()
    m = (xy * weights[:, None]).sum(axis=0) / sw
    sigma = math.sqrt(((xy - m) ** 2 * weights[:, None]).sum() / (2 * sw))
    h = adjust * sigma * (sw * sw / (weights * weights).sum()) ** (-1 / 6)
    x0, x1 = xy[:, 0].min() - 3 * h, xy[:, 0].max() + 3 * h
    y0, y1 = xy[:, 1].min() - 3 * h, xy[:, 1].max() + 3 * h
    ny = max(2, int(nx * (y1 - y0) / (x1 - x0)))
    gx, gy = np.linspace(x0, x1, nx), np.linspace(y0, y1, ny)
    z = np.exp(-(gx[None, :] - xy[:, 0, None]) ** 2 / (2 * h * h)).T @ (weights[:, None] * np.exp(-(gy[None, :] - xy[:, 1, None]) ** 2 / (2 * h * h)))
    return gx, gy, (z / z.max()).T
LON = "longitude"
LAT = "latitude"
WEIGHT = None
BOUNDARIES = "kde-map-boundaries.geojson"  # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
SCOPE = "us"
DRAW_OUTLINES = True
base, project = load_map(BOUNDARIES, SCOPE) if DRAW_OUTLINES else (None, None)
d = df.dropna(subset=[LON, LAT])
d = d[d[LAT].abs() <= 90]
if project is None:
    project = make_projection(d[LON].tolist(), d[LAT].tolist(), SCOPE)
xy = np.array([project(lon, lat) for lon, lat in zip(d[LON], d[LAT])])
weights = d[WEIGHT].fillna(0).to_numpy(dtype=float) if WEIGHT else np.ones(len(d))
gx, gy, z = density_grid(xy, weights, 0.5)  # 1 is Silverman's rule, which blurs separate clusters together
levels = [(i + 1) / 7 for i in range(6)] + [1.0001]
fig, ax = plt.subplots(figsize=(8, 5))
if base is not None:
    draw_regions(ax, base, project, lambda i: GREY + "55", "white")
cmap = mpl_colors.LinearSegmentedColormap.from_list("seq", [SEQ[0], SEQ[-1]])
ax.contourf(gx, gy, z, levels=levels, cmap=cmap, alpha=0.62)
ax.set_aspect("equal")
ax.set_axis_off()
ax.set_title("Density of points, as a share of the peak")
plt.show()

Needs pandas, numpy, matplotlib · reads kde-map-demo.csv · app theme from the optional codesplash helper

Genetics

Genotype data: de Finetti diagrams, linkage disequilibrium, Manhattan plots and site frequency spectra.

5

Genetics

svg#definetti

De Finetti diagram (genotype frequencies)

Do the markers' genotype frequencies sit on the Hardy–Weinberg curve, or do some have too few or too many heterozygotes?

Demo data · seed 20261101 · 60 rows · default settings · 640 × 360

How to read it

  1. Read each point as one marker: its distance from each corner shows its share of AA, AB and BB, and its left–right place is the allele frequency.
  2. Points on the curve have the heterozygote share Hardy–Weinberg predicts; points below it have too few heterozygotes, points above too many.
  3. With the band on, a point outside it fails the χ² test at that sample size; compare its colour with the QC verdict.
  1. Callout 1: All heterozygotes (AB) at the apex.
  2. Callout 2: The Hardy–Weinberg parabola.
  3. Callout 3: A marker below the curve: too few heterozygotes.
  4. Callout 4: The AA corner: no copies of the second allele.

Watch out

  • A heterozygote deficit across many markers is more often mixed ancestry, inbreeding or a calling problem than selection.
  • The band depends on n: with thousands of people tiny, harmless departures fall outside it; read the effect (distance from the curve) as well.

Defaults

Hardy–Weinberg curve
On
Draws the parabola AB = 2q(1 − q) where markers in equilibrium fall.
Band for sample size
0
People per marker for the χ² acceptance band (0 hides the band).
Range 0 to 10,000,000, step 10
Band level (α)
0.05
Markers outside the band fail the 1-df χ² test of Hardy–Weinberg at this α.
Range 0.0001 to 0.5, step 0.005

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Each row is normalised by its own total, so counts and shares both work; rows with a missing or negative count, or a zero total, are left out.
  • AA sits at the bottom left, BB at the bottom right and AB at the apex; the x position is the second allele's frequency q = BB + AB/2.
  • The parabola is AB = 2q(1 − q). The band is AB = 2q(1 − q)(1 ± √(c/n)), c the upper-α χ²₁ quantile, since X² = n D² / (pq)² with D = AA − p² (Cannings & Edwards 1968).

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.

# De Finetti diagram (genotype frequencies) — Codesplash Chart Lab (recipe "definetti")
# controls: parabola=true, n=0, alpha=0.05
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("definetti-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["HWE"] = pd.Categorical(df["HWE"].astype("string"), categories=["passes", "fails HWE"])

_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 freq_levels(s, k=8):
    """Declared level order when the column is categorical, else by descending count (ties A→Z)."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(v) for v in s.cat.categories][:k]
    vc = s.dropna().astype(str).value_counts()
    return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
AA = "AA"
AB = "AB"
BB = "BB"
LABEL = "marker"
GROUP = "HWE"
N_BAND, ALPHA, PARABOLA = 0, 0.05, True  # band sample size (0 = no band), band level, Hardy–Weinberg curve
H = np.sqrt(3) / 2  # apex height: AA at (0, 0), BB at (1, 0), AB at (½, H)
cnt = df[[AA, AB, BB]].apply(pd.to_numeric, errors="coerce")
tot = cnt.sum(axis=1, skipna=False)
keep = (cnt >= 0).all(axis=1) & (tot > 0)  # missing, negative or all-zero rows are left out
d, cnt, tot = df[keep], cnt[keep], tot[keep]
x = (cnt[BB] + cnt[AB] / 2) / tot  # frequency of the second allele
y = H * cnt[AB] / tot
q = np.linspace(0, 1, 121)
het = 2 * q * (1 - q)  # Hardy–Weinberg heterozygote share
groups = freq_levels(d[GROUP], 50) if GROUP else [None]
fig, ax = plt.subplots(figsize=(7, 6.2))
ax.plot([0, 1, 0.5, 0], [0, 0, H, 0], color=REF, linewidth=1)
if N_BAND > 0:
    k = np.sqrt(stats.chi2.isf(ALPHA, 1) / N_BAND)  # X² = n D² / (pq)²  →  AB = 2pq(1 ± √(c/n)) (Cannings & Edwards 1968)
    lo, hi = np.maximum(0, het * (1 - k)), np.minimum(het * (1 + k), 2 * np.minimum(q, 1 - q))
    ax.fill_between(q, H * lo, H * hi, color=PALETTE[0], alpha=0.16, linewidth=0, label=f"{100 * (1 - ALPHA):g}% χ² band, n = {N_BAND}")
if PARABOLA:
    ax.plot(q, H * het, color=REF, linewidth=1.4, label="Hardy–Weinberg")
for i, g in enumerate(groups):
    m = (d[GROUP].astype(str) == g).to_numpy() if GROUP else np.ones(len(d), bool)
    ax.scatter(x[m], y[m], s=18, color=PALETTE[i % len(PALETTE)], alpha=0.85, edgecolors="white", linewidths=0.5, label=g)
if LABEL and len(d) <= 12:
    for xi, yi, name in zip(x, y, d[LABEL].astype(str)):
        ax.annotate(name, (xi, yi), xytext=(5, 0), textcoords="offset points", va="center", fontsize=8)
ax.text(-0.03, 0, AA, ha="right", va="center", fontweight="bold")
ax.text(1.03, 0, BB, ha="left", va="center", fontweight="bold")
ax.text(0.5, H + 0.03, AB, ha="center", va="bottom", fontweight="bold")
ax.set_aspect("equal")
ax.set_xlim(-0.18, 1.18)
ax.set_ylim(-0.08, H + 0.12)
ax.set_xticks([0, 0.25, 0.5, 0.75, 1])
ax.set_yticks([])
for side in ("left", "right", "top"):
    ax.spines[side].set_visible(False)
ax.set_xlabel("frequency of the second allele")
if ax.get_legend_handles_labels()[0]:
    ax.legend(frameon=False, loc="upper left")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads definetti-demo.csv · app theme from the optional codesplash helper

Genetics

svg#ld-heatmap

LD heatmap (pairwise linkage disequilibrium)

Which markers are inherited together, and where do the blocks of strong linkage disequilibrium start and end?

Demo data · seed 20261101 · 66 rows · default settings · 640 × 360

How to read it

  1. Read each cell as one pair of markers: darker means stronger linkage disequilibrium (r² or |D′| near 1).
  2. In the triangle, follow a cell up its two diagonals to the markers it pairs; cells next to the marker row pair neighbours.
  3. Dark triangles along the top are blocks of markers inherited together; a light band between them marks where recombination broke the link.
  1. Callout 1: A block: neighbouring markers in strong LD.
  2. Callout 2: Cells far down pair distant markers.
  3. Callout 3: Marker names run along the top.

Watch out

  • |D′| = 1 is common with rare alleles even without real linkage; read r² to judge how well one marker tags another.
  • Markers are evenly spaced here, whatever their base-pair distances; a block may span very different physical lengths.

Defaults

Layout
Triangle (Haploview)
Triangle: rotated cells under the marker row, as in Haploview. Square: a lower-triangular matrix.
Also: Square (lower triangle)
Values in cells
On
Prints each pair's value (as .85) when there are 16 markers or fewer.

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Markers keep the order in which the pairs first name them (marker A, then marker B, row by row), which is the engine's marker order.
  • Shade runs from 0 (light) to 1 (dark) on the theme's sequential ramp; values outside 0–1 are clamped for colour. Pairs with no row are drawn as empty outlines.
  • In the triangle layout the cell for markers i and j sits halfway between them, (j − i) half-cells below the marker row (Barrett et al. 2005).

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.

# LD heatmap (pairwise linkage disequilibrium) — Codesplash Chart Lab (recipe "ld-heatmap")
# controls: layout=triangle, labels=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.collections import PolyCollection

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("ld-heatmap-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")
A = "marker A"
B = "marker B"
VALUE = "r²"
LAYOUT, LABELS = "triangle", True
# marker order: first appearance over A then B, row by row
markers = list(dict.fromkeys(str(v) for pair in zip(df[A], df[B]) for v in pair if pd.notna(v)))
idx = {m: i for i, m in enumerate(markers)}
k = len(markers)
M = np.full((k, k), np.nan)  # M[j, i] = value of the pair (i < j); a pair listed twice keeps its last value
for a, b, v in zip(df[A], df[B], pd.to_numeric(df[VALUE], errors="coerce")):
    if pd.isna(a) or pd.isna(b) or pd.isna(v) or str(a) == str(b):
        continue
    i, j = sorted((idx[str(a)], idx[str(b)]))
    M[j, i] = v
def cell_text(v):
    r = round(float(v), 2)
    return str(int(r)) if r in (0, 1) else f"{r:.2f}".replace("0.", ".", 1)
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
fig, ax = plt.subplots(figsize=(7.5, 6))
if LAYOUT == "square":
    im = ax.imshow(M[1:, :-1], cmap=cmap, vmin=0, vmax=1)  # rows: markers 2..k, columns: 1..k−1
    ax.set_xticks(range(k - 1), markers[:-1], rotation=45, ha="right")
    ax.set_yticks(range(k - 1), markers[1:])
    for j in range(1, k):
        for i in range(j):
            if LABELS and k <= 16 and not np.isnan(M[j, i]):
                ax.text(i, j - 1, cell_text(M[j, i]), ha="center", va="center", fontsize=7, color="white" if M[j, i] > 0.55 else "black")
else:
    polys, vals, centres = [], [], []
    for j in range(k):
        for i in range(j):
            cx, cy = (i + j + 1) / 2, -(j - i) / 2  # Haploview: halfway between the markers, (j − i)/2 below them
            polys.append([(cx, cy + 0.5), (cx + 0.5, cy), (cx, cy - 0.5), (cx - 0.5, cy)])
            vals.append(M[j, i])
            centres.append((cx, cy))
    im = PolyCollection(polys, array=np.ma.masked_invalid(vals), cmap=cmap, edgecolors="white", linewidths=0.5)
    im.set_clim(0, 1)
    ax.add_collection(im)
    for m, name in enumerate(markers):
        ax.text(m + 0.5, 0.1, name, rotation=45, ha="left", va="bottom", fontsize=8)
    if LABELS and k <= 16:
        for (cx, cy), v in zip(centres, vals):
            if not np.isnan(v):
                ax.text(cx, cy, cell_text(v), ha="center", va="center", fontsize=7, color="white" if v > 0.55 else "black")
    ax.set_xlim(0, k)
    ax.set_ylim(-k / 2, 1.5)
    ax.set_aspect("equal")
    ax.axis("off")
fig.colorbar(im, ax=ax, shrink=0.6, label=VALUE)
plt.show()

Needs pandas, numpy, matplotlib · reads ld-heatmap-demo.csv · app theme from the optional codesplash helper

Genetics

svg#manhattan

Manhattan plot (association scan)

Where along the genome do markers show association with the trait, and does any pass the genome-wide threshold?

Demo data · seed 20261101 · 1,320 rows · default settings · 640 × 360

How to read it

  1. Read each point as one marker: the higher it sits, the smaller its p-value (−log₁₀ p).
  2. Look for towers that cross the genome-wide line; a real signal usually shows as a peak of neighbouring markers in LD, not one lone point.
  3. Use the suggestive line for markers worth following up, and the labels to name the strongest hits.
  1. Callout 1: A peak crossing the genome-wide line.
  2. Callout 2: The genome-wide line (5 × 10⁻⁸).
  3. Callout 3: Chromosomes side by side in alternating shades.

Watch out

  • Check the QQ plot and λ_GC first: inflation from population structure lifts every chromosome and makes false towers.
  • A peak marks a region associated with the trait; it is compatible with several causal variants nearby, and the top marker need not be one of them.

Defaults

Genome-wide line
5e-8
p below this line is genome-wide significant; 5 × 10⁻⁸ is the usual line for a whole genome.
Range 1e-300 to 0.5, step 1e-8
Suggestive line
0.00001
A second, looser line to flag markers worth following up (0 hides it).
Range 0 to 0.5, step 0.00001
Label top markers
3
Labels this many markers with the smallest p-values (0 labels none).
Range 0 to 20, step 1

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • y = −log₁₀ p. Rows with a missing position or a p outside (0, 1] are left out (a p of exactly 0 has no −log₁₀).
  • With more than one chromosome, they are placed in the order 1–22, X, Y, XY, MT (others A→Z), each starting where the last ended plus a gap of 0.5% of the summed spans; within a chromosome x = position − its first position.
  • With one chromosome (or none) x is the position as given; without base-pair positions, marker order works as the position.

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result. Positions are only meaningful when they are base pairs; with marker order the spacing is even, whatever the real distances.

# Manhattan plot (association scan) — Codesplash Chart Lab (recipe "manhattan")
# controls: gw=5e-8, suggestive=0.00001, top=3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re

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("manhattan-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["chromosome"] = pd.Categorical(df["chromosome"].astype("string"), categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"])

_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")
POS = "position (bp)"
P = "p"
CHROM = "chromosome"
LABEL = "marker"
GW, SUGGESTIVE, TOP = 5e-8, 0.00001, 3  # lines (0 = none) and top markers to label
SPECIAL = {"X": 1000, "Y": 1001, "XY": 1002, "M": 1003, "MT": 1003}
def chrom_key(name):
    s = re.sub(r"^chr", "", str(name).strip(), flags=re.I)
    u = s.upper()
    return (int(s), "", str(name)) if s.isdigit() else (SPECIAL[u], "", str(name)) if u in SPECIAL else (2000, u, str(name))
d = pd.DataFrame({"pos": pd.to_numeric(df[POS], errors="coerce"), "p": pd.to_numeric(df[P], errors="coerce")})
d["chrom"] = df[CHROM].astype("string").fillna("unknown").astype(str) if CHROM else ""
d["label"] = df[LABEL].astype("string") if LABEL else None
d = d[d["pos"].notna() & (d["p"] > 0) & (d["p"] <= 1)].copy()  # a p of 0 has no −log10
order = sorted(d["chrom"].unique(), key=chrom_key)  # 1–22, X, Y, XY, MT, then others
span = d.groupby("chrom")["pos"].agg(["min", "max"]).loc[order]
multi = len(order) > 1
if multi:
    width = span["max"] - span["min"]
    gap = width.sum() * 0.005 if width.sum() > 0 else 1  # 0.5% of the summed spans between chromosomes
    span["offset"] = np.concatenate([[0], np.cumsum((width + gap).to_numpy())[:-1]])
    d["x"] = d["chrom"].map(span["offset"]) + d["pos"] - d["chrom"].map(span["min"])
    centres = span["offset"] + width / 2
else:
    d["x"] = d["pos"]
d["y"] = -np.log10(d["p"])
d["band"] = d["chrom"].map({ch: i % 2 for i, ch in enumerate(order)})
top = d.sort_values("p", kind="stable").head(TOP)
def top_label(r):
    if LABEL and pd.notna(r["label"]):
        return str(r["label"])
    return f"{r['chrom']}:{r['pos']:g}" if multi else f"{r['pos']:g}"
fig, ax = plt.subplots(figsize=(10, 4.5))
for b, alpha in ((0, 1.0), (1, 0.5)):  # alternating shades by chromosome
    s = d[d["band"] == b]
    ax.scatter(s["x"], s["y"], s=6, color=PALETTE[0], alpha=alpha, linewidths=0)
if 0 < SUGGESTIVE < 1:
    ax.axhline(-np.log10(SUGGESTIVE), color=REF, linestyle="--", linewidth=1, label=f"suggestive {SUGGESTIVE:g}")
if 0 < GW < 1:
    ax.axhline(-np.log10(GW), color=PALETTE[3], linewidth=1.2, label=f"genome-wide {GW:g}")
for _, r in top.iterrows():
    ax.scatter([r["x"]], [r["y"]], s=40, facecolors="none", edgecolors="black", linewidths=0.8)
    ax.annotate(top_label(r), (r["x"], r["y"]), xytext=(4, 5), textcoords="offset points", fontsize=8)
if multi:
    ax.set_xticks(centres.to_numpy(), [re.sub(r"^chr", "", str(ch), flags=re.I) for ch in order], fontsize=7)
    ax.set_xlabel("chromosome")
else:
    ax.set_xlabel(POS)
lines = [-np.log10(t) for t in (GW, SUGGESTIVE) if 0 < t < 1]
ax.set_ylim(0, max([d["y"].max() if len(d) else 0, *lines, 1]) * 1.08)
ax.set_ylabel("−log₁₀ p")
if lines:
    ax.legend(frameon=False, loc="upper right")
plt.show()

Needs pandas, numpy, matplotlib, re · reads manhattan-demo.csv · app theme from the optional codesplash helper

Genetics

svg#gwas-qq

QQ plot of p-values (with λ_GC)

Do the p-values of a scan follow the null except for a few real signals, or are they inflated across the board?

Demo data · seed 20261101 · 500 rows · default settings · 640 × 360

How to read it

  1. Read the dashed line as what p-values look like when no marker is associated; points on it are null.
  2. Points that follow the line and rise only at the top right are compatible with a few real signals on a calibrated test.
  3. Points that leave the line early and stay above it, with λ_GC well above 1, suggest inflation from structure, relatedness or a mis-specified test.
  1. Callout 1: λ_GC: median χ² relative to the null.
  2. Callout 2: Most markers on the null line.
  3. Callout 3: A few strong signals leave the line at the end.

Watch out

  • λ_GC needs hundreds of mostly null markers; with a handful of markers or a candidate set it means little.
  • A polygenic trait in a large sample raises λ without any structure; LD score regression separates the two, a QQ plot cannot.

Defaults

λ_GC from the method
0
The engine's λ_GC to show; 0 estimates it from the p-values drawn (median χ²₁ over 0.4549).
Range 0 to 100, step 0.001
95% band
On
Pointwise 95% range of each ordered p under the null, from Beta(i, n − i + 1).

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Expected p-values are R's ppoints(n): (i − a)/(n + 1 − 2a) with a = 3/8 for n ≤ 10 and ½ otherwise; p outside (0, 1] is left out.
  • λ_GC = median of the χ²₁ upper quantiles of p, divided by qchisq(0.5, 1) = 0.4549 (Devlin & Roeder 1999); a λ given by the method is shown as given.
  • The band holds the i-th smallest of n uniform p-values with 95% probability (Beta(i, n − i + 1)); it is pointwise, not simultaneous. Above 400 p-values it is evaluated at log-spaced ranks.

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.

# QQ plot of p-values (with λ_GC) — Codesplash Chart Lab (recipe "gwas-qq")
# controls: lambda=0, band=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

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("gwas-qq-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")
P = "p"
LAMBDA, BAND = 0, True  # λ_GC from the method (0 = estimate from these p-values), 95% band
p = pd.to_numeric(df[P], errors="coerce")
p = np.sort(p[(p > 0) & (p <= 1)].to_numpy())
n = len(p)
a = 3 / 8 if n <= 10 else 0.5
e = (np.arange(1, n + 1) - a) / (n + 1 - 2 * a)  # R's ppoints(n)
lam = LAMBDA if LAMBDA > 0 else np.median(stats.chi2.isf(p, 1)) / stats.chi2.ppf(0.5, 1)  # Devlin & Roeder (1999)
i = np.arange(1, n + 1)
band_lo, band_hi = -np.log10(stats.beta.ppf(0.975, i, n - i + 1)), -np.log10(stats.beta.ppf(0.025, i, n - i + 1))  # every rank (the app samples ranks above 400)
ex, ob = -np.log10(e), -np.log10(p)
fig, ax = plt.subplots(figsize=(6, 6))
if BAND and n:
    ax.fill_between(ex, band_lo, band_hi, color=PALETTE[0], alpha=0.16, linewidth=0, label="95% band")
lim = ex.max() if n else 1
ax.plot([0, lim], [0, lim], color=REF, linestyle="--", linewidth=1, label="expected under the null")
ax.scatter(ex, ob, s=8, color=PALETTE[0], linewidths=0, label="markers")
ax.text(0.03, 0.97, f"λ_GC = {lam:.3f}", transform=ax.transAxes, va="top")
ax.set_xlabel("expected −log₁₀ p")
ax.set_ylabel("observed −log₁₀ p")
ax.set_xlim(0, None)
ax.set_ylim(0, None)
ax.legend(frameon=False, loc="lower right")
plt.show()

Needs pandas, numpy, matplotlib, scipy · reads gwas-qq-demo.csv · app theme from the optional codesplash helper

Genetics

svg#sfs-bar

Site frequency spectrum

How many sites carry the derived allele once, twice, …, and does that match what a constant-size neutral population predicts?

Demo data · seed 20261101 · 300 rows · default settings · 640 × 360

How to read it

  1. Read each bar as the number of segregating sites whose derived allele is carried by that many of the n sequences.
  2. Compare the bars with the dashed neutral expectation θ_W / i, scaled to the same number of sites.
  3. Too many singletons (left bars above the line) is what growth or a sweep leaves; too many middle classes is what balancing selection or structure leaves.
  1. Callout 1: Singletons: one sequence carries the derived allele.
  2. Callout 2: Middle classes.
  3. Callout 3: The neutral expectation θ_W / i.

Watch out

  • Fold the spectrum when the ancestral allele is unknown; an unfolded spectrum with a wrong ancestral call puts sites at the far end.
  • Demography and selection shape the spectrum in similar ways; a departure is compatible with several histories, and Tajima's D summarises it in one number.

Defaults

Sequences (n)
0
Sequences sampled per site; 0 uses the largest count + 1. Set it for folded or pre-counted spectra.
Range 0 to 100,000, step 1
Fold the spectrum
Off
Combines counts i and n − i into the minor-allele class, for when the ancestral allele is unknown.
Neutral expectation
On
θ_W / i scaled to the observed number of segregating sites (folded: i and n − i combined).

Pinned in the code

  • Draws the genetics method's published numbers as given (codesplash ≡ codesplashr); only the labelled reference curves are computed for display.
  • Classes are 1 … n − 1 (folded: 1 … ⌊n/2⌋); sites with count 0 or n are not segregating and are left out, as are missing, non-integer or out-of-range counts.
  • With the second role bound, each row is a class and its number of sites (a spectrum the method already counted).
  • Expectation: θ_W / i with θ_W = S / a₁, a₁ = Σ 1/i, so it sums to the observed S; folded classes add i and n − i, halved when i = n − i (Tajima 1989; Fu 1995).

Use with care

Research use only: genotype charts describe a sample; they are not a clinical or diagnostic result.

# Site frequency spectrum — Codesplash Chart Lab (recipe "sfs-bar")
# controls: n=0, folded=false, expected=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("sfs-bar-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

COUNT = "derived"
SITES = None
N, FOLDED, EXPECTED = 0, False, True  # sequences (0 = largest count + 1), fold, neutral expectation
k = pd.to_numeric(df[COUNT], errors="coerce")
w = pd.to_numeric(df[SITES], errors="coerce") if SITES else pd.Series(1.0, index=df.index)  # sites per row (pre-counted spectrum) or 1
ok = k.notna() & ((k - k.round()).abs() <= 1e-9) & (k >= 0) & w.notna() & (w >= 0)
k, w = k[ok].round().astype(int), w[ok]
n = int(round(N)) if N > 0 else (int(k.max()) + 1 if len(k) else 0)
seg = (k > 0) & (k < n)  # counts 0 and n are not segregating
k, w = k[seg].to_numpy(), w[seg].to_numpy()
cls = np.minimum(k, n - k) if FOLDED else k
K = n // 2 if FOLDED else n - 1
obs = np.bincount(cls - 1, weights=w, minlength=K)[:K] if K > 0 else np.zeros(0)
S = obs.sum()
a1 = (1 / np.arange(1, n)).sum()  # Watterson's a1
i = np.arange(1, K + 1)
exp = (S / a1) * ((1 / i + 1 / (n - i)) / np.where(i == n - i, 2, 1) if FOLDED else 1 / i)  # θ_W / i, sums to S (Tajima 1989; Fu 1995)
XLABEL = "minor-allele count" if FOLDED else "derived-allele count"
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(i, obs, width=0.78, color=PALETTE[0], alpha=0.85, label=f"observed (S = {S:g})")
if EXPECTED and S > 0:
    ax.plot(i, exp, color=PALETTE[1], linestyle="--", marker="o", markersize=4, label=f"neutral expectation (θ_W = {S / a1:.4g})")
ax.set_xlabel(XLABEL)
ax.set_ylabel("sites")
ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads sfs-bar-demo.csv · app theme from the optional codesplash helper