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.
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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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
counts, _ = np.histogram(x, bins=edges, density=True)
fig = go.Figure(go.Bar(x=(edges[:-1] + edges[1:]) / 2, y=counts, width=np.diff(edges), marker_color=PALETTE[0], opacity=0.85, name="score"))
grid = np.linspace(edges[0], edges[-1], 512)
scale = 1.0
from scipy.stats import gaussian_kde
h = bandwidth(x, "nrd0") * 1
fig.add_scatter(x=grid, y=gaussian_kde(x, bw_method=h / x.std(ddof=1))(grid) * scale, mode="lines", line_color=PALETTE[1], name="KDE")
fig.update_layout(bargap=0, xaxis_title="score", yaxis_title="Density")
fig.show()
Needs pandas, numpy, plotly, scipy · reads histogram-demo.csv · app theme from the optional codesplash helper
# Histogram — Codesplash Chart Lab (recipe "histogram")# controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("histogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
x <- df[["score"]]
x <- x[is.finite(x)]
breaks <- np_edges(x, "fd")
bw <- diff(breaks)[1]
scale <- 1 # density
kde <- density(x, bw = bandwidth(x, "nrd0") * 1,
from = min(breaks), to = max(breaks), n = 512)
p <- ggplot(data.frame(x = x), aes(x)) +
geom_histogram(aes(y = after_stat(density)), breaks = breaks, closed = "left", fill = cs_cat[1], colour = "white", alpha = 0.85) +
geom_line(data = data.frame(x = kde$x, y = kde$y * scale), aes(x, y), colour = cs_cat[2], linewidth = 1) +
labs(x = "score", y = "Density") +
theme_cs
print(p)
Needs ggplot2 · reads histogram-demo.csv · app theme from the optional codesplashr helper
-- Histogram — Codesplash Chart Lab (recipe "histogram")-- controls: bins=fd, binCount=30, scale=density, kde=true, bandwidth=nrd0, adjust=1, normal=false, rug=false-- numpy-style equal-width edges from min to max; bins are [a, b), the last one closed
WITH v AS (SELECT "score"::DOUBLE AS x FROM read_csv('histogram-demo.csv') WHERE "score" IS NOT NULL AND isfinite("score"::DOUBLE)),
s AS (
SELECT min(x) AS lo, max(x) AS hi, count(*) AS n,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1
FROM v
),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(CASE WHEN true THEN 2 * iqr * pow(n, -1.0 / 3) END, 0)))::INTEGER, 1) AS k FROM s),
b AS (
SELECT least(floor((x - lo) / ((hi - lo) / k)), k - 1)::INTEGER AS bin
FROM v, k
)
SELECT bin,
lo + bin * (hi - lo) / k AS x0,
lo + (bin + 1) * (hi - lo) / k AS x1,
count(*) AS count,
count(*) / (n * (hi - lo) / k) AS density
FROM b, k
GROUP BY bin, lo, hi, n, k
ORDER BY bin;
Compare the medians first: the line inside each box.
Compare the box heights: each box holds the middle half of its group, so a taller box means more spread.
Check the points beyond the whiskers, then the violin outline for a shape the box cannot show, such as two humps.
1Callout 1: Line in the box: the median. Dot: the mean.
2Callout 2: Beyond the whiskers: values flagged as unusual, not errors.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 box_stats(v, k=1.5):
"""Tukey box: type-7 quartiles (np.quantile default), whiskers at the most extreme points within k × IQR."""
q1, med, q3 = np.quantile(v, [0.25, 0.5, 0.75])
iqr = q3 - q1
inside = v[(v >= q1 - k * iqr) & (v <= q3 + k * iqr)]
out = v[(v < q1 - k * iqr) | (v > q3 + k * iqr)]
return dict(q1=q1, med=med, q3=q3, lo=inside.min(), hi=inside.max(), mean=v.mean(),
notch=1.58 * iqr / np.sqrt(v.size), outliers=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)
parts = groups(df, "outcome", "arm", max_levels=12)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = PALETTE[i % len(PALETTE)]
# bw.nrd0 per group, truncated to the data range; one scale group = one density scale
fig.add_violin(x=[label] * v.size, y=v, name=label, bandwidth=bandwidth(v, "nrd0"), spanmode="hard",
scalegroup="all", scalemode="width", points=False, box_visible=False,
line_color=color, fillcolor=color, opacity=0.35, showlegend=False)
s = box_stats(v, 1.5) # precomputed so plotly draws the app's type-7 box, not its own quartile method
fig.add_box(x=[label], q1=[s["q1"]], median=[s["med"]], q3=[s["q3"]], lowerfence=[s["lo"]], upperfence=[s["hi"]],
mean=[s["mean"]], boxmean=True,
width=0.18, line_color=color, fillcolor="rgba(0,0,0,0)", name=label, showlegend=False)
fig.add_scatter(x=[label] * s["outliers"].size, y=s["outliers"], mode="markers", marker=dict(color=color, symbol="circle-open"), showlegend=False)
fig.update_layout(violinmode="overlay", boxmode="overlay", xaxis_title="arm", yaxis_title="outcome")
fig.show()
Needs pandas, numpy, plotly · reads box-violin-demo.csv · app theme from the optional codesplash helper
# Box & violin — Codesplash Chart Lab (recipe "box-violin")# controls: violin=true, notch=false, mean=true, whisker=1.5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("box-violin-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("Control", "Treatment A", "Treatment B"))
d <- df[is.finite(df[["outcome"]]) & !is.na(df[["arm"]]), , drop = FALSE]
d <- d[d[["arm"]] %in% head(levels(d[["arm"]]), 12), , drop = FALSE] # at most 12 groups
d[["arm"]] <- droplevels(d[["arm"]])
p <- ggplot(d, aes(x = .data[["arm"]], y = .data[["outcome"]]))
# violins: bw.nrd0 per group, truncated to the data range, one density scale (scale = "area")
p <- p + geom_violin(aes(fill = .data[["arm"]]), bw = "nrd0", trim = TRUE, scale = "area", alpha = 0.3, colour = NA, show.legend = FALSE) +
scale_fill_manual(values = rep(cs_cat, length.out = nlevels(d[["arm"]])))
# box: quantile type 7, whiskers within 1.5 × IQR, notches 1.58·IQR/√n — ggplot2's own conventions match the app
p <- p + geom_boxplot(width = 0.18, coef = 1.5, notch = FALSE, fill = NA, outlier.shape = 1, outlier.colour = cs_cat[1])
p <- p + stat_summary(fun = mean, geom = "point", shape = 23, size = 2.5, fill = cs_cat[2], colour = "white")
p <- p + labs(x = "arm", y = "outcome") + theme_cs
print(p)
Needs ggplot2 · reads box-violin-demo.csv · app theme from the optional codesplashr helper
-- Box & violin — Codesplash Chart Lab (recipe "box-violin")-- controls: violin=true, notch=false, mean=true, whisker=1.5-- Tukey box statistics: type-7 quartiles (quantile_cont), whiskers at the most extreme values-- within 1.5 × IQR of the box, notch half-width 1.58·IQR/√n (McGill, Tukey & Larsen 1978)
WITH v0 AS (
SELECT "arm"::VARCHAR AS grp, "outcome"::DOUBLE AS x
FROM read_csv('box-violin-demo.csv')
WHERE "outcome" IS NOT NULL AND isfinite("outcome"::DOUBLE) AND "arm" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 12 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Control', 'Treatment A', 'Treatment B'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 12),
q AS (
SELECT grp, rk, count(*) AS n, avg(x) AS mean,
quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.5) AS median, quantile_cont(x, 0.75) AS q3,
min(x) AS vmin, max(x) AS vmax
FROM v
GROUP BY grp, rk
)
SELECT q.grp AS "group", q.n, q.vmin AS min, q.q1, q.median, q.q3, q.vmax AS max, q.mean,
min(v.x) FILTER (WHERE v.x >= q.q1 - 1.5 * (q.q3 - q.q1)) AS whisker_lo,
max(v.x) FILTER (WHERE v.x <= q.q3 + 1.5 * (q.q3 - q.q1)) AS whisker_hi,
count(*) FILTER (WHERE v.x < q.q1 - 1.5 * (q.q3 - q.q1) OR v.x > q.q3 + 1.5 * (q.q3 - q.q1)) AS outliers,
1.58 * (q.q3 - q.q1) / sqrt(q.n) AS notch_half_width
FROM q JOIN v USING (grp)
GROUP BY q.grp, q.rk, q.n, q.vmin, q.q1, q.median, q.q3, q.vmax, q.mean
ORDER BY q.rk;
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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
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 = go.Figure()
for i, (label, v, h) in enumerate(curves):
fill = "tozeroy" if i == 1 else None
fig.add_scatter(x=grid, y=kde(v, h, grid), mode="lines", name=label, fill=fill, line=dict(color=PALETTE[i], width=2 if i == 1 else 1.5, dash="dash" if i == 0 else "solid"))
if pooled.size <= 5000:
fig.add_scatter(x=pooled, y=np.zeros_like(pooled), mode="markers", marker=dict(symbol="line-ns-open", size=10, color=INK, opacity=0.3), showlegend=False)
fig.update_layout(xaxis_title="income_k", yaxis_title="Density", showlegend=len(curves) > 1)
fig.show()
Needs pandas, numpy, plotly · reads density-demo.csv · app theme from the optional codesplash helper
# Density curve — Codesplash Chart Lab (recipe "density")# controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("density-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
kde <- function(v, h, grid) {
# Gaussian kernel density by direct summation on `grid` (the app's method; density() uses an FFT)
vapply(grid, function(g) sum(dnorm((g - v) / h)), numeric(1)) / (length(v) * h)
}
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "income_k", NULL, max_levels = 6)
pooled <- unlist(parts, use.names = FALSE)
base <- bandwidth(pooled, "nrd0") * 1
curves <- lapply(c(0.5, 1, 2), function(k) list(label = sprintf("bw %.3g (×%g)", base * k, k), v = pooled, h = base * k)) # compare bandwidths
pad <- 3 * max(vapply(curves, function(cv) cv$h, numeric(1))) # R density(cut = 3)
grid <- seq(min(pooled) - pad, max(pooled) + pad, length.out = 160)
dens <- do.call(rbind, lapply(curves, function(cv) data.frame(curve = cv$label, x = grid, y = kde(cv$v, cv$h, grid))))
labels <- vapply(curves, function(cv) cv$label, "")
dens$curve <- factor(dens$curve, levels = labels)
cols <- setNames(rep(cs_cat, length.out = length(labels)), labels)
p <- ggplot(dens, aes(x, y, colour = curve))
p <- p + geom_area(data = dens[dens$curve == labels[2], ], aes(fill = curve), alpha = 0.22, colour = NA, show.legend = FALSE)
p <- p + geom_line(aes(linetype = curve), linewidth = 0.9) +
scale_linetype_manual(values = c("dashed", "solid", "solid")) +
scale_colour_manual(values = cols) + scale_fill_manual(values = cols) +
labs(x = "income_k", y = "Density", colour = NULL, linetype = NULL) + theme_cs
if (length(labels) == 1) p <- p + theme(legend.position = "none")
if (length(pooled) <= 5000) p <- p + geom_rug(data = data.frame(x = pooled), aes(x = x), inherit.aes = FALSE, alpha = 0.3)
print(p)
Needs ggplot2 · reads density-demo.csv · app theme from the optional codesplashr helper
-- Density curve — Codesplash Chart Lab (recipe "density")-- controls: bandwidth=nrd0, adjust=1, compare=true, fill=true, rug=true-- Gaussian KDE by direct summation on a 160-point grid over [min − 3·bw, max + 3·bw] (R density(cut = 3));-- bandwidth = nrd0 × 1 per group; type-7 median per group
WITH v0 AS (
SELECT 'income_k' AS grp, "income_k"::DOUBLE AS x
FROM read_csv('density-demo.csv')
WHERE "income_k" IS NOT NULL AND isfinite("income_k"::DOUBLE)
),
lv AS ( -- level order by frequency; at most 6 groups
SELECT grp, row_number() OVER (ORDER BY n DESC, grp) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 6),
s AS (
SELECT grp, rk, count(*) AS n, stddev_samp(x) AS sd,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
min(x) AS lo, max(x) AS hi, quantile_cont(x, 0.5) AS median
FROM v
GROUP BY grp, rk
HAVING count(*) >= 1
),
b AS (SELECT *, 1 * 0.9 * coalesce(nullif(least(sd, iqr / 1.34), 0), nullif(sd, 0), 1) * pow(n, -0.2) AS h FROM s),
r AS (SELECT min(lo) - 3 * max(h) AS lo, max(hi) + 3 * max(h) AS hi FROM b),
grid AS (SELECT r.lo + (r.hi - r.lo) * i / 159 AS gx FROM r, range(160) t(i))
SELECT b.grp AS "group", grid.gx AS x,
sum(exp(-0.5 * pow((grid.gx - v.x) / b.h, 2))) / (b.n * b.h * sqrt(2 * pi())) AS density,
b.h AS bandwidth, b.median
FROM b JOIN v USING (grp) CROSS JOIN grid
GROUP BY b.grp, b.rk, grid.gx, b.n, b.h, b.median
ORDER BY b.rk, x;
Read each row as one group's distribution, on a shared x axis.
Follow the peaks from row to row to see the level shift.
Compare widths to see whether spread changes along with the level.
1Callout 1: A peak: where this group's values concentrate.
2Callout 2: The short vertical line: this group's median.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
def ramp(t):
"""A colour on the sequential ramp, t in [0, 1] (interpolated in RGB)."""
a, b = np.array(px.colors.hex_to_rgb(SEQ[0])), np.array(px.colors.hex_to_rgb(SEQ[1]))
r, g, bl = (a + (b - a) * min(max(t, 0.0), 1.0)).round().astype(int)
return f"rgb({r}, {g}, {bl})"
SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"] # the app's sequential ramp
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
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
overlap = 1.6
k = len(parts)
fig = go.Figure()
for i, ((label, v), d) in enumerate(zip(parts, dens)):
base = k - 1 - i # first group on top
color = PALETTE[i % len(PALETTE)] if k <= 8 else ramp(0.25 + 0.7 * i / max(1, k - 1))
fig.add_scatter(x=np.r_[grid, grid[::-1]], y=np.r_[base + overlap * d / top, np.full(grid.size, base)],
fill="toself", mode="lines", line=dict(color=color, width=1), fillcolor=color, opacity=0.6, name=label, showlegend=False)
m = np.median(v)
fig.add_scatter(x=[m, m], y=[base, base + overlap * np.interp(m, grid, d) / top], mode="lines", line=dict(color=INK, width=1.2), showlegend=False, hoverinfo="skip")
fig.update_layout(xaxis_title="temp_c", yaxis=dict(tickvals=[k - 1 - i for i in range(k)], ticktext=[label for label, _ in parts], showgrid=False), height=200 + 40 * k)
fig.show()
Needs pandas, numpy, plotly · reads ridgeline-demo.csv · app theme from the optional codesplash helper
# Ridgeline — Codesplash Chart Lab (recipe "ridgeline")# controls: overlap=1.6, order=data, median=true, bandwidth=nrd0, adjust=1
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ridgeline-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- factor(df[["month"]], levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
kde <- function(v, h, grid) {
# Gaussian kernel density by direct summation on `grid` (the app's method; density() uses an FFT)
vapply(grid, function(g) sum(dnorm((g - v) / h)), numeric(1)) / (length(v) * h)
}
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
seq_cols <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$sequential else c("#eff6fd", "#1a469d") # the app's sequential ramp
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "temp_c", "month", max_levels = 24)
parts <- parts[lengths(parts) > 1]
hs <- vapply(parts, function(v) bandwidth(v, "nrd0") * 1, 0) # each ridge its own bandwidth
pooled <- unlist(parts, use.names = FALSE)
grid <- seq(min(pooled) - 3 * max(hs), max(pooled) + 3 * max(hs), length.out = 140)
k <- length(parts)
ridges <- do.call(rbind, lapply(seq_len(k), function(i) {
data.frame(group = names(parts)[i], base = k - i, x = grid, d = kde(parts[[i]], hs[i], grid)) # first group on top
}))
overlap <- 1.6
ridges$top <- ridges$base + overlap * ridges$d / max(ridges$d) # one height scale (ggridges scale = overlap)
ridges$group <- factor(ridges$group, levels = names(parts))
cols <- if (k <= 8) cs_cat[seq_len(k)] else colorRampPalette(seq_cols)(100)[round(25 + 70 * (seq_len(k) - 1) / max(1, k - 1))]
p <- ggplot(ridges, aes(x, group = group)) +
geom_ribbon(aes(ymin = base, ymax = top, fill = group), alpha = 0.55, show.legend = FALSE) +
geom_line(aes(y = top, colour = group), linewidth = 0.5, show.legend = FALSE) +
scale_fill_manual(values = cols) + scale_colour_manual(values = cols) +
scale_y_continuous(breaks = k - seq_len(k), labels = names(parts)) +
labs(x = "temp_c", y = NULL) + theme_cs + theme(panel.grid.major.y = element_blank())
med <- data.frame(group = factor(names(parts), levels = names(parts)), base = k - seq_len(k), m = vapply(parts, median, 0))
med$top <- med$base + overlap * mapply(function(v, h, m) kde(v, h, m), parts, hs, med$m) / max(ridges$d)
p <- p + geom_segment(data = med, aes(x = m, xend = m, y = base, yend = top), inherit.aes = FALSE, colour = ink, alpha = 0.6)
print(p)
Needs ggplot2 · reads ridgeline-demo.csv · app theme from the optional codesplashr helper
-- Ridgeline — Codesplash Chart Lab (recipe "ridgeline")-- controls: overlap=1.6, order=data, median=true, bandwidth=nrd0, adjust=1-- Gaussian KDE by direct summation on a 140-point grid over [min − 3·bw, max + 3·bw] (R density(cut = 3));-- bandwidth = nrd0 × 1 per group; type-7 median per group
WITH v0 AS (
SELECT "month"::VARCHAR AS grp, "temp_c"::DOUBLE AS x
FROM read_csv('ridgeline-demo.csv')
WHERE "temp_c" IS NOT NULL AND isfinite("temp_c"::DOUBLE) AND "month" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 24 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 24),
s AS (
SELECT grp, rk, count(*) AS n, stddev_samp(x) AS sd,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
min(x) AS lo, max(x) AS hi, quantile_cont(x, 0.5) AS median
FROM v
GROUP BY grp, rk
HAVING count(*) >= 2
),
b AS (SELECT *, 1 * 0.9 * coalesce(nullif(least(sd, iqr / 1.34), 0), nullif(sd, 0), 1) * pow(n, -0.2) AS h FROM s),
r AS (SELECT min(lo) - 3 * max(h) AS lo, max(hi) + 3 * max(h) AS hi FROM b),
grid AS (SELECT r.lo + (r.hi - r.lo) * i / 139 AS gx FROM r, range(140) t(i))
SELECT b.grp AS "group", grid.gx AS x,
sum(exp(-0.5 * pow((grid.gx - v.x) / b.h, 2))) / (b.n * b.h * sqrt(2 * pi())) AS density,
b.h AS bandwidth, b.median
FROM b JOIN v USING (grp) CROSS JOIN grid
GROUP BY b.grp, b.rk, grid.gx, b.n, b.h, b.median
ORDER BY b.rk, x;
Needs duckdb · reads ridgeline-demo.csv
ggridges::geom_density_ridges(scale = overlap) draws the same picture; the code builds the ridges with base ggplot2 so no extension package is needed.
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
# ECDF — Codesplash Chart Lab (recipe "ecdf")# controls: band=true, median=true, complement=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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
def rgba(color, alpha):
r, g, b = px.colors.hex_to_rgb(color) if color.startswith("#") else px.colors.unlabel_rgb(color)
return f"rgba({r:.0f}, {g:.0f}, {b:.0f}, {alpha})"
parts = groups(df, "minutes", "device", max_levels=8)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = PALETTE[i % len(PALETTE)]
xs = np.unique(v)
F = np.searchsorted(np.sort(v), xs, side="right") / v.size # F̂(x) = #{xᵢ ≤ x}/n
eps = np.sqrt(np.log(2 / 0.05) / (2 * v.size)) # DKW 95% band
lo, hi = np.clip(F - eps, 0, 1), np.clip(F + eps, 0, 1)
fig.add_scatter(x=xs, y=lo, mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=xs, y=hi, mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(color, 0.15), showlegend=False, hoverinfo="skip")
many = len(parts) > 1 # several groups: a dash and a median marker shape per group, as in the app
fig.add_scatter(x=xs, y=F, mode="lines", line=dict(color=color, width=2, shape="hv", dash=SERIES_DASHES[i % 8] if many else "solid"), name=label)
fig.add_vline(x=np.median(v), line=dict(color=color, dash="dot", width=1)) # type-7 median
fig.add_scatter(x=[np.median(v)], y=[0.5], mode="markers", marker=dict(symbol=SERIES_MARKERS[i % 8] if many else "circle", size=8, color="rgba(0,0,0,0)", line=dict(color=color, width=1.5)), showlegend=False, hoverinfo="skip")
fig.update_layout(xaxis_title="minutes", yaxis_title="F(x)", yaxis_range=[0, 1.02], showlegend=len(parts) > 1)
fig.show()
Needs pandas, numpy, plotly · reads ecdf-demo.csv · app theme from the optional codesplash helper
# ECDF — Codesplash Chart Lab (recipe "ecdf")# controls: band=true, median=true, complement=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("ecdf-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["device"]] <- factor(df[["device"]], levels = c("Desktop", "Mobile", "Tablet"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "minutes", "device", max_levels = 8)
steps <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]
xs <- sort(unique(v))
F <- ecdf(v)(xs) # F̂(x) = #{xᵢ ≤ x}/n, right-continuous
eps <- sqrt(log(2 / 0.05) / (2 * length(v))) # DKW 95% band, simultaneous over x
data.frame(group = k, x = xs, xend = c(xs[-1], max(xs)), F = F, lo = pmax(F - eps, 0), hi = pmin(F + eps, 1))
}))
steps$group <- factor(steps$group, levels = names(parts))
cols <- setNames(rep(cs_cat, length.out = length(parts)), names(parts))
p <- ggplot(steps)
p <- p + geom_rect(aes(xmin = x, xmax = xend, ymin = lo, ymax = hi, fill = group), alpha = 0.15, show.legend = FALSE)
p <- p + geom_step(aes(x, F, colour = group, linetype = group), direction = "hv", linewidth = 0.9) # dash per group, as in the app
med <- data.frame(group = factor(names(parts), levels = names(parts)), m = vapply(parts, median, 0)) # type-7 median
p <- p + geom_vline(data = med, aes(xintercept = m, colour = group), linetype = "dotted", show.legend = FALSE)
p <- p + geom_point(data = med, aes(x = m, y = 0.5, colour = group, shape = group), size = 2.2, show.legend = FALSE) + scale_shape_manual(values = cs_shapes)
p <- p + scale_colour_manual(values = cols) + scale_fill_manual(values = cols) + scale_linetype_manual(values = cs_linetypes) +
labs(x = "minutes", y = "F(x)", colour = NULL, linetype = NULL) + theme_cs
if (length(parts) == 1) p <- p + theme(legend.position = "none")
print(p)
Needs ggplot2 · reads ecdf-demo.csv · app theme from the optional codesplashr helper
-- ECDF — Codesplash Chart Lab (recipe "ecdf")-- controls: band=true, median=true, complement=false-- empirical CDF per group: F̂(x) = #{xᵢ ≤ x}/n at each distinct value (cume_dist), with the-- Dvoretzky–Kiefer–Wolfowitz 95% band F̂ ± √(ln(2/0.05)/(2n)) clipped to [0, 1]
WITH v0 AS (
SELECT "device"::VARCHAR AS grp, "minutes"::DOUBLE AS x
FROM read_csv('ecdf-demo.csv')
WHERE "minutes" IS NOT NULL AND isfinite("minutes"::DOUBLE) AND "device" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Desktop', 'Mobile', 'Tablet'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 8),
n AS (SELECT grp, rk, count(*) AS n FROM v GROUP BY grp, rk),
e AS (SELECT DISTINCT grp, x, cume_dist() OVER (PARTITION BY grp ORDER BY x) AS f FROM v)
SELECT e.grp AS "group", e.x, e.f AS ecdf,
greatest(e.f - sqrt(ln(2 / 0.05) / (2 * n.n)), 0) AS band_lo,
least(e.f + sqrt(ln(2 / 0.05) / (2 * n.n)), 1) AS band_hi,
1 - e.f AS exceedance
FROM e JOIN n USING (grp)
ORDER BY n.rk, e.x;
Points on the straight line: the data match a normal shape.
Look at the ends. Points above the line on the right and below on the left mean heavy tails; curving one way means skew.
Compare with the envelope: points outside it stray further than chance alone would usually allow.
1Callout 1: Points on the line: this part of the data matches a normal shape.
2Callout 2: Above the line at the right: larger values than a normal would give.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
fig = go.Figure()
fig.add_scatter(x=z, y=lo, mode="lines", line=dict(width=0), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=z, y=hi, mode="lines", line=dict(width=0), fill="tonexty", fillcolor="rgba(120, 140, 170, 0.18)", name=f"{1 - alpha:.0%} pointwise envelope")
fig.add_scatter(x=z, y=ref, mode="lines", line=dict(color=INK, width=1), name="qqline (quartiles)")
fig.add_scatter(x=z[~outside], y=y[~outside], mode="markers", marker=dict(color=PALETTE[0], size=6), name="inside")
fig.add_scatter(x=z[outside], y=y[outside], mode="markers", marker=dict(color=PALETTE[3], size=7), name=f"{outside.sum()} outside")
fig.update_layout(xaxis_title="Theoretical quantiles (normal)", yaxis_title="residual")
fig.show()
Needs pandas, numpy, plotly, scipy · reads qq-demo.csv · app theme from the optional codesplash helper
# Normal Q–Q plot — Codesplash Chart Lab (recipe "qq")# controls: envelope=true, level=0.95, detrended=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
x <- sort(df[["residual"]][is.finite(df[["residual"]])])
n <- length(x)
z <- qnorm(ppoints(n)) # R plotting positions
q <- quantile(x, c(0.25, 0.75), type = 7) # qqline through the quartiles
slope <- diff(q) / diff(qnorm(c(0.25, 0.75)))
intercept <- q[[1]] - slope * qnorm(0.25)
line <- intercept + slope * z
qq <- data.frame(z = z, y = x, ref = line)
# exact pointwise envelope: U(i) ~ Beta(i, n − i + 1), through Φ⁻¹ and the qqline (not simultaneous)
i <- seq_len(n)
alpha <- 1 - 0.95
qq$lo <- intercept + slope * qnorm(qbeta(alpha / 2, i, n - i + 1))
qq$hi <- intercept + slope * qnorm(qbeta(1 - alpha / 2, i, n - i + 1))
qq$outside <- qq$y < qq$lo | qq$y > qq$hi
p <- ggplot(qq, aes(z))
p <- p + geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.15)
p <- p + geom_line(aes(y = ref), linewidth = 0.4) +
geom_point(aes(y = y, colour = outside), size = 1.4, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = cs_cat[4])) +
labs(x = "Theoretical quantiles (normal)", y = "residual",
subtitle = sprintf("%d point(s) outside the pointwise envelope", sum(qq$outside))) +
theme_cs
print(p)
Needs ggplot2 · reads qq-demo.csv · app theme from the optional codesplashr helper
DuckDB has no inverse normal function, so there is no geometry SQL for Q–Q plots.
Points on the diagonal: the fitted normal's probabilities match the data's.
An S shape around the diagonal means the data's centre differs from a normal's.
Use the band to judge whether a departure is more than noise.
1Callout 1: Diagonal: where the data and the fitted normal agree.
2Callout 2: Sagging below the diagonal in the middle: a shape mismatch near the centre.
3Callout 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
# Normal P–P plot — Codesplash Chart Lab (recipe "pp")# controls: band=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
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 = go.Figure()
eps = np.sqrt(np.log(2 / 0.05) / (2 * n)) # DKW constant: a visual guide
t = np.linspace(0, 1, 101)
fig.add_scatter(x=t, y=np.clip(t - eps, 0, 1), mode="lines", line=dict(width=0), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=t, y=np.clip(t + eps, 0, 1), mode="lines", line=dict(width=0), fill="tonexty", fillcolor="rgba(120, 140, 170, 0.18)", name="95% Kolmogorov band")
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color=INK, width=1), showlegend=False)
fig.add_scatter(x=p, y=F, mode="markers", marker=dict(color=PALETTE[0], size=6), name="repair_h")
fig.update_layout(xaxis_title="Theoretical cumulative probability", yaxis_title="Empirical cumulative probability", width=560, height=520)
fig.show()
Needs pandas, numpy, plotly, scipy · reads pp-demo.csv · app theme from the optional codesplash helper
# Normal P–P plot — Codesplash Chart Lab (recipe "pp")# controls: band=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pp-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
x <- sort(df[["repair_h"]][is.finite(df[["repair_h"]])])
n <- length(x)
pts <- data.frame(p = ppoints(n), F = pnorm((x - mean(x)) / sd(x))) # Φ((x − x̄)/s), s with n − 1
eps <- sqrt(log(2 / 0.05) / (2 * n)) # DKW constant: a visual guide (conservative with estimated mean/SD)
band <- data.frame(t = seq(0, 1, length.out = 101))
p <- ggplot(pts, aes(p, F))
p <- p + geom_ribbon(data = band, aes(x = t, ymin = pmax(t - eps, 0), ymax = pmin(t + eps, 1)), inherit.aes = FALSE, fill = cs_cat[1], alpha = 0.15)
p <- p + geom_abline(slope = 1, intercept = 0, linewidth = 0.4) +
geom_point(colour = cs_cat[1], size = 1.3) +
coord_equal() + labs(x = "Theoretical cumulative probability", y = "Empirical: Φ((repair_h − mean) / sd)") +
theme_cs
print(p)
Needs ggplot2 · reads pp-demo.csv · app theme from the optional codesplashr helper
DuckDB has no normal CDF function, so there is no geometry SQL for P–P plots.
Read the rain to check the summaries against the real observations and spot gaps or clumps.
1Callout 1: Cloud: the shape of the distribution.
2Callout 2: Box: the median and the middle half.
3Callout 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
# Raincloud — Codesplash Chart Lab (recipe "raincloud")# controls: cloud=true, box=true, points=true, adjust=1
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 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 box_stats(v, k=1.5):
"""Tukey box: type-7 quartiles (np.quantile default), whiskers at the most extreme points within k × IQR."""
q1, med, q3 = np.quantile(v, [0.25, 0.5, 0.75])
iqr = q3 - q1
inside = v[(v >= q1 - k * iqr) & (v <= q3 + k * iqr)]
out = v[(v < q1 - k * iqr) | (v > q3 + k * iqr)]
return dict(q1=q1, med=med, q3=q3, lo=inside.min(), hi=inside.max(), mean=v.mean(),
notch=1.58 * iqr / np.sqrt(v.size), outliers=out)
parts = groups(df, "rt_ms", "condition", max_levels=8)
k = len(parts)
rng = np.random.default_rng(11) # rain jitter is cosmetic; values are never moved
fig = go.Figure()
for i, (label, v) in enumerate(parts):
base = k - 1 - i # first group on top
color = PALETTE[i % len(PALETTE)]
h = bandwidth(v, "nrd0") * 1
# half violin over [min − bw, max + bw]; one scale group keeps one density scale (tallest group)
fig.add_violin(x=v, y=np.full(v.size, base), orientation="h", side="positive", width=0.9, bandwidth=h,
spanmode="manual", span=[v.min() - h, v.max() + h], scalegroup="all", scalemode="width",
points=False, box_visible=False, line_color=color, fillcolor=color, opacity=0.55, name=label, showlegend=False)
s = box_stats(v) # type-7 quartiles, whiskers within 1.5 × IQR (precomputed)
fig.add_box(y=[base - 0.1], q1=[s["q1"]], median=[s["med"]], q3=[s["q3"]], lowerfence=[s["lo"]], upperfence=[s["hi"]],
orientation="h", width=0.08, line_color=color, fillcolor="rgba(0,0,0,0)", showlegend=False)
fig.add_scatter(x=v, y=base - 0.27 + rng.uniform(-0.07, 0.07, v.size), mode="markers", marker=dict(color=color, size=4, opacity=0.6), showlegend=False)
fig.update_layout(violinmode="overlay", xaxis_title="rt_ms", yaxis=dict(tickvals=[k - 1 - i for i in range(k)], ticktext=[label for label, _ in parts], showgrid=False), height=160 + 110 * k)
fig.show()
Needs pandas, numpy, plotly · reads raincloud-demo.csv · app theme from the optional codesplash helper
# Raincloud — Codesplash Chart Lab (recipe "raincloud")# controls: cloud=true, box=true, points=true, adjust=1
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("raincloud-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["condition"]] <- factor(df[["condition"]], levels = c("Congruent", "Neutral", "Incongruent"))
kde <- function(v, h, grid) {
# Gaussian kernel density by direct summation on `grid` (the app's method; density() uses an FFT)
vapply(grid, function(g) sum(dnorm((g - v) / h)), numeric(1)) / (length(v) * h)
}
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "rt_ms", "condition", max_levels = 8)
k <- length(parts)
base <- setNames(k - seq_len(k), names(parts)) # first group on top
clouds <- do.call(rbind, lapply(names(parts), function(lbl) {
v <- parts[[lbl]]
h <- bw.nrd0(v) * 1
grid <- seq(min(v) - h, max(v) + h, length.out = 96) # cloud over [min − bw, max + bw]
data.frame(group = lbl, x = grid, d = if (length(v) > 1) kde(v, h, grid) else 0)
}))
clouds$base <- base[clouds$group]
clouds$top <- clouds$base + 0.45 * clouds$d / max(clouds$d) # scaled to the tallest group
pts <- data.frame(group = rep(names(parts), lengths(parts)), x = unlist(parts, use.names = FALSE))
pts$base <- base[pts$group]
cols <- setNames(rep(cs_cat, length.out = k), names(parts))
p <- ggplot()
p <- p + geom_ribbon(data = clouds, aes(x = x, ymin = base, ymax = top, fill = group), alpha = 0.5, show.legend = FALSE)
p <- p + geom_boxplot(data = pts, aes(x = x, y = base - 0.1, group = group), orientation = "y", width = 0.08, coef = 1.5, outlier.shape = NA, fill = NA) # type 7
p <- p + geom_point(data = pts, aes(x = x, y = base - 0.27, colour = group), position = position_jitter(width = 0, height = 0.07, seed = 11), size = 0.8, alpha = 0.6, show.legend = FALSE)
p <- p + scale_fill_manual(values = cols) + scale_colour_manual(values = cols) +
scale_y_continuous(breaks = base, labels = names(base)) +
labs(x = "rt_ms", y = NULL) + theme_cs + theme(panel.grid.major.y = element_blank())
print(p)
Needs ggplot2 · reads raincloud-demo.csv · app theme from the optional codesplashr helper
-- Raincloud — Codesplash Chart Lab (recipe "raincloud")-- controls: cloud=true, box=true, points=true, adjust=1-- Tukey box statistics: type-7 quartiles (quantile_cont), whiskers at the most extreme values-- within 1.5 × IQR of the box, notch half-width 1.58·IQR/√n (McGill, Tukey & Larsen 1978)
WITH v0 AS (
SELECT "condition"::VARCHAR AS grp, "rt_ms"::DOUBLE AS x
FROM read_csv('raincloud-demo.csv')
WHERE "rt_ms" IS NOT NULL AND isfinite("rt_ms"::DOUBLE) AND "condition" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['Congruent', 'Neutral', 'Incongruent'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 8),
q AS (
SELECT grp, rk, count(*) AS n, avg(x) AS mean,
quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.5) AS median, quantile_cont(x, 0.75) AS q3,
min(x) AS vmin, max(x) AS vmax
FROM v
GROUP BY grp, rk
)
SELECT q.grp AS "group", q.n, q.vmin AS min, q.q1, q.median, q.q3, q.vmax AS max, q.mean,
min(v.x) FILTER (WHERE v.x >= q.q1 - 1.5 * (q.q3 - q.q1)) AS whisker_lo,
max(v.x) FILTER (WHERE v.x <= q.q3 + 1.5 * (q.q3 - q.q1)) AS whisker_hi,
count(*) FILTER (WHERE v.x < q.q1 - 1.5 * (q.q3 - q.q1) OR v.x > q.q3 + 1.5 * (q.q3 - q.q1)) AS outliers,
1.58 * (q.q3 - q.q1) / sqrt(q.n) AS notch_half_width
FROM q JOIN v USING (grp)
GROUP BY q.grp, q.rk, q.n, q.vmin, q.q1, q.median, q.q3, q.vmax, q.mean
ORDER BY q.rk;
Needs duckdb · reads raincloud-demo.csv
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.
Look at the dots first: each one is an observation, spread sideways only so they don't overlap.
Read the bar beside them: the group mean with its interval.
Compare intervals with the spread of the dots: a narrow interval is about the mean, not about individual values.
1Callout 1: Each dot is one observation.
2Callout 2: The bar: mean and its interval.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
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 = go.Figure()
for i, (label, v) in enumerate(parts):
fig.add_scatter(x=i + rng.uniform(-0.5 / 2, 0.5 / 2, v.size), y=v, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=2 * 2.5, opacity=0.55), name=label, showlegend=False)
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
fig.add_scatter(x=[i], y=[m], mode="markers", marker=dict(color=INK, size=8), error_y=dict(type="data", array=[half], color=INK, width=6), showlegend=False)
fig.update_layout(xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="fertilizer"), yaxis_title="yield_t_ha", title="mean ± 95% CI (t)")
fig.show()
Needs pandas, numpy, plotly, scipy · reads strip-demo.csv · app theme from the optional codesplash helper
# Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")# controls: interval=ci, jitter=0.5, size=2.5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("strip-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["fertilizer"]] <- factor(df[["fertilizer"]], levels = c("None", "Nitrogen", "Phosphate", "Both"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "yield_t_ha", "fertilizer", max_levels = 12)
pts <- data.frame(group = factor(rep(names(parts), lengths(parts)), levels = names(parts)), value = unlist(parts, use.names = FALSE))
summ <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]; n <- length(v); s <- sd(v)
half <- qt(0.975, n - 1) * s / sqrt(n) # 95% CI: t(0.975, n − 1) · s/√n
data.frame(group = k, mean = mean(v), lo = mean(v) - if (n > 1) half else 0, hi = mean(v) + if (n > 1) half else 0)
}))
summ$group <- factor(summ$group, levels = names(parts))
p <- ggplot(pts, aes(group, value)) +
geom_point(aes(colour = group), position = position_jitter(width = 0.5 / 2, height = 0, seed = 23), size = 2.5 * 0.6, alpha = 0.55, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = length(parts)))
p <- p + geom_errorbar(data = summ, aes(x = group, ymin = lo, ymax = hi), inherit.aes = FALSE, width = 0.15, colour = ink) +
geom_point(data = summ, aes(x = group, y = mean), inherit.aes = FALSE, size = 2.4, colour = ink)
p <- p + labs(x = "fertilizer", y = "yield_t_ha", subtitle = "mean ± 95% CI (t)") + theme_cs
print(p)
Needs ggplot2 · reads strip-demo.csv · app theme from the optional codesplashr helper
-- Strip plot with mean ± CI — Codesplash Chart Lab (recipe "strip")-- controls: interval=ci, jitter=0.5, size=2.5-- per-group mean, SD (n − 1) and SE; the 95% CI half-width is qt(0.975, n − 1) · se-- (DuckDB has no t quantile function — multiply in Python/R, or use 1.96 for large n)
WITH v0 AS (
SELECT "fertilizer"::VARCHAR AS grp, "yield_t_ha"::DOUBLE AS x
FROM read_csv('strip-demo.csv')
WHERE "yield_t_ha" IS NOT NULL AND isfinite("yield_t_ha"::DOUBLE) AND "fertilizer" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 12 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['None', 'Nitrogen', 'Phosphate', 'Both'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 12)
SELECT grp AS "group", count(*) AS n, avg(x) AS mean, stddev_samp(x) AS sd, stddev_samp(x) / sqrt(count(*)) AS se
FROM v
GROUP BY grp, rk
ORDER BY rk;
Needs duckdb · reads strip-demo.csv
Jitter comes from a seeded generator in each language, so dot positions differ from the app; values, means and intervals are identical.
Read each dot's vertical position: it sits at its exact value.
The sideways spread only avoids overlap, so a wide swarm means many rows near that value.
Compare the median lines across groups, then the swarm shapes.
1Callout 1: The line: this group's median.
2Callout 2: A wide swarm: many values close together.
3Callout 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
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")# controls: size=3, median=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
def swarm(pos, r):
"""The app's greedy swarm: in value order, each point takes the smallest sideways offset
(alternating sides) that keeps circles of radius r apart. pos and r are in pixels."""
order = np.argsort(pos, kind="stable")
placed, out, start = [], np.zeros(pos.size), 0
for i in order:
x = pos[i]
while start < len(placed) and placed[start][0] < x - 2 * r:
start += 1
best = 0.0
for step in range(400):
y = 0.0 if step == 0 else (1 if step % 2 else -1) * np.ceil(step / 2) * r * 0.9
if all((px_ - x) ** 2 + (py_ - y) ** 2 >= (2 * r) ** 2 for px_, py_ in placed[start:]):
best = y
break
placed.append((x, best))
out[i] = best
return out
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
parts = groups(df, "age", "ward", max_levels=8)
W, H = 640, 360 # the plot size (pixels) the layout is computed for
R = 3 # point radius in pixels
pooled = np.concatenate([v for _, v in parts])
lo, hi = pooled.min(), pooled.max()
band = W / len(parts)
fig = go.Figure()
for i, (label, v) in enumerate(parts):
off = swarm((v - lo) / ((hi - lo) or 1) * H, R)
widest = np.abs(off).max()
if widest > 0.45 * band: # a swarm wider than its band is compressed horizontally
off *= 0.45 * band / widest
fig.add_scatter(x=i + off / band, y=v, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=2 * R), name=label, showlegend=False)
fig.add_shape(type="line", x0=i - 0.4, x1=i + 0.4, y0=np.median(v), y1=np.median(v), line=dict(color=INK, width=2)) # type-7 median
fig.update_layout(width=W + 120, height=H + 110, xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="ward"), yaxis_title="age")
fig.show()
Needs pandas, numpy, plotly · reads beeswarm-demo.csv · app theme from the optional codesplash helper
# Beeswarm — Codesplash Chart Lab (recipe "beeswarm")# controls: size=3, median=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("beeswarm-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["ward"]] <- factor(df[["ward"]], levels = c("Cardiology", "Maternity", "Pediatrics"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
swarm <- function(pos, r) {
# the app's greedy swarm: in value order, each point takes the smallest sideways offset # (alternating sides) that keeps circles of radius r apart; pos and r are in pixels
out <- numeric(length(pos)); px <- numeric(0); py <- numeric(0); start <- 1
for (i in order(pos)) {
x <- pos[i]
while (start <= length(px) && px[start] < x - 2 * r) start <- start + 1
near <- if (start <= length(px)) start:length(px) else integer(0)
best <- 0
for (step in 0:399) {
y <- if (step == 0) 0 else (if (step %% 2 == 1) 1 else -1) * ceiling(step / 2) * r * 0.9
if (all((px[near] - x)^2 + (py[near] - y)^2 >= (2 * r)^2)) { best <- y; break }
}
px <- c(px, x); py <- c(py, best); out[i] <- best
}
out
}
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "age", "ward", max_levels = 8)
W <- 640; H <- 360 # the plot size (pixels) the layout is computed for
R <- 3 # point radius in pixels
pooled <- unlist(parts, use.names = FALSE)
rng <- range(pooled); band <- W / length(parts)
pts <- do.call(rbind, lapply(seq_along(parts), function(i) {
v <- parts[[i]]
off <- swarm((v - rng[1]) / max(diff(rng), 1e-12) * H, R)
if (max(abs(off)) > 0.45 * band) off <- off * 0.45 * band / max(abs(off)) # compress a swarm wider than its band
data.frame(group = names(parts)[i], pos = i - 1 + off / band, value = v)
}))
pts$group <- factor(pts$group, levels = names(parts))
p <- ggplot(pts, aes(pos, value, colour = group)) +
geom_point(size = 3 * 0.55, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = length(parts))) +
scale_x_continuous(breaks = seq_along(parts) - 1, labels = names(parts)) +
labs(x = "ward", y = "age") + theme_cs
med <- data.frame(i = seq_along(parts) - 1, m = vapply(parts, median, 0)) # type-7 median
p <- p + geom_segment(data = med, aes(x = i - 0.4, xend = i + 0.4, y = m, yend = m), inherit.aes = FALSE, colour = ink, linewidth = 0.8)
print(p)
Needs ggplot2 · reads beeswarm-demo.csv · app theme from the optional codesplashr 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.
Count the dots: each one is one observation, stacked in its bin.
Look at the stack heights for the shape, as you would on a histogram.
Notice isolated dots: in a small sample each one matters.
1Callout 1: A tall stack: many observations share nearly the same value.
2Callout 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
# Dot plot (Wilkinson) — Codesplash Chart Lab (recipe "dot-plot")# controls: bins=30
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for centre, count in stacks:
for j in range(count): # circles in data units: diameter = binwidth
fig.add_shape(type="circle", x0=centre - 0.47 * w, x1=centre + 0.47 * w, y0=(j + 0.03) * w, y1=(j + 0.97) * w, fillcolor=PALETTE[0], line_width=0)
fig.add_scatter(x=[s[0] for s in stacks], y=[s[1] * w for s in stacks], mode="markers", marker_opacity=0, hovertext=[f"{s[1]} values" for s in stacks], showlegend=False)
fig.update_xaxes(range=[x.min() - w, x.max() + w], title="sleep_h")
fig.update_yaxes(range=[0, max(tallest * w, (x.max() - x.min()) / 4)], scaleanchor="x", visible=False)
fig.show()
Needs pandas, numpy, plotly · reads dot-plot-demo.csv · app theme from the optional codesplash helper
# Dot plot (Wilkinson) — Codesplash Chart Lab (recipe "dot-plot")# controls: bins=30
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("dot-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
x <- df[["sleep_h"]]
x <- sort(x[is.finite(x)])
w <- diff(range(x)) / 30 # binwidth = range / 30
# tallest Wilkinson stack (to keep dots inside the panel, as the app shrinks them)
bin <- integer(length(x)); b <- 0L; end <- -Inf
for (i in seq_along(x)) { if (x[i] >= end) { b <- b + 1L; end <- x[i] + w }; bin[i] <- b }
tallest <- max(tabulate(bin))
p <- ggplot(data.frame(x = x), aes(x)) +
# Wilkinson dot-density: a value >= the current bin end starts [x, x + w); stack centre = midpoint
geom_dotplot(method = "dotdensity", binwidth = w, stackratio = 1, fill = cs_cat[1], colour = NA,
dotsize = min(1, 0.9 / (tallest * w / diff(range(x)) * 1.6))) +
scale_y_continuous(NULL, breaks = NULL) +
labs(x = "sleep_h") + theme_cs
print(p)
Needs ggplot2 · reads dot-plot-demo.csv · app theme from the optional codesplashr helper
-- Dot plot (Wilkinson) — Codesplash Chart Lab (recipe "dot-plot")-- controls: bins=30-- Wilkinson dot-density binning, binwidth w = range / 30: scan the sorted values; a value ≥ the-- current bin end starts a new bin [x, x + w); stack centre = midpoint of its first and last value.-- The scan is sequential (one recursion step per row) — fine for samples, slow for millions of rows.
WITH RECURSIVE v AS (
SELECT "sleep_h"::DOUBLE AS x, row_number() OVER (ORDER BY "sleep_h"::DOUBLE) AS i
FROM read_csv('dot-plot-demo.csv')
WHERE "sleep_h" IS NOT NULL AND isfinite("sleep_h"::DOUBLE)
),
w AS (SELECT (max(x) - min(x)) / 30 AS w FROM v),
scan(i, x, bin_start) AS (
SELECT i, x, x FROM v WHERE i = 1
UNION ALL
SELECT v.i, v.x, CASE WHEN v.x >= scan.bin_start + w.w THEN v.x ELSE scan.bin_start END
FROM scan JOIN v ON v.i = scan.i + 1 CROSS JOIN w
)
SELECT bin_start, (min(x) + max(x)) / 2 AS centre, count(*) AS dots
FROM scan
GROUP BY bin_start
ORDER BY bin_start;
Find the median line, then the widest box: it holds the middle half.
Each narrower box halves the tail again, so the stack shows how the tails behave.
Compare how quickly boxes shrink across groups: slow shrinking means a long tail.
1Callout 1: Widest box: the middle half.
2Callout 2: Each narrower box covers half of what remains in the tail.
3Callout 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
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)]
INK = cs.palette(dark=False)["foreground"] if cs else "#131922"
BG = cs.palette(dark=False)["background"] if cs else "#ffffff"
parts = [(label, v) for label, v in groups(df, "order_value", "region", max_levels=8) if v.size > 3]
bg = np.array(px.colors.hex_to_rgb(BG))
fig = go.Figure()
for i, (label, v) in enumerate(parts):
color = np.array(px.colors.hex_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
r, g_, b = (color * share + bg * (1 - share)).round().astype(int)
fig.add_shape(type="rect", x0=i - half, x1=i + half, y0=lo, y1=hi, fillcolor=f"rgb({r}, {g_}, {b})", line_width=0, layer="below")
fig.add_shape(type="line", x0=i - 0.4, x1=i + 0.4, y0=np.median(v), y1=np.median(v), line=dict(color=INK, width=2))
_, lo, hi = boxes[-1]
out = v[(v < lo) | (v > hi)] # beyond the deepest box
fig.add_scatter(x=np.full(out.size, i), y=out, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=5, opacity=0.6), name=label, showlegend=False)
fig.add_scatter(x=[i, i], y=[v.min(), v.max()], mode="markers", marker_opacity=0, showlegend=False, hoverinfo="skip") # keeps the axis range
fig.update_layout(xaxis=dict(tickvals=list(range(len(parts))), ticktext=[label for label, _ in parts], title="region", range=[-0.6, len(parts) - 0.4]), yaxis_title="order_value")
fig.show()
Needs pandas, numpy, plotly · reads boxen-demo.csv · app theme from the optional codesplash helper
# Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("boxen-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
letter_values <- function(v, outlier_share = 0.007) {
# tail probabilities 2^-(d+1), d = 1..k (type 7); about 0.7 % of points stay beyond the deepest box
n <- length(v)
k <- max(1, floor(log2(n) - log2(max(1, n * outlier_share))) + 1)
p <- 2^-(seq_len(k) + 1)
data.frame(depth = seq_len(k), lo = quantile(v, p, type = 7, names = FALSE), hi = quantile(v, 1 - p, type = 7, names = FALSE))
}
bg <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$background else "#ffffff"
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
parts <- groups_of(df, "order_value", "region", max_levels = 8)
parts <- parts[lengths(parts) > 3]
mix <- function(col, share) vapply(share, function(s) grDevices::rgb(t(grDevices::col2rgb(col) * s + grDevices::col2rgb(bg) * (1 - s)) / 255), "")
boxes <- do.call(rbind, lapply(seq_along(parts), function(i) {
lv <- letter_values(parts[[i]])
k <- nrow(lv)
half <- 0.4 * (1 - 0.7 * (lv$depth - 1) / k) # deeper boxes are narrower …
share <- (92 - 72 * (lv$depth - 1) / max(1, k - 1)) / 100 # … and fade toward the background
data.frame(i = i - 1, depth = lv$depth, xmin = i - 1 - half, xmax = i - 1 + half, lo = lv$lo, hi = lv$hi,
fill = mix(cs_cat[(i - 1) %% length(cs_cat) + 1], share))
}))
outs <- do.call(rbind, lapply(seq_along(parts), function(i) {
v <- parts[[i]]; deepest <- boxes[boxes$i == i - 1, ][which.max(boxes$depth[boxes$i == i - 1]), ]
o <- v[v < deepest$lo | v > deepest$hi] # beyond the deepest box
if (length(o)) data.frame(i = i - 1, value = o, group = names(parts)[i]) else NULL
}))
boxes <- boxes[order(boxes$i, -boxes$depth), ] # deepest first, so wider, darker central boxes sit on top
med <- data.frame(i = seq_along(parts) - 1, m = vapply(parts, median, 0))
p <- ggplot() +
geom_rect(data = boxes, aes(xmin = xmin, xmax = xmax, ymin = lo, ymax = hi, fill = I(fill))) +
geom_segment(data = med, aes(x = i - 0.4, xend = i + 0.4, y = m, yend = m), colour = ink, linewidth = 0.9) +
scale_x_continuous(breaks = seq_along(parts) - 1, labels = names(parts)) +
labs(x = "region", y = "order_value") + theme_cs
if (!is.null(outs)) p <- p + geom_point(data = outs, aes(i, value), colour = cs_cat[1], alpha = 0.6, size = 1)
print(p)
Needs ggplot2 · reads boxen-demo.csv · app theme from the optional codesplashr helper
-- Letter-value (boxen) plot — Codesplash Chart Lab (recipe "boxen")-- controls: defaults-- letter values per group: tail probabilities 2^−(d+1), d = 1…k with-- k = ⌊log₂ n − log₂ max(1, 0.007·n)⌋ + 1 (never more than 8), type-7 quantiles (quantile_cont)
WITH v0 AS (
SELECT "region"::VARCHAR AS grp, "order_value"::DOUBLE AS x
FROM read_csv('boxen-demo.csv')
WHERE "order_value" IS NOT NULL AND isfinite("order_value"::DOUBLE) AND "region" IS NOT NULL
),
lv AS ( -- level order as stored in the data dictionary; at most 8 groups
SELECT grp, row_number() OVER (ORDER BY list_position(['North', 'South', 'West'], grp)) AS rk
FROM (SELECT grp, count(*) AS n FROM v0 GROUP BY grp)
),
v AS (SELECT v0.grp, v0.x, lv.rk FROM v0 JOIN lv USING (grp) WHERE lv.rk <= 8),
q AS (
SELECT grp, rk, count(*) AS n, quantile_cont(x, 0.5) AS median,
quantile_cont(x, [0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125]) AS lo,
quantile_cont(x, [0.75, 0.875, 0.9375, 0.96875, 0.984375, 0.9921875, 0.99609375, 0.998046875]) AS hi
FROM v
GROUP BY grp, rk
HAVING count(*) > 3
)
SELECT grp AS "group", d AS depth, lo[d] AS lo, hi[d] AS hi, median, n
FROM q, range(1, 9) t(d)
WHERE d <= floor(log2(n) - log2(greatest(1, 0.007 * n))) + 1
ORDER BY rk, d;
Needs duckdb · reads boxen-demo.csv
seaborn's boxenplot(k_depth="proportion") rounds the depth slightly differently, so the code draws the letter values itself.
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
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")# controls: bins=fd, value=percent
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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
fig.add_scatter(x=xs, y=np.r_[0, counts / v.size * 100, 0], mode="lines+markers", line=dict(color=PALETTE[i % len(PALETTE)], width=2, dash=SERIES_DASHES[i % 8] if many else "solid"), marker=dict(size=6 if many else 5, symbol=SERIES_MARKERS[i % 8] if many else "circle"), name=label)
fig.update_layout(xaxis_title="commute_min", yaxis_title="Percent of group", showlegend=len(parts) > 1)
fig.show()
Needs pandas, numpy, plotly · reads freq-poly-demo.csv · app theme from the optional codesplash helper
# Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")# controls: bins=fd, value=percent
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("freq-poly-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["mode"]] <- factor(df[["mode"]], levels = c("Car", "Transit", "Bike"))
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
groups_of <- function(df, value, group = NULL, max_levels = 12) {
# values per group in level order; rows missing the value or the group are dropped
v <- df[[value]]
if (is.null(group)) return(stats::setNames(list(v[is.finite(v)]), value))
g <- df[[group]]
keep <- is.finite(v) & !is.na(g)
out <- split(v[keep], factor(g[keep], levels = utils::head(levels(g), max_levels)))
out[lengths(out) > 0]
}
parts <- groups_of(df, "commute_min", "mode", max_levels = 8)
breaks <- np_edges(unlist(parts, use.names = FALSE), "fd") # one shared set of numpy edges on the pooled data
w <- diff(breaks)[1]
mids <- c(breaks[1] - w / 2, (head(breaks, -1) + tail(breaks, -1)) / 2, tail(breaks, 1) + w / 2) # closed to zero half a bin beyond each end
poly <- do.call(rbind, lapply(names(parts), function(k) {
v <- parts[[k]]
counts <- tabulate(findInterval(v, breaks, rightmost.closed = TRUE, all.inside = TRUE), nbins = length(breaks) - 1) # [a, b), last closed
data.frame(group = k, x = mids, y = c(0, counts / length(v) * 100, 0))
}))
poly$group <- factor(poly$group, levels = names(parts))
p <- ggplot(poly, aes(x, y, colour = group, linetype = group, shape = group)) + # dash and dot shape per group, as in the app
geom_line(linewidth = 0.9) + geom_point(data = function(d) d[!(d$x %in% range(d$x)), ], size = 1.6) + # dots at the bin midpoints, not the closing zeros
scale_colour_manual(values = rep(cs_cat, length.out = length(parts))) + scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = "commute_min", y = "Percent of group", colour = NULL, linetype = NULL, shape = NULL) + theme_cs
if (length(parts) == 1) p <- p + theme(legend.position = "none")
print(p)
Needs ggplot2 · reads freq-poly-demo.csv · app theme from the optional codesplashr helper
-- Frequency polygon — Codesplash Chart Lab (recipe "freq-poly")-- controls: bins=fd, value=percent-- one shared set of numpy-style edges over the pooled data; counts per group, bins [a, b) with the last closed-- (bins a group never reaches have no row)
WITH v AS (
SELECT "mode"::VARCHAR AS grp, "commute_min"::DOUBLE AS x
FROM read_csv('freq-poly-demo.csv')
WHERE "commute_min" IS NOT NULL AND isfinite("commute_min"::DOUBLE) AND "mode" IS NOT NULL
),
s AS (
SELECT min(x) AS lo, max(x) AS hi, count(*) AS n,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1
FROM v
),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(CASE WHEN true THEN 2 * iqr * pow(n, -1.0 / 3) END, 0)))::INTEGER, 1) AS k FROM s),
b AS (
SELECT grp, least(floor((x - lo) / ((hi - lo) / k)), k - 1)::INTEGER AS bin
FROM v, k
)
SELECT grp, bin,
lo + bin * (hi - lo) / k AS x0,
lo + (bin + 1) * (hi - lo) / k AS x1,
count(*) AS count,
count(*) / sum(count(*)) OVER (PARTITION BY grp) AS share,
count(*) / sum(count(*)) OVER (PARTITION BY grp) / ((hi - lo) / k) AS density
FROM b, k
GROUP BY grp, bin, lo, hi, k
ORDER BY grp, bin;
Read a row as stem plus leaf: the stem is the leading digit and each leaf is the next digit of one value.
Turn your head sideways: the leaf lengths form a histogram.
Check the note above the display for where the decimal point falls.
1Callout 1: Stem: the leading digit.
2Callout 2: Leaves: the next digit of each value in this row.
3Callout 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
Needs ggplot2 · reads stem-leaf-demo.csv · app theme from the optional codesplashr 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.
Find the darkest cells: that is where most rows sit.
Read the overall tilt of the dark area for the direction of the relationship.
Check the colour bar: it tells you how many rows each shade means.
1Callout 1: Darkest cells: where most rows fall.
2Callout 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
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")# controls: binsX=30, binsY=20, scale=linear
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
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 = go.Figure(go.Heatmap(x=(xe[:-1] + xe[1:]) / 2, y=(ye[:-1] + ye[1:]) / 2, z=Z.T, colorscale=[[0, SEQ[0]], [1, SEQ[1]]],
customdata=H.T, hovertemplate="count %{customdata}<extra></extra>", colorbar=dict(title="count")))
fig.update_layout(xaxis_title="height_cm", yaxis_title="weight_kg")
fig.show()
Needs pandas, numpy, plotly · reads hist2d-demo.csv · app theme from the optional codesplash helper
# 2-D histogram — Codesplash Chart Lab (recipe "hist2d")# controls: binsX=30, binsY=20, scale=linear
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("hist2d-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
seq_cols <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$sequential else c("#eff6fd", "#1a469d") # the app's sequential ramp
d <- df[is.finite(df[["height_cm"]]) & is.finite(df[["weight_kg"]]), , drop = FALSE]
edges <- function(v, k) { r <- range(v); if (r[1] == r[2]) r <- r + c(-0.5, 0.5); seq(r[1], r[2], length.out = k + 1) } # numpy histogram2d edges
xe <- edges(d[["height_cm"]], 30); ye <- edges(d[["weight_kg"]], 20)
ix <- findInterval(d[["height_cm"]], xe, rightmost.closed = TRUE, all.inside = TRUE) # [a, b), last bin closed
iy <- findInterval(d[["weight_kg"]], ye, rightmost.closed = TRUE, all.inside = TRUE)
cells <- as.data.frame(table(ix = factor(ix, levels = seq_len(30)), iy = factor(iy, levels = seq_len(20))), responseName = "count")
cells$ix <- as.integer(cells$ix); cells$iy <- as.integer(cells$iy)
cells <- transform(cells, x0 = xe[ix], x1 = xe[ix + 1], y0 = ye[iy], y1 = ye[iy + 1])
p <- ggplot(cells, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = count)) +
geom_rect() + # empty cells show the ramp's low end
scale_fill_gradient(low = seq_cols[1], high = seq_cols[2], name = "count") +
labs(x = "height_cm", y = "weight_kg") + theme_cs
print(p)
Needs ggplot2 · reads hist2d-demo.csv · app theme from the optional codesplashr helper
-- 2-D histogram — Codesplash Chart Lab (recipe "hist2d")-- controls: binsX=30, binsY=20, scale=linear-- numpy histogram2d(x, y, bins=[30, 20]): equal-width edges over [min, max] per axis, bins [a, b) with the-- last one closed; rows with a missing coordinate are dropped; empty cells have no row
WITH v AS (
SELECT "height_cm"::DOUBLE AS x, "weight_kg"::DOUBLE AS y
FROM read_csv('hist2d-demo.csv')
WHERE "height_cm" IS NOT NULL AND "weight_kg" IS NOT NULL AND isfinite("height_cm"::DOUBLE) AND isfinite("weight_kg"::DOUBLE)
),
s AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1 FROM v),
b AS (
SELECT least(floor((x - x0) / (x1 - x0) * 30), 29)::INTEGER AS ix,
least(floor((y - y0) / (y1 - y0) * 20), 19)::INTEGER AS iy
FROM v, s
)
SELECT ix, iy,
x0 + ix * (x1 - x0) / 30 AS x_lo, x0 + (ix + 1) * (x1 - x0) / 30 AS x_hi,
y0 + iy * (y1 - y0) / 20 AS y_lo, y0 + (iy + 1) * (y1 - y0) / 20 AS y_hi,
count(*) AS count
FROM b, s
GROUP BY ix, iy, x0, x1, y0, y1
ORDER BY ix, iy;
Find the darkest hexagons: the densest part of the data.
Read the shape the hexagons trace for the relationship.
Look for isolated light hexagons far from the main cloud: rare combinations worth checking.
1Callout 1: Darkest hexagons: the most rows.
2Callout 2: Isolated hexagons: rare combinations.
3Callout 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
# Hexbin — Codesplash Chart Lab (recipe "hexbin")# controls: gridsize=30, log=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("hexbin-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
def hexbin_cells(x, y, nx):
"""matplotlib's hexbin lattice (what the app reproduces): ny = ⌊nx/√3⌋, two offset rectangular
lattices, each point goes to the nearer centre under (Δx)² + 3(Δy)² in grid units."""
ny = max(1, int(nx / np.sqrt(3)))
xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
pad = 1e-9 * (xmax - xmin)
xmin, xmax = xmin - pad, xmax + pad
sx, sy = (xmax - xmin) / nx, (ymax - ymin) / ny
ix, iy = (x - xmin) / sx, (y - ymin) / sy
ix1, iy1, ix2, iy2 = np.round(ix), np.round(iy), np.floor(ix), np.floor(iy)
first = (ix - ix1) ** 2 + 3 * (iy - iy1) ** 2 < (ix - ix2 - 0.5) ** 2 + 3 * (iy - iy2 - 0.5) ** 2
cx = np.where(first, xmin + ix1 * sx, xmin + (ix2 + 0.5) * sx)
cy = np.where(first, ymin + iy1 * sy, ymin + (iy2 + 0.5) * sy)
cells = pd.DataFrame({"x": cx, "y": cy}).value_counts().reset_index(name="count")
return cells, sx, sy
def ramp(t):
"""A colour on the sequential ramp, t in [0, 1] (interpolated in RGB)."""
a, b = np.array(px.colors.hex_to_rgb(SEQ[0])), np.array(px.colors.hex_to_rgb(SEQ[1]))
r, g, bl = (a + (b - a) * min(max(t, 0.0), 1.0)).round().astype(int)
return f"rgb({r}, {g}, {bl})"
SEQ = cs.palette(dark=False)["sequential"] if cs else ["#eff6fd", "#1a469d"] # the app's sequential ramp
d = df[["distance_km", "fare_usd"]].dropna()
cells, sx, sy = hexbin_cells(d["distance_km"].to_numpy(dtype=float), d["fare_usd"].to_numpy(dtype=float), 30)
z = np.log1p(cells["count"]) # log(1 + count)
# plotly has no hexbin trace: draw pointy-top hexagons, one filled trace per colour step of the ramp
hx = np.array([0.5, 0.5, 0, -0.5, -0.5, 0, 0.5]) * sx
hy = np.array([-1, 1, 2, 1, -1, -2, -1]) * sy / 6
steps = 9
level = np.minimum((z / z.max() * steps).astype(int), steps - 1)
fig = go.Figure()
for k in range(steps):
sel = cells[level == k]
if sel.empty:
continue
xs = np.concatenate([np.r_[cx + hx, np.nan] for cx in sel["x"]])
ys = np.concatenate([np.r_[cy + hy, np.nan] for cy in sel["y"]])
fig.add_scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=ramp((k + 0.5) / steps), line=dict(width=0), hoverinfo="skip", showlegend=False)
fig.add_scatter(x=cells["x"], y=cells["y"], mode="markers", marker=dict(size=4, opacity=0, color=z, colorscale=[[0, SEQ[0]], [1, SEQ[1]]], showscale=True,
colorbar=dict(title="log(1 + count)")), customdata=cells["count"], hovertemplate="count %{customdata}<extra></extra>", showlegend=False)
fig.update_layout(xaxis_title="distance_km", yaxis_title="fare_usd")
fig.show()
Needs pandas, numpy, plotly · reads hexbin-demo.csv · app theme from the optional codesplash helper
# Hexbin — Codesplash Chart Lab (recipe "hexbin")# controls: gridsize=30, log=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("hexbin-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
seq_cols <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$sequential else c("#eff6fd", "#1a469d") # the app's sequential ramp
hex_cells <- function(x, y, nx) {
# matplotlib's hexbin lattice (the app reproduces it): ny = floor(nx / sqrt(3)), two offset lattices, # each point goes to the nearer centre under dx^2 + 3 dy^2 in grid units; round() is half-to-even like numpy
ny <- max(1, floor(nx / sqrt(3)))
xmin <- min(x); xmax <- max(x); ymin <- min(y); ymax <- max(y)
pad <- 1e-9 * (xmax - xmin); xmin <- xmin - pad; xmax <- xmax + pad
sx <- (xmax - xmin) / nx; sy <- (ymax - ymin) / ny
ix <- (x - xmin) / sx; iy <- (y - ymin) / sy
first <- (ix - round(ix))^2 + 3 * (iy - round(iy))^2 < (ix - floor(ix) - 0.5)^2 + 3 * (iy - floor(iy) - 0.5)^2
cx <- ifelse(first, xmin + round(ix) * sx, xmin + (floor(ix) + 0.5) * sx)
cy <- ifelse(first, ymin + round(iy) * sy, ymin + (floor(iy) + 0.5) * sy)
cells <- aggregate(list(count = rep(1, length(cx))), list(x = cx, y = cy), sum)
list(cells = cells, sx = sx, sy = sy)
}
d <- df[is.finite(df[["distance_km"]]) & is.finite(df[["fare_usd"]]), , drop = FALSE]
hb <- hex_cells(d[["distance_km"]], d[["fare_usd"]], 30)
cells <- hb$cells
# pointy-top hexagons: vertices at (+-sx/2, +-sy/6) and (0, +-sy/3)
hexes <- data.frame(id = rep(seq_len(nrow(cells)), each = 6), count = rep(cells$count, each = 6),
x = rep(cells$x, each = 6) + c(0.5, 0.5, 0, -0.5, -0.5, 0) * hb$sx,
y = rep(cells$y, each = 6) + c(-1, 1, 2, 1, -1, -2) * hb$sy / 6)
p <- ggplot(hexes, aes(x, y, group = id, fill = count)) +
geom_polygon() + # empty hexes are not drawn
scale_fill_gradient(low = seq_cols[1], high = seq_cols[2], transform = "log1p", name = "count (log scale)") +
labs(x = "distance_km", y = "fare_usd") + theme_cs
print(p)
Needs ggplot2 · reads hexbin-demo.csv · app theme from the optional codesplashr helper
-- Hexbin — Codesplash Chart Lab (recipe "hexbin")-- controls: gridsize=30, log=true-- matplotlib hexbin lattice (gridsize 30): ny = ⌊nx/√3⌋, two offset rectangular lattices; each point goes to-- the nearer centre under (Δx)² + 3(Δy)² in grid units (round_even = numpy's half-to-even rounding)
WITH v AS (
SELECT "distance_km"::DOUBLE AS x, "fare_usd"::DOUBLE AS y
FROM read_csv('hexbin-demo.csv')
WHERE "distance_km" IS NOT NULL AND "fare_usd" IS NOT NULL AND isfinite("distance_km"::DOUBLE) AND isfinite("fare_usd"::DOUBLE)
),
s AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS ymin, max(y) AS ymax FROM v),
g AS (
SELECT x0 - 1e-9 * (x1 - x0) AS xmin, ymin,
(x1 - x0) * (1 + 2e-9) / 30 AS sx,
(ymax - ymin) / greatest(1, floor(30 / sqrt(3))) AS sy
FROM s
),
p AS (SELECT (x - xmin) / sx AS ix, (y - ymin) / sy AS iy, xmin, ymin, sx, sy FROM v, g),
c AS (
SELECT *, pow(ix - round_even(ix, 0), 2) + 3 * pow(iy - round_even(iy, 0), 2)
< pow(ix - floor(ix) - 0.5, 2) + 3 * pow(iy - floor(iy) - 0.5, 2) AS first
FROM p
)
SELECT CASE WHEN first THEN xmin + round_even(ix, 0) * sx ELSE xmin + (floor(ix) + 0.5) * sx END AS cx,
CASE WHEN first THEN ymin + round_even(iy, 0) * sy ELSE ymin + (floor(iy) + 0.5) * sy END AS cy,
count(*) AS count, any_value(sx) AS sx, any_value(sy) AS sy
FROM c
GROUP BY ALL
ORDER BY cx, cy;
Needs duckdb · reads hexbin-demo.csv
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.
Read the bands like a contour map: each inner band is denser than the one around it.
Count the separate peaks: each may be a distinct group.
Read each band's orientation for how the two variables move together inside that group.
1Callout 1: The innermost band: the top of this hill.
2Callout 2: A second hill: a second cluster of rows.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
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 = go.Figure(go.Contour(x=gx, y=gy, z=z.T, colorscale=[[0, SEQ[0]], [1, SEQ[1]]], showscale=False, line_width=0.8,
contours=dict(start=levels[0], end=levels[-1], size=levels[1] - levels[0] if levels.size > 1 else 1, coloring="fill")))
fig.add_scatter(x=xs, y=ys, mode="markers", marker=dict(color=PALETTE[0], size=3, opacity=0.35), showlegend=False)
fig.update_layout(xaxis_title="duration_min", yaxis_title="waiting_min")
fig.show()
Needs pandas, numpy, plotly · reads density-2d-demo.csv · app theme from the optional codesplash helper
# 2-D density contours — Codesplash Chart Lab (recipe "density-2d")# controls: levels=7, grid=60, fill=true, points=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("density-2d-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
seq_cols <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$sequential else c("#eff6fd", "#1a469d") # the app's sequential ramp
ink <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$foreground else "#131922"
d <- df[is.finite(df[["duration_min"]]) & is.finite(df[["waiting_min"]]), , drop = FALSE]
x <- d[["duration_min"]]; y <- d[["waiting_min"]]
lims <- c(range(x) + c(-1, 1) * 0.15 * diff(range(x)), range(y) + c(-1, 1) * 0.15 * diff(range(y))) # expanded 15 % per side
k2 <- MASS::kde2d(x, y, n = 60, lims = lims) # product Gaussian kernel, h = bandwidth.nrd (SDs h/4)
grid <- expand.grid(x = k2$x, y = k2$y)
grid$z <- as.vector(k2$z)
levels <- max(grid$z) * seq_len(7) / (7 + 1) # equally spaced levels max·i/(k + 1)
p <- ggplot(grid, aes(x, y, z = z))
p <- p + geom_contour_filled(breaks = c(levels, Inf), show.legend = FALSE) +
scale_fill_manual(values = colorRampPalette(seq_cols)(length(levels)), drop = FALSE)
p <- p + geom_contour(breaks = levels, colour = ink, linewidth = 0.3, alpha = 0.6)
p <- p + geom_point(data = data.frame(x = x, y = y), aes(x, y), inherit.aes = FALSE, colour = cs_cat[1], size = 0.6, alpha = 0.35)
p <- p + labs(x = "duration_min", y = "waiting_min") + theme_cs
print(p)
Needs ggplot2 · reads density-2d-demo.csv · app theme from the optional codesplashr helper
-- 2-D density contours — Codesplash Chart Lab (recipe "density-2d")-- controls: levels=7, grid=60, fill=true, points=true-- MASS::kde2d on a 60 × 60 grid over the range expanded by 15 % per side: product Gaussian kernel with-- standard deviations h/4, h = bandwidth.nrd = 4·1.06·min(sd, IQR/1.34)·n^(−1/5). Cost is grid² × rows.
WITH v AS (
SELECT "duration_min"::DOUBLE AS x, "waiting_min"::DOUBLE AS y
FROM read_csv('density-2d-demo.csv')
WHERE "duration_min" IS NOT NULL AND "waiting_min" IS NOT NULL AND isfinite("duration_min"::DOUBLE) AND isfinite("waiting_min"::DOUBLE)
),
s AS (
SELECT count(*) AS n, min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1,
stddev_samp(x) AS sdx, stddev_samp(y) AS sdy,
quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqrx,
quantile_cont(y, 0.75) - quantile_cont(y, 0.25) AS iqry
FROM v
),
h AS (
SELECT n, 1.06 * least(sdx, coalesce(nullif(iqrx / 1.34, 0), sdx)) * pow(n, -0.2) AS hx,
1.06 * least(sdy, coalesce(nullif(iqry / 1.34, 0), sdy)) * pow(n, -0.2) AS hy,
x0 - 0.15 * (x1 - x0) AS gx0, x1 + 0.15 * (x1 - x0) AS gx1,
y0 - 0.15 * (y1 - y0) AS gy0, y1 + 0.15 * (y1 - y0) AS gy1
FROM s
),
gx AS (SELECT gx0 + (gx1 - gx0) * i / 59 AS gx FROM h, range(60) t(i)),
gy AS (SELECT gy0 + (gy1 - gy0) * j / 59 AS gy FROM h, range(60) t(j))
SELECT gx.gx AS x, gy.gy AS y,
sum(exp(-0.5 * pow((gx.gx - v.x) / h.hx, 2)) * exp(-0.5 * pow((gy.gy - v.y) / h.hy, 2)))
/ (2 * pi() * h.n * h.hx * h.hy) AS density
FROM gx, gy, v, h
GROUP BY gx.gx, gy.gy, h.n, h.hx, h.hy
ORDER BY y, x;
Needs duckdb · reads density-2d-demo.csv
R uses MASS::kde2d (ships with R); Python ports it so both grids and contour levels match the app.
Compare bar lengths: they all start at zero, so length is the value.
Read from the longest down for the ranking.
Check whether an “Other” bar groups levels beyond the top ones.
1Callout 1: Bar length: the count or share.
2Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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()
counts = counts.sort_values(ascending=False, kind="stable")
if len(counts) > 12:
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
frame = pd.DataFrame({"level": values.index, "value": values.values})
fig = px.bar(frame, x="level", y="value", text_auto="d")
fig.update_layout(showlegend=False, yaxis_title="Count", xaxis_title="channel")
fig.show()
Needs pandas, numpy, plotly · reads bar-demo.csv · app theme from the optional codesplash helper
# Bar chart — Codesplash Chart Lab (recipe "bar")# controls: value=count, orientation=vertical, order=freq, top=12, color=single, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("bar-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["channel"]] <- factor(df[["channel"]])
v <- as.character(df[["channel"]])
v <- v[!is.na(v)] # missing values excluded
counts <- sort(table(v), decreasing = TRUE)
if (length(counts) > 12) { # pool levels beyond the top 12 into "Other"
counts <- c(counts[seq_len(12)], Other = sum(counts[-seq_len(12)]))
}
bars <- data.frame(level = names(counts), n = as.numeric(counts))
bars$value <- bars$n
bars$level <- factor(bars$level, levels = bars$level) # by frequency
fill <- setNames(rep(cs_cat[1], nlevels(bars$level)), levels(bars$level))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6" # pooled levels in neutral grey
p <- ggplot(bars, aes(x = level, y = value, fill = level)) +
geom_col(show.legend = FALSE) +
scale_fill_manual(values = fill) +
geom_text(aes(label = value), vjust = -0.4, size = 3) +
labs(x = "channel", y = "Count") +
theme_cs
print(p)
Needs ggplot2 · reads bar-demo.csv · app theme from the optional codesplashr helper
-- Bar chart — Codesplash Chart Lab (recipe "bar")-- controls: value=count, orientation=vertical, order=freq, top=12, color=single, labels=true-- counts per level, top 12 kept and the rest pooled into 'Other'; missing excluded
WITH counts AS (
SELECT "channel"::VARCHAR AS level, count(*) AS n
FROM read_csv('bar-demo.csv')
WHERE "channel" IS NOT NULL
GROUP BY ALL
),
ranked AS (SELECT *, row_number() OVER (ORDER BY n DESC, level) AS rk FROM counts)
SELECT CASE WHEN rk <= 12 THEN level ELSE 'Other' END AS level,
sum(n) AS count,
sum(n) / (SELECT sum(n) FROM counts) AS share
FROM ranked
GROUP BY ALL
ORDER BY min(rk);
Compare the same colour across clusters to see how one subgroup changes across categories.
Compare colours within a cluster to see how subgroups differ inside one category.
Use shares within subgroup when subgroup sizes differ.
1Callout 1: One cluster: one category, split by subgroup.
2Callout 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
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")# controls: value=count, top=8, labels=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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
long = values.stack().rename("value").reset_index()
colors = {s: ("#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)]) for j, s in enumerate(values.columns)}
fig = px.bar(long, x="plan", y="value", color="region", barmode="group",
category_orders={"plan": list(values.index), "region": list(values.columns)},
color_discrete_map=colors,
pattern_shape="region", pattern_shape_map={s: SERIES_HATCHES[7 if s == "Other" else j % 8] for j, s in enumerate(values.columns)}) # texture per subgroup, as in the app
fig.update_traces(marker_pattern_fgcolor=HATCH_INK, marker_pattern_fillmode="overlay")
fig.update_layout(xaxis_title="plan", yaxis_title="Count")
fig.show()
Needs pandas, numpy, plotly · reads bar-grouped-demo.csv · app theme from the optional codesplash helper
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")# controls: value=count, top=8, labels=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("bar-grouped-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro", "Enterprise"))
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
crosstab <- function(a, b, la, lb, max_a, max_b) {
# a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last
ok <- !is.na(a) & !is.na(b)
pool <- function(v, lv, cap) {
keep <- head(lv, cap)
v <- as.character(v)
factor(ifelse(v %in% keep, v, "Other"), levels = c(keep, if (length(lv) > cap) "Other"))
}
table(category = pool(a[ok], la, max_a), group = pool(b[ok], lb, max_b))
}
tab <- crosstab(df[["plan"]], df[["region"]], levels(df[["plan"]]), levels(df[["region"]]), 8, 6)
long <- as.data.frame(tab, responseName = "n")
long$value <- long$n
fill <- setNames(rep(cs_cat, length.out = nlevels(long$group)), levels(long$group))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6" # pooled levels in neutral grey
fill <- setNames(cs_textures(unname(fill), idx = ifelse(names(fill) == "Other", 8, seq_along(fill))), names(fill)) # texture per subgroup, as in the app
p <- ggplot(long, aes(category, value, fill = group)) +
geom_col(position = position_dodge(width = 0.85), width = 0.8) +
scale_fill_manual(values = fill, name = "region") +
labs(x = "plan", y = "Count") +
theme_cs
print(p)
Needs ggplot2 · reads bar-grouped-demo.csv · app theme from the optional codesplashr helper
-- Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")-- controls: value=count, top=8, labels=false-- category × subgroup counts; levels beyond the caps pool into 'Other'; missing rows excluded
WITH
la(level, rk) AS (VALUES ('Basic', 1), ('Plus', 2), ('Pro', 3), ('Enterprise', 4)),
lb(level, rk) AS (VALUES ('North', 1), ('South', 2), ('West', 3)),
t AS (
SELECT CASE WHEN la.rk <= 8 THEN la.level ELSE 'Other' END AS a,
CASE WHEN lb.rk <= 6 THEN lb.level ELSE 'Other' END AS b,
count(*) AS n, min(la.rk) AS ra, min(lb.rk) AS rb
FROM read_csv('bar-grouped-demo.csv') s
JOIN la ON la.level = s."plan"::VARCHAR
JOIN lb ON lb.level = s."region"::VARCHAR
GROUP BY 1, 2
)
SELECT a AS "plan", b AS "region", n,
n / sum(n) OVER (PARTITION BY b) AS share_within_region
FROM t
ORDER BY ra, rb;
Read the whole bar for the total, or switch to 100% to compare composition.
Compare the first and last segments: they share a baseline.
Use the segment labels for the middle ones, which start at different points.
1Callout 1: Segment length: this subgroup's share.
2Callout 2: Middle segments float, so compare them by their labels.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
values = tab.div(tab.sum(axis=1).replace(0, np.nan), axis=0).fillna(0) * 100 # row %
fig = go.Figure()
for j, s in enumerate(values.columns):
v = values[s]
share = v / values.sum(axis=1).replace(0, np.nan)
text = [f"{x:.0f}%" if sh >= 0.06 else "" for x, sh in zip(v, share)] if True else None
color = "#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)]
fig.add_bar(y=list(values.index), x=v, orientation="h", name=s, marker_color=color, text=text, textposition="inside")
fig.update_layout(barmode="stack", legend_title_text="priority",
xaxis_title="% of category", yaxis_title="team", yaxis_autorange="reversed")
fig.show()
Needs pandas, numpy, plotly · reads bar-stacked-demo.csv · app theme from the optional codesplash helper
# Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")# controls: mode=percent, orientation=horizontal, top=10, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("bar-stacked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["team"]] <- factor(df[["team"]])
df[["priority"]] <- factor(df[["priority"]], levels = c("Critical", "High", "Medium", "Low"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
freq_levels <- function(v) {
# the app's order when the data dictionary declares none: by descending frequency, ties alphabetical
t <- table(as.character(v[!is.na(v)]))
names(t)[order(-as.numeric(t), names(t))]
}
crosstab <- function(a, b, la, lb, max_a, max_b) {
# a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last
ok <- !is.na(a) & !is.na(b)
pool <- function(v, lv, cap) {
keep <- head(lv, cap)
v <- as.character(v)
factor(ifelse(v %in% keep, v, "Other"), levels = c(keep, if (length(lv) > cap) "Other"))
}
table(category = pool(a[ok], la, max_a), group = pool(b[ok], lb, max_b))
}
tab <- crosstab(df[["team"]], df[["priority"]], freq_levels(df[["team"]]), levels(df[["priority"]]), 10, 6)
long <- as.data.frame(tab, responseName = "n")
long$value <- ave(long$n, long$category, FUN = function(v) if (sum(v) > 0) v / sum(v) * 100 else 0) # row %
long$share <- ave(long$n, long$category, FUN = function(v) if (sum(v) > 0) v / sum(v) else 0)
long$category <- factor(long$category, levels = rev(levels(long$category))) # first category on top
fill <- setNames(rep(cs_cat, length.out = nlevels(long$group)), levels(long$group))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6"
p <- ggplot(long, aes(x = value, y = category, fill = group)) +
geom_col(position = position_stack(reverse = TRUE), width = 0.7) + # first level at the baseline
geom_text(aes(label = ifelse(share >= 0.06, sprintf("%.0f%%", value), "")),
position = position_stack(vjust = 0.5, reverse = TRUE), colour = "white", size = 2.5) +
scale_fill_manual(values = fill, name = "priority") +
labs(x = "% of category", y = "team") +
theme_cs
print(p)
Needs ggplot2 · reads bar-stacked-demo.csv · app theme from the optional codesplashr helper
-- Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")-- controls: mode=percent, orientation=horizontal, top=10, labels=true-- category × stack-level counts with row shares; levels beyond the caps pool into 'Other'
WITH
la AS (
SELECT "team"::VARCHAR AS level, row_number() OVER (ORDER BY count(*) DESC, "team"::VARCHAR) AS rk
FROM read_csv('bar-stacked-demo.csv') WHERE "team" IS NOT NULL GROUP BY 1
),
lb(level, rk) AS (VALUES ('Critical', 1), ('High', 2), ('Medium', 3), ('Low', 4)),
t AS (
SELECT CASE WHEN la.rk <= 10 THEN la.level ELSE 'Other' END AS a,
CASE WHEN lb.rk <= 6 THEN lb.level ELSE 'Other' END AS b,
count(*) AS n, min(la.rk) AS ra, min(lb.rk) AS rb
FROM read_csv('bar-stacked-demo.csv') s
JOIN la ON la.level = s."team"::VARCHAR
JOIN lb ON lb.level = s."priority"::VARCHAR
GROUP BY 1, 2
)
SELECT a AS "team", b AS "priority", n,
n / sum(n) OVER (PARTITION BY a) AS row_share
FROM t
ORDER BY ra, rb;
Read top down: categories are ranked by the aggregate.
Check the labels for the exact values.
Check which aggregate is shown: a total favours big categories, a mean does not.
1Callout 1: The leader on this aggregate.
2Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = px.bar(agg, x="value", y="product", orientation="h", color_discrete_sequence=[PALETTE[0]], text_auto=",.0f")
fig.update_layout(xaxis_title="Sum of revenue", yaxis_title="product", yaxis_autorange="reversed", xaxis_rangemode="tozero")
fig.show()
Needs pandas, numpy, plotly · reads bar-ranked-demo.csv · app theme from the optional codesplash helper
# Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")# controls: stat=sum, top=12, order=desc, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("bar-ranked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["product"]] <- factor(df[["product"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["product"]])
val <- df[["revenue"]]
ok <- !is.na(cat) & !is.na(val)
agg <- tapply(val[ok], cat[ok], sum)
r <- data.frame(level = names(agg), value = as.numeric(agg))
r <- r[is.finite(r$value), ]
r <- head(r[order(-r$value, r$level), ], 12) # ties alphabetical
r$level <- factor(r$level, levels = rev(r$level)) # first ranked on top
p <- ggplot(r, aes(value, level)) +
geom_col(fill = cs_cat[1], width = 0.7) +
geom_text(aes(label = prettyNum(signif(value, 4), big.mark = ",")), hjust = -0.1, size = 2.8) +
geom_vline(xintercept = 0, linewidth = 0.3) +
scale_x_continuous(expand = expansion(mult = c(0, 0.12))) +
labs(x = "Sum of revenue", y = "product") +
theme_cs
print(p)
Needs ggplot2 · reads bar-ranked-demo.csv · app theme from the optional codesplashr helper
-- Ranked bars — Codesplash Chart Lab (recipe "bar-ranked")-- controls: stat=sum, top=12, order=desc, labels=true-- Sum of revenue per category, ranked (ties alphabetical), top 12
SELECT "product"::VARCHAR AS level, sum("revenue") AS value, count(*) AS n
FROM read_csv('bar-ranked-demo.csv')
WHERE "product" IS NOT NULL AND "revenue" IS NOT NULL
GROUP BY 1
ORDER BY value DESC, level
LIMIT 12;
Needs ggplot2 · reads lollipop-demo.csv · app theme from the optional codesplashr helper
-- Lollipop chart — Codesplash Chart Lab (recipe "lollipop")-- controls: stat=mean, top=14, order=desc, labels=true-- Mean revenue per category, ranked (ties alphabetical), top 14
SELECT "product"::VARCHAR AS level, avg("revenue") AS value, count(*) AS n
FROM read_csv('lollipop-demo.csv')
WHERE "product" IS NOT NULL AND "revenue" IS NOT NULL
GROUP BY 1
ORDER BY value DESC, level
LIMIT 14;
Compare the dots in a row to see how the groups differ inside one category.
Read the line joining them as the size of that gap.
Read the column of dots down the rows for how one group changes across categories.
1Callout 1: One dot per group in this row.
2Callout 2: The line joining dots: the gap between groups.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for level, row in cells.iterrows(): # thin segment spanning the group values
fig.add_shape(type="line", x0=row.min(), x1=row.max(), y0=level, y1=level, line=dict(color="#9aa0a6", width=3), layer="below")
for j, grp in enumerate(groups):
fig.add_scatter(x=cells[grp], y=cells.index, mode="markers", name=grp, marker=dict(color=PALETTE[j], size=11))
fig.update_layout(xaxis_title="Mean life_expectancy", yaxis_title="country", yaxis_autorange="reversed", legend_title_text="sex")
fig.show()
Needs pandas, numpy, plotly · reads cleveland-dot-demo.csv · app theme from the optional codesplash helper
# Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")# controls: stat=mean, top=12, sort=value
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cleveland-dot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["country"]] <- factor(df[["country"]])
df[["sex"]] <- factor(df[["sex"]], levels = c("Female", "Male"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["country"]])
val <- df[["life_expectancy"]]
ok <- !is.na(cat) & !is.na(val)
overall <- tapply(val[ok], cat[ok], mean) # the aggregate over all rows orders the rows
r <- data.frame(level = names(overall), overall = as.numeric(overall))
r <- r[is.finite(r$overall), ]
r <- head(r[order(-r$overall, r$level), ], 12) # ties alphabetical
groups <- head(levels(df[["sex"]]), 3) # first three group levels (dictionary order, else frequency)
grp <- as.character(df[["sex"]])
ok <- ok & !is.na(grp) & grp %in% groups
cells <- aggregate(list(value = val[ok]), list(level = cat[ok], group = grp[ok]), mean)
cells <- cells[cells$level %in% r$level, ]
cells$level <- factor(cells$level, levels = rev(r$level)) # first row on top
cells$group <- factor(cells$group, levels = groups)
span <- aggregate(value ~ level, cells, function(v) c(lo = min(v), hi = max(v)))
span <- data.frame(level = span$level, lo = span$value[, "lo"], hi = span$value[, "hi"])
p <- ggplot(cells, aes(value, level)) +
geom_segment(data = span, aes(x = lo, xend = hi, y = level, yend = level), colour = "#9aa0a6", linewidth = 1) +
geom_point(aes(colour = group), size = 3) +
scale_colour_manual(values = cs_cat, name = "sex") +
labs(x = "Mean life_expectancy", y = "country") + # no zero baseline: dots are read by position
theme_cs
print(p)
Needs ggplot2 · reads cleveland-dot-demo.csv · app theme from the optional codesplashr helper
-- Cleveland dot plot — Codesplash Chart Lab (recipe "cleveland-dot")-- controls: stat=mean, top=12, sort=value-- Mean life_expectancy per category (overall and per group); rows sorted by the overall aggregate
SELECT "country"::VARCHAR AS level,
"sex"::VARCHAR AS grp,
avg("life_expectancy") AS value, count(*) AS n
FROM read_csv('cleveland-dot-demo.csv')
WHERE "country" IS NOT NULL AND "life_expectancy" IS NOT NULL
GROUP BY GROUPING SETS ((level), (level, grp))
ORDER BY grp NULLS FIRST, value DESC, level;
Read the bar's length as the size of the change and the label as its value.
Rows are sorted by change, so the biggest movers are together.
1Callout 1: The later value.
2Callout 2: The earlier value; the bar between them is the change.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for row in w.itertuples():
fig.add_shape(type="line", x0=row.start, x1=row.end, y0=row.level, y1=row.level, line=dict(color="#ced1d6", width=6), layer="below")
fig.add_scatter(x=w["start"], y=w["level"], mode="markers", name=periods[0], marker=dict(color="#9aa0a6", size=12))
fig.add_scatter(x=w["end"], y=w["level"], mode="markers+text", name=periods[1], marker=dict(color=PALETTE[0], size=12),
text=[f"{g:+.3g}" for g in w["gap"]], textposition="middle right")
fig.update_layout(xaxis_title="Mean engagement", yaxis_title="department", yaxis_autorange="reversed")
fig.show()
Needs pandas, numpy, plotly · reads dumbbell-demo.csv · app theme from the optional codesplash helper
# Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")# controls: stat=mean, sort=gap, top=12, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("dumbbell-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["department"]] <- factor(df[["department"]])
df[["year"]] <- factor(df[["year"]], levels = c("2025", "2026"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
periods <- head(levels(df[["year"]]), 2) # from → to: the first two period levels
cat <- as.character(df[["department"]])
per <- as.character(df[["year"]])
val <- df[["engagement"]]
ok <- !is.na(cat) & !is.na(val) & per %in% periods
a <- tapply(val[ok & per == periods[1]], cat[ok & per == periods[1]], mean)
b <- tapply(val[ok & per == periods[2]], cat[ok & per == periods[2]], mean)
both <- intersect(names(a), names(b)) # categories missing either period are dropped
w <- data.frame(level = both, from = as.numeric(a[both]), to = as.numeric(b[both]))
w$gap <- w$to - w$from
w <- head(w[order(-w$gap, w$level), ], 12) # biggest movers on top
w$level <- factor(w$level, levels = rev(w$level))
pts <- rbind(data.frame(level = w$level, value = w$from, period = periods[1]),
data.frame(level = w$level, value = w$to, period = periods[2]))
pts$period <- factor(pts$period, levels = periods)
p <- ggplot(w) +
geom_segment(aes(x = from, xend = to, y = level, yend = level), colour = "#ced1d6", linewidth = 2.2) +
geom_point(data = pts, aes(value, level, colour = period), size = 3) +
geom_text(aes(x = pmax(from, to), y = level, label = sprintf("%+.3g", gap)), hjust = -0.3, size = 2.8) +
scale_colour_manual(values = setNames(c("#9aa0a6", cs_cat[1]), periods), name = NULL) +
scale_x_continuous(expand = expansion(mult = c(0.05, 0.12))) +
labs(x = "Mean engagement", y = "department") +
theme_cs
print(p)
Needs ggplot2 · reads dumbbell-demo.csv · app theme from the optional codesplashr helper
-- Dumbbell chart — Codesplash Chart Lab (recipe "dumbbell")-- controls: stat=mean, sort=gap, top=12, labels=true-- Mean engagement per category for the first two period levels (from → to)
WITH
p(level, rk) AS (VALUES ('2025', 1), ('2026', 2)),
cells AS (
SELECT s."department"::VARCHAR AS level, p.rk, avg(s."engagement") AS value
FROM read_csv('dumbbell-demo.csv') s JOIN p ON p.level = s."year"::VARCHAR
WHERE p.rk <= 2 AND s."department" IS NOT NULL AND s."engagement" IS NOT NULL
GROUP BY 1, 2
)
SELECT level,
max(value) FILTER (WHERE rk = 1) AS "from",
max(value) FILTER (WHERE rk = 2) AS "to",
"to" - "from" AS gap
FROM cells
GROUP BY level
HAVING count(*) = 2
ORDER BY gap DESC, level;
Follow each line from left to right: up means it rose.
Check where lines cross: the ranking changed there.
Read the labels at both ends for the values.
1Callout 1: A steep rising line: a big gain.
2Callout 2: Coloured lines: the biggest movers.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])]
fig = go.Figure()
for row in w.itertuples():
fig.add_scatter(x=periods, y=[row.start, row.end], mode="lines+markers+text", line=dict(color=row.color, width=3 if row.color != "#9aa0a6" else 1.5),
text=[f"{row.level} {row.start:,.4g}", f"{row.end:,.4g} {row.level}"], textposition=["middle left", "middle right"], showlegend=False)
fig.update_layout(yaxis_title="Sum of units_k", xaxis=dict(type="category", range=[-0.8, 1.8]))
fig.show()
Needs pandas, numpy, plotly · reads slope-demo.csv · app theme from the optional codesplash helper
# Slope chart — Codesplash Chart Lab (recipe "slope")# controls: stat=sum, color=emphasis, emphasis=3, top=8
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("slope-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["brand"]] <- factor(df[["brand"]])
df[["year"]] <- factor(df[["year"]], levels = c("2024", "2026"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
periods <- head(levels(df[["year"]]), 2) # from → to: the first two period levels
cat <- as.character(df[["brand"]])
per <- as.character(df[["year"]])
val <- df[["units_k"]]
ok <- !is.na(cat) & !is.na(val) & per %in% periods
a <- tapply(val[ok & per == periods[1]], cat[ok & per == periods[1]], sum)
b <- tapply(val[ok & per == periods[2]], cat[ok & per == periods[2]], sum)
both <- intersect(names(a), names(b)) # categories missing either period are dropped
w <- data.frame(level = both, from = as.numeric(a[both]), to = as.numeric(b[both]))
w$gap <- w$to - w$from
w <- head(w[order(-w$to), ], 8) # top N by the second period
movers <- w$level[order(-abs(w$gap))][seq_len(min(3, nrow(w)))] # largest |change|
w$color <- ifelse(w$level %in% movers, ifelse(w$gap >= 0, cs_cat[1], "#ce5342"), "#9aa0a6")
nudge <- function(ys, gap) {
# spread label positions so neighbours are at least `gap` apart (lines keep their true ends)
o <- order(ys)
out <- ys
for (k in seq_along(o)[-1]) out[o[k]] <- max(out[o[k]], out[o[k - 1]] + gap)
out
}
gap <- 0.035 * diff(range(c(w$from, w$to)))
w$from_label <- nudge(w$from, gap)
w$to_label <- nudge(w$to, gap)
p <- ggplot(w) +
geom_segment(aes(x = 1, xend = 2, y = from, yend = to, colour = color), linewidth = 1) +
geom_point(aes(x = 1, y = from, colour = color), size = 2) +
geom_point(aes(x = 2, y = to, colour = color), size = 2) +
geom_text(aes(x = 0.95, y = from_label, label = paste(level, prettyNum(signif(from, 4), big.mark = ",")), colour = color), hjust = 1, size = 2.8) +
geom_text(aes(x = 2.05, y = to_label, label = paste(prettyNum(signif(to, 4), big.mark = ","), level), colour = color), hjust = 0, size = 2.8) +
scale_colour_identity() +
scale_x_continuous(breaks = 1:2, labels = periods, limits = c(0.3, 2.7)) +
labs(x = NULL, y = "Sum of units_k") +
theme_cs
print(p)
Needs ggplot2 · reads slope-demo.csv · app theme from the optional codesplashr helper
-- Slope chart — Codesplash Chart Lab (recipe "slope")-- controls: stat=sum, color=emphasis, emphasis=3, top=8-- Sum of units_k per category for the first two period levels (from → to)
WITH
p(level, rk) AS (VALUES ('2024', 1), ('2026', 2)),
cells AS (
SELECT s."brand"::VARCHAR AS level, p.rk, sum(s."units_k") AS value
FROM read_csv('slope-demo.csv') s JOIN p ON p.level = s."year"::VARCHAR
WHERE p.rk <= 2 AND s."brand" IS NOT NULL AND s."units_k" IS NOT NULL
GROUP BY 1, 2
)
SELECT level,
max(value) FILTER (WHERE rk = 1) AS "from",
max(value) FILTER (WHERE rk = 2) AS "to",
"to" - "from" AS gap
FROM cells
GROUP BY level
HAVING count(*) = 2
ORDER BY gap DESC, level;
The centre of the chart is neutral: disagreement grows to the left, agreement to the right.
Compare how far each bar reaches on each side.
Read the order: items are ranked by net agreement.
1Callout 1: Centre: the neutral responses straddle zero.
2Callout 2: Right side: the share who agree.
3Callout 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
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")# controls: sort=net, labels=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
left = start.reindex(order)
for j, lvl in enumerate(LEVELS):
w = shares.loc[order, lvl]
fig.add_bar(y=order, x=w, base=left, orientation="h", name=lvl, marker_color=COLORS[j],
text=[f"{v:.0f}" if v >= 6 else "" for v in w], textposition="inside")
left = left + w
fig.update_layout(barmode="overlay", yaxis_autorange="reversed", xaxis_title="Share of responses (%)", legend_orientation="h")
fig.add_vline(x=0, line_width=1)
fig.show()
Needs pandas, numpy, plotly · reads likert-demo.csv · app theme from the optional codesplash helper
# Likert diverging bars — Codesplash Chart Lab (recipe "likert")# controls: sort=net, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("likert-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["Meaningful work"]] <- factor(df[["Meaningful work"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Clear goals"]] <- factor(df[["Clear goals"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Manager support"]] <- factor(df[["Manager support"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Fair pay"]] <- factor(df[["Fair pay"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Work–life balance"]] <- factor(df[["Work–life balance"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
df[["Growth opportunities"]] <- factor(df[["Growth opportunities"]], levels = c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
items <- c("Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities")
LEVELS <- c("Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree") # response order from the data dictionary
COLORS <- c("#c95443", "#da8477", "#ced1d6", "#6691ca", "#2a69b5") # disagree … neutral … agree
k <- length(LEVELS)
mid <- (k - 1) / 2 # with an odd number of levels the middle one is neutral
shares <- t(sapply(items, function(it) {
v <- as.character(df[[it]])
v <- v[!is.na(v) & v %in% LEVELS]
100 * as.numeric(table(factor(v, levels = LEVELS))) / max(length(v), 1) # % of non-missing responses
}))
colnames(shares) <- LEVELS
j <- seq_len(k) - 1
neg <- rowSums(shares[, j < mid, drop = FALSE])
pos <- rowSums(shares[, j > mid, drop = FALSE])
neutral <- rowSums(shares[, j == mid, drop = FALSE])
net <- pos - neg # net agreement
start <- -(neg + neutral / 2) # half the neutral share on each side of zero
ord <- items[order(-net)] # by net agreement
segs <- do.call(rbind, lapply(items, function(it) {
x0 <- start[[it]] + c(0, cumsum(shares[it, ])[-k])
data.frame(item = it, level = factor(LEVELS, levels = LEVELS), xmin = x0, xmax = x0 + shares[it, ])
}))
segs$y <- match(segs$item, rev(ord)) # first item on top
p <- ggplot(segs) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = y - 0.35, ymax = y + 0.35, fill = level)) +
geom_text(aes(x = (xmin + xmax) / 2, y = y, label = ifelse(xmax - xmin >= 6, round(xmax - xmin), "")), size = 2.5) +
geom_vline(xintercept = 0, linewidth = 0.4) +
scale_fill_manual(values = setNames(COLORS, LEVELS), name = NULL) +
scale_y_continuous(breaks = seq_along(ord), labels = rev(ord)) +
scale_x_continuous(labels = function(v) paste0(abs(v), "%")) +
labs(x = "Share of responses, centred on neutral (disagree left, agree right)", y = NULL) +
theme_cs +
theme(legend.position = "bottom")
print(p)
Needs ggplot2 · reads likert-demo.csv · app theme from the optional codesplashr helper
-- Likert diverging bars — Codesplash Chart Lab (recipe "likert")-- controls: sort=net, labels=true-- response shares per item over non-missing responses on the declared scale
WITH long AS (
UNPIVOT (SELECT "Meaningful work"::VARCHAR AS "Meaningful work", "Clear goals"::VARCHAR AS "Clear goals", "Manager support"::VARCHAR AS "Manager support", "Fair pay"::VARCHAR AS "Fair pay", "Work–life balance"::VARCHAR AS "Work–life balance", "Growth opportunities"::VARCHAR AS "Growth opportunities" FROM read_csv('likert-demo.csv'))
ON "Meaningful work", "Clear goals", "Manager support", "Fair pay", "Work–life balance", "Growth opportunities"
INTO NAME item VALUE response
),
scale(response, j) AS (VALUES ('Strongly disagree', 0), ('Disagree', 1), ('Neutral', 2), ('Agree', 3), ('Strongly agree', 4))
SELECT item, response, j, count(*) AS n,
count(*) / sum(count(*)) OVER (PARTITION BY item) AS share
FROM long JOIN scale USING (response)
GROUP BY item, response, j
ORDER BY item, j;
Read the bars left to right: categories are sorted by size.
Follow the line for the running share of the total.
Where the line crosses the reference: everything left of it is the vital few.
1Callout 1: The largest category.
2Callout 2: The running total crosses the reference here.
3Callout 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
# Pareto chart — Codesplash Chart Lab (recipe "pareto")# controls: top=10, threshold=80, cumLabels=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])]
from plotly.subplots import make_subplots
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_bar(x=r["defect"], y=r["value"], marker_color=colors, name="Count")
fig.add_scatter(x=r["defect"], y=r["cumulative"] * 100, mode="lines+markers", name="Cumulative %",
line_color=PALETTE[1], text=[f"{v:.0%}" for v in r["cumulative"]], textposition="top center", secondary_y=True)
fig.add_hline(y=THRESHOLD * 100, line_dash="dash", line_color=PALETTE[1], secondary_y=True)
fig.update_yaxes(title_text="Count", secondary_y=False)
fig.update_yaxes(title_text="Cumulative %", range=[0, 105], secondary_y=True)
fig.update_layout(xaxis_title="defect", showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads pareto-demo.csv · app theme from the optional codesplash helper
# Pareto chart — Codesplash Chart Lab (recipe "pareto")# controls: top=10, threshold=80, cumLabels=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pareto-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["defect"]] <- factor(df[["defect"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["defect"]])
val <- rep(1, length(cat)) # no value column: count rows
ok <- !is.na(cat) & !is.na(val)
sums <- tapply(val[ok], cat[ok], sum)
sums <- sums[sums > 0] # non-positive totals are not meaningful in a Pareto chart
r <- data.frame(level = names(sums), value = as.numeric(sums))
r <- r[order(-r$value, r$level), ] # ties alphabetical
r$share <- r$value / sum(r$value)
r$cumulative <- cumsum(r$share)
if (nrow(r) > 10) { # pool the rest into "Other", kept last
rest <- r[-seq_len(10), ]
r <- rbind(r[seq_len(10), ], data.frame(level = "Other", value = sum(rest$value), share = sum(rest$share), cumulative = 1))
}
threshold <- 0.8
vital <- which(r$cumulative >= threshold - 1e-12)[1] # bars up to the crossing are the vital few
r$kind <- ifelse(r$level == "Other", "other", ifelse(seq_len(nrow(r)) <= vital, "vital", "rest"))
r$level <- factor(r$level, levels = r$level)
ymax <- max(r$value)
p <- ggplot(r, aes(level, value)) +
geom_col(aes(fill = kind), show.legend = FALSE) +
scale_fill_manual(values = c(vital = cs_cat[1], rest = grDevices::adjustcolor(cs_cat[1], 0.45), other = "#9aa0a6")) +
geom_line(aes(y = cumulative * ymax, group = 1), colour = cs_cat[2], linewidth = 0.9) +
geom_point(aes(y = cumulative * ymax), colour = cs_cat[2], size = 1.8) +
geom_hline(yintercept = threshold * ymax, colour = cs_cat[2], linetype = "dashed") +
scale_y_continuous("Count", sec.axis = sec_axis(~ . / ymax * 100, name = "Cumulative %")) +
labs(x = "defect") +
theme_cs +
theme(axis.text.x = element_text(angle = 35, hjust = 1))
print(p)
Needs ggplot2 · reads pareto-demo.csv · app theme from the optional codesplashr helper
-- Pareto chart — Codesplash Chart Lab (recipe "pareto")-- controls: top=10, threshold=80, cumLabels=false-- per-category totals sorted descending (ties alphabetical) with cumulative share; beyond 10 pooled into 'Other'
WITH sums AS (
SELECT "defect"::VARCHAR AS level, count(*) AS value
FROM read_csv('pareto-demo.csv')
WHERE "defect" IS NOT NULL
GROUP BY 1
HAVING value > 0
),
ranked AS (SELECT *, row_number() OVER (ORDER BY value DESC, level) AS rk FROM sums),
pooled AS (
SELECT CASE WHEN rk <= 10 THEN level ELSE 'Other' END AS level, sum(value) AS value, min(rk) AS rk
FROM ranked GROUP BY 1
)
SELECT level, value,
value / sum(value) OVER () AS share,
sum(value) OVER (ORDER BY rk) / sum(value) OVER () AS cumulative
FROM pooled
ORDER BY rk;
Read column width as the size of each column level.
Read the heights inside a column as the row shares for that level.
Use the colours: strong shades mark cells far from what independence predicts.
1Callout 1: A strongly shaded cell: many more rows than independence predicts.
2Callout 2: Same column, lower row: fewer than predicted.
3Callout 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).
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
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")# controls: shading=pearson, labels=true, top=8
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
fig = go.Figure()
for j, level in enumerate(tab.columns):
sel = [t for t in tiles if t[1] == j]
fig.add_bar(
x=[t[2] + t[4] / 2 for t in sel], width=[t[4] for t in sel],
y=[t[5] for t in sel], base=[1 - t[3] - t[5] for t in sel],
marker_color=[shade(resid[t[0], j]) for t in sel], marker_line=dict(color="white", width=0.5),
name=str(level), text=[f"{o[t[0], j] / rt[t[0]]:.0%}" for t in sel], textposition="inside", showlegend=False,
customdata=[resid[t[0], j] for t in sel], hovertemplate=f"{level}<br>residual %{{customdata:.2f}}<extra></extra>")
fig.update_layout(barmode="overlay", bargap=0, title=f"χ²({dof}) = {chi2:.1f}",
xaxis=dict(tickvals=list(lefts + widths / 2), ticktext=list(tab.index), title="class", range=[0, 1]),
yaxis=dict(range=[0, 1], title="outcome", showticklabels=False))
fig.show()
Needs pandas, numpy, plotly · reads mosaic-demo.csv · app theme from the optional codesplash helper
# Mosaic plot — Codesplash Chart Lab (recipe "mosaic")# controls: shading=pearson, labels=true, top=8
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mosaic-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["class"]] <- factor(df[["class"]], levels = c("1st", "2nd", "3rd", "Crew"))
df[["outcome"]] <- factor(df[["outcome"]], levels = c("Survived", "Died"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
crosstab <- function(a, b, la, lb, max_a, max_b) {
# a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last
ok <- !is.na(a) & !is.na(b)
pool <- function(v, lv, cap) {
keep <- head(lv, cap)
v <- as.character(v)
factor(ifelse(v %in% keep, v, "Other"), levels = c(keep, if (length(lv) > cap) "Other"))
}
table(category = pool(a[ok], la, max_a), group = pool(b[ok], lb, max_b))
}
tab <- crosstab(df[["class"]], df[["outcome"]], levels(df[["class"]]), levels(df[["outcome"]]), 8, 6)
o <- unclass(tab)
n <- sum(o); rt <- rowSums(o); ct <- colSums(o)
e <- outer(rt, ct) / n # expected counts under independence
resid <- ifelse(e > 0, (o - e) / sqrt(e), 0) # chisq.test()$residuals
chi2 <- sum(ifelse(e > 0, (o - e)^2 / e, 0)) # Pearson χ², no continuity correction
dof <- max(0, (sum(rt > 0) - 1) * (sum(ct > 0) - 1))
SHADES <- c("#c13e2e", "#df9489", "#f3f5f8", "#799fd1", "#0859ac")
CLASSES <- c("r ≤ −4", "−4 < r ≤ −2", "|r| < 2", "2 ≤ r < 4", "r ≥ 4") # vcd cut-offs
gap <- 0.012
widths <- rt / n * (1 - gap * (length(rt) - 1)) # column widths ∝ the column variable's margins
lefts <- c(0, cumsum(widths + gap))[seq_along(rt)]
tiles <- do.call(rbind, lapply(seq_along(rt), function(i) {
h <- if (rt[i] > 0) o[i, ] / rt[i] * (1 - gap * (length(ct) - 1)) else rep(0, length(ct))
top <- c(0, cumsum(h + gap))[seq_along(ct)] # heights ∝ the share within the column
r <- resid[i, ]
cls <- 3 + sign(r) * ifelse(abs(r) >= 4, 2, ifelse(abs(r) >= 2, 1, 0))
data.frame(col = names(rt)[i], row = colnames(o), xmin = lefts[i], xmax = lefts[i] + widths[i],
ymin = 1 - top - h, ymax = 1 - top, share = if (rt[i] > 0) o[i, ] / rt[i] else 0,
class = factor(CLASSES[cls], levels = CLASSES))
}))
tiles$row <- factor(tiles$row, levels = colnames(o))
marg <- ct / n # row-level labels at the marginal shares (spine-plot convention)
p <- ggplot(tiles) +
geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = class), colour = "white", linewidth = 0.3) +
geom_text(aes(x = (xmin + xmax) / 2, y = (ymin + ymax) / 2, label = ifelse(xmax - xmin > 0.05 & ymax - ymin > 0.05, sprintf("%.0f%%", 100 * share), "")), size = 2.5) +
scale_fill_manual(values = setNames(SHADES, CLASSES), drop = FALSE, name = sprintf("χ²(%d) = %.1f", dof, chi2)) +
scale_x_continuous(breaks = lefts + widths / 2, labels = names(rt), expand = c(0, 0)) +
scale_y_continuous(breaks = 1 - (cumsum(marg) - marg / 2), labels = names(ct), expand = c(0, 0)) +
labs(x = "class", y = "outcome") +
theme_cs +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads mosaic-demo.csv · app theme from the optional codesplashr helper
-- Mosaic plot — Codesplash Chart Lab (recipe "mosaic")-- controls: shading=pearson, labels=true, top=8-- contingency table with expected counts and Pearson / standardized residuals (R chisq.test conventions)
WITH
la(level, rk) AS (VALUES ('1st', 1), ('2nd', 2), ('3rd', 3), ('Crew', 4)),
lb(level, rk) AS (VALUES ('Survived', 1), ('Died', 2)),
t AS (
SELECT CASE WHEN la.rk <= 8 THEN la.level ELSE 'Other' END AS a,
CASE WHEN lb.rk <= 6 THEN lb.level ELSE 'Other' END AS b,
count(*) AS n, min(la.rk) AS ra, min(lb.rk) AS rb
FROM read_csv('mosaic-demo.csv') s
JOIN la ON la.level = s."class"::VARCHAR
JOIN lb ON lb.level = s."outcome"::VARCHAR
GROUP BY 1, 2
),
m AS (
SELECT a, b, n, ra, rb,
sum(n) OVER (PARTITION BY a) AS row_total,
sum(n) OVER (PARTITION BY b) AS col_total,
sum(n) OVER () AS total
FROM t
)
SELECT a AS "class", b AS "outcome", n,
row_total * col_total / total AS expected,
(n - row_total * col_total / total) / sqrt(row_total * col_total / total) AS pearson_residual,
(n - row_total * col_total / total)
/ sqrt(row_total * col_total / total * (1 - row_total / total) * (1 - col_total / total)) AS std_residual,
n / row_total AS share_within_column
FROM m
ORDER BY ra, rb;
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
# Waffle chart — Codesplash Chart Lab (recipe "waffle")# controls: top=6, percents=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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()]
fig = go.Figure()
for i, lab in enumerate(labels):
ks = np.flatnonzero(owner == i)
# one 0.9 × 0.9 bar per square, so the squares can carry the level's texture (as in the app)
fig.add_bar(x=ks % 10, y=np.full(ks.size, 0.9), base=9 - ks // 10 - 0.45, width=0.9, name=lab,
marker=dict(color=colors[i], line_width=0, pattern=dict(shape=hatches[i], fgcolor=HATCH_INK, fillmode="overlay")))
fig.update_layout(barmode="overlay", xaxis=dict(visible=False, range=[-0.6, 9.6]), yaxis=dict(visible=False, range=[-0.6, 9.6], scaleanchor="x"))
fig.show()
Needs pandas, numpy, plotly · reads waffle-demo.csv · app theme from the optional codesplash helper
# Waffle chart — Codesplash Chart Lab (recipe "waffle")# controls: top=6, percents=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("waffle-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["heating"]] <- factor(df[["heating"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
freq_levels <- function(v) {
# the app's order when the data dictionary declares none: by descending frequency, ties alphabetical
t <- table(as.character(v[!is.na(v)]))
names(t)[order(-as.numeric(t), names(t))]
}
hamilton <- function(values, cells = 100) {
# largest-remainder (Hamilton) allocation: cells always total `cells`; ties go to the earlier level
exact <- values / sum(values) * cells
out <- floor(exact)
rest <- order(-(exact - floor(exact)), seq_along(exact))
add <- head(rest, cells - sum(out))
out[add] <- out[add] + 1
out
}
keep <- head(freq_levels(df[["heating"]]), 6)
v <- as.character(df[["heating"]])
v <- v[!is.na(v)]
v <- ifelse(v %in% keep, v, "Other")
lv <- c(keep, if (any(v == "Other")) "Other")
counts <- as.numeric(table(factor(v, levels = lv)))
cells <- hamilton(counts) # each of the 100 squares is 1 % of non-missing rows
labels <- sprintf("%s %.1f%%", lv, 100 * counts / sum(counts))
grid <- data.frame(k = 0:99, who = factor(rep(labels, cells), levels = labels))
grid$row <- grid$k %/% 10 # squares fill row by row from the top left
grid$col <- grid$k %% 10
fill <- setNames(rep(cs_cat, length.out = length(lv)), labels)
fill[lv == "Other"] <- "#9aa0a6"
fill <- setNames(cs_textures(unname(fill), idx = ifelse(lv == "Other", 8, seq_along(lv))), labels) # texture per level, as in the app
p <- ggplot(grid, aes(col, row, fill = who)) +
geom_tile(width = 0.9, height = 0.9) +
scale_y_reverse() +
scale_fill_manual(values = fill, name = NULL) +
coord_equal() +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads waffle-demo.csv · app theme from the optional codesplashr helper
-- Waffle chart — Codesplash Chart Lab (recipe "waffle")-- controls: top=6, percents=true-- per-level counts (top 6 + 'Other') and their 100 waffle squares by the largest-remainder method
WITH
lv AS (
SELECT "heating"::VARCHAR AS level, row_number() OVER (ORDER BY count(*) DESC, "heating"::VARCHAR) AS rk
FROM read_csv('waffle-demo.csv') WHERE "heating" IS NOT NULL GROUP BY 1
),
counts AS (
SELECT CASE WHEN lv.rk <= 6 THEN lv.level ELSE 'Other' END AS level, count(*) AS n, min(lv.rk) AS rk
FROM read_csv('waffle-demo.csv') s JOIN lv ON lv.level = s."heating"::VARCHAR
GROUP BY 1
),
exact AS (SELECT *, n * 100.0 / sum(n) OVER () AS exact FROM counts),
alloc AS (
SELECT *, floor(exact)::INTEGER AS base,
row_number() OVER (ORDER BY exact - floor(exact) DESC, rk) AS rem_rank,
100 - sum(floor(exact)::INTEGER) OVER () AS leftover
FROM exact
)
SELECT level, n, n / sum(n) OVER () AS share,
base + CASE WHEN rem_rank <= leftover THEN 1 ELSE 0 END AS squares
FROM alloc
ORDER BY rk;
Check the raw points behind them for how varied individuals are.
1Callout 1: The dot: the group mean. The bar: its interval.
2Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
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
fig.add_scatter(x=i + jitter, y=v, mode="markers", marker=dict(color="#9aa0a6", size=4, opacity=0.5), showlegend=False)
fig.add_scatter(x=np.arange(len(s)), y=s["mean"], mode="markers", marker=dict(color=PALETTE[0], size=11),
error_y=dict(type="data", array=s["half"], thickness=2, width=6), name="mean", showlegend=False)
fig.update_layout(xaxis=dict(tickvals=list(range(len(s))), ticktext=list(s.index), title="condition"), yaxis_title=LABEL)
fig.show()
Needs pandas, numpy, plotly, scipy · reads point-range-demo.csv · app theme from the optional codesplash helper
# Point-range (mean ± CI) — Codesplash Chart Lab (recipe "point-range")# controls: interval=ci, level=0.95, points=true, sort=data
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("point-range-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["condition"]] <- factor(df[["condition"]], levels = c("Baseline", "Caffeine", "Sleep-deprived", "Music", "Dual task"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
d <- data.frame(y = df[["reaction_ms"]], g = as.character(df[["condition"]]))
d <- d[!is.na(d$y) & !is.na(d$g), ]
ord <- intersect(levels(df[["condition"]]), d$g) # dictionary order
s <- data.frame(g = ord,
n = as.numeric(tapply(d$y, d$g, length)[ord]),
mean = as.numeric(tapply(d$y, d$g, mean)[ord]),
sd = as.numeric(tapply(d$y, d$g, sd)[ord])) # sd uses n − 1
s$se <- s$sd / sqrt(s$n)
s$half <- qt(1 - (1 - 0.95) / 2, s$n - 1) * s$se # t interval per group, as t.test(x)$conf.int
s$half[is.na(s$half)] <- 0 # n < 2: the interval collapses to the mean
s <- head(s, 15)
s$g <- factor(s$g, levels = s$g)
d <- d[d$g %in% levels(s$g), ]
d$g <- factor(d$g, levels = levels(s$g))
d$jitter <- ave(seq_along(d$y), d$g, FUN = function(i) ((seq_along(i) * 0.618034) %% 1 - 0.5) * 0.36) # deterministic jitter
p <- ggplot(s, aes(as.numeric(g), mean)) + # numeric x so the jittered points share the axis
geom_point(data = d, aes(as.numeric(g) + jitter, y), colour = "#9aa0a6", alpha = 0.5, size = 0.8) +
geom_errorbar(aes(ymin = mean - half, ymax = mean + half), colour = cs_cat[1], width = 0.12, linewidth = 0.8) +
geom_point(colour = cs_cat[1], size = 3) +
scale_x_continuous(breaks = seq_len(nrow(s)), labels = levels(s$g)) +
labs(x = "condition", y = "reaction_ms (mean ± 95 % CI)") +
theme_cs
print(p)
Needs ggplot2 · reads point-range-demo.csv · app theme from the optional codesplashr helper
-- Point-range (mean ± CI) — Codesplash Chart Lab (recipe "point-range")-- controls: interval=ci, level=0.95, points=true, sort=data-- per-group n, mean, SD (n − 1) and SE; CI half-width = t(1 − α/2, n − 1) · se (DuckDB has no t quantile —-- multiply in Python/R, e.g. scipy.stats.t.ppf or qt)
SELECT "condition"::VARCHAR AS grp, count(*) AS n, avg("reaction_ms") AS mean, stddev_samp("reaction_ms") AS sd,
stddev_samp("reaction_ms") / sqrt(count(*)) AS se
FROM read_csv('point-range-demo.csv')
WHERE "condition" IS NOT NULL AND "reaction_ms" IS NOT NULL
GROUP BY 1
ORDER BY grp;
Follow each line: it shows the mean across one factor at one level of the other.
Parallel lines: the first factor's effect is the same at both levels.
Non-parallel or crossing lines: the effect depends on the other factor.
1Callout 1: The lines spread apart here: the factors interact.
2Callout 2: The lines start close together at this level.
3Callout 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
# Interaction plot — Codesplash Chart Lab (recipe "interaction")# controls: interval=ci, level=0.95, dodge=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
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
fig.add_scatter(x=xs, y=sub["mean"], mode="lines+markers", name=t, line_color=PALETTE[k % len(PALETTE)],
error_y=dict(type="data", array=sub["half"], width=4))
fig.update_layout(xaxis=dict(tickvals=list(range(len(xl))), ticktext=xl, title="fertilizer"), yaxis_title="Mean yield_t_ha", legend_title_text="irrigation")
fig.show()
Needs pandas, numpy, plotly, scipy · reads interaction-demo.csv · app theme from the optional codesplash helper
Needs ggplot2 · reads interaction-demo.csv · app theme from the optional codesplashr helper
-- Interaction plot — Codesplash Chart Lab (recipe "interaction")-- controls: interval=ci, level=0.95, dodge=true-- cell means of the outcome per x × trace with n, SD and SE (multiply SE by t(1 − α/2, n − 1) for the CI)
SELECT "fertilizer"::VARCHAR AS x, "irrigation"::VARCHAR AS trace, count(*) AS n, avg("yield_t_ha") AS mean,
stddev_samp("yield_t_ha") AS sd, stddev_samp("yield_t_ha") / sqrt(count(*)) AS se
FROM read_csv('interaction-demo.csv')
WHERE "fertilizer" IS NOT NULL AND "irrigation" IS NOT NULL AND "yield_t_ha" IS NOT NULL
GROUP BY 1, 2
ORDER BY trace, x;
Read the overall direction: rising, falling or flat.
Read how tightly the points follow the fit line, and whether the fit should be straight at all.
Look for points far from the rest and for groups that behave differently.
1Callout 1: The fit line: the average trend, with its band.
2Callout 2: A cloud of one group: does the trend hold inside each group?
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
xv = d["spend_k"].to_numpy(dtype=float)
yv = d["revenue_k"].to_numpy(dtype=float)
fig = go.Figure()
for i, lv in enumerate(freq_levels(d["segment"])):
m = (d["segment"].astype(str) == lv).to_numpy()
fig.add_scatter(x=d["spend_k"][m], y=yv[m], mode="markers", name=lv, marker=dict(color=PALETTE[i % len(PALETTE)], symbol=SERIES_MARKERS[i % 8], size=6, opacity=0.7)) # marker shape per group, as in the app
grid, fit, lo, hi, a, b = ols_band(xv, yv)
gx = grid
fig.add_scatter(x=np.r_[gx, gx[::-1]], y=np.r_[hi, lo[::-1]], fill="toself", fillcolor="rgba(78,86,97,0.15)", line_width=0, name="95% CI", hoverinfo="skip")
fig.add_scatter(x=gx, y=fit, mode="lines", line=dict(color=REF, width=2), name="OLS")
fig.update_layout(xaxis_title="spend_k", yaxis_title="revenue_k")
fig.show()
Needs pandas, numpy, plotly, scipy, statsmodels · reads scatter-demo.csv · app theme from the optional codesplash helper
# Scatter plot — Codesplash Chart Lab (recipe "scatter")# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["segment"]] <- factor(df[["segment"]], levels = c("Consumer", "SMB", "Enterprise"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["segment"]], "cs_declared") <- TRUE # stored level order
d <- df[!is.na(df[["spend_k"]]) & !is.na(df[["revenue_k"]]), , drop = FALSE] # rows with a missing x or y are dropped
p <- ggplot(d, aes(x = .data[["spend_k"]], y = .data[["revenue_k"]])) +
geom_point(aes(colour = .data[["segment"]], shape = .data[["segment"]]), size = 1.8, alpha = 0.7) +
scale_colour_manual(values = cs_cat, name = "segment") + scale_shape_manual(values = cs_shapes, name = "segment") + # shape per group, as in the app
# one overall fit (colour only maps the points), 95% CI of the mean
geom_smooth(method = "lm", formula = y ~ x, level = 0.95, colour = ref_col, fill = ref_col, alpha = 0.15) +
labs(x = "spend_k", y = "revenue_k") +
theme_cs
print(p)
Needs ggplot2 · reads scatter-demo.csv · app theme from the optional codesplashr helper
-- Scatter plot — Codesplash Chart Lab (recipe "scatter")-- controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto-- OLS fit y = a + b·x over rows with both values (the band needs t(0.975, n − 2) on the client)-- the chart fits all rows (group NULL); per-segment fits are listed for comparison
WITH v AS (SELECT "spend_k"::DOUBLE AS x, "revenue_k"::DOUBLE AS y, "segment"::VARCHAR AS grp FROM read_csv('scatter-demo.csv') WHERE "spend_k" IS NOT NULL AND "revenue_k" IS NOT NULL)
SELECT grp AS "segment", regr_count(y, x) AS n,
regr_intercept(y, x) AS intercept,
regr_slope(y, x) AS slope,
regr_r2(y, x) AS r2,
sqrt(regr_syy(y, x) * (1 - regr_r2(y, x)) / (regr_count(y, x) - 2)) AS sigma,
sqrt(regr_syy(y, x) * (1 - regr_r2(y, x)) / (regr_count(y, x) - 2)) / sqrt(regr_sxx(y, x)) AS se_slope,
avg(x) AS mean_x,
regr_sxx(y, x) AS sxx
FROM v
GROUP BY GROUPING SETS ((), (grp))
ORDER BY grp NULLS FIRST;
Read position as for any scatter: the two main variables.
Read bubble area as the third variable; use the size legend.
Colour marks the group: look for groups that sit apart.
1Callout 1: Large bubbles: heavy rows, which can hide the small ones.
2Callout 2: Size legend: area shows the value.
3Callout 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
# Bubble chart — Codesplash Chart Lab (recipe "bubble")# controls: logX=true, scale=1, labels=5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
d = df.dropna(subset=["gdp_per_capita_k", "life_expectancy", "population_m"])
d = d[d["gdp_per_capita_k"] > 0]
d = d[d["population_m"] > 0].sort_values("population_m", ascending=False, kind="stable") # largest first
fig = px.scatter(d, x="gdp_per_capita_k", y="life_expectancy", size="population_m", size_max=44, color="region", color_discrete_sequence=PALETTE, symbol="region", symbol_sequence=SERIES_MARKERS, hover_name="country", log_x=True) # shape per colour group, as in the app
# plotly sizes markers by area (sizemode='area'), like the app
top = d.head(5)
fig.add_scatter(x=top["gdp_per_capita_k"], y=top["life_expectancy"], text=top["country"].astype(str), mode="text", textfont_size=10, showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads bubble-demo.csv · app theme from the optional codesplash helper
# Bubble chart — Codesplash Chart Lab (recipe "bubble")# controls: logX=true, scale=1, labels=5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("bubble-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("Africa", "Americas", "Asia", "Europe", "Oceania"))
df[["country"]] <- factor(df[["country"]])
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
d <- df[stats::complete.cases(df[c("gdp_per_capita_k", "life_expectancy", "population_m")]), , drop = FALSE]
d <- d[d[["gdp_per_capita_k"]] > 0, , drop = FALSE] # log axis: x <= 0 cannot be drawn
d <- d[d[["population_m"]] > 0, , drop = FALSE] # zero/negative sizes draw no bubble
d <- d[order(-d[["population_m"]]), , drop = FALSE] # largest first so small bubbles stay visible
p <- ggplot(d, aes(x = .data[["gdp_per_capita_k"]], y = .data[["life_expectancy"]], size = .data[["population_m"]])) +
geom_point(aes(colour = .data[["region"]], shape = .data[["region"]]), alpha = 0.75) + # shape per colour group, as in the app
scale_colour_manual(values = cs_cat, name = "region") + scale_shape_manual(values = cs_shapes, name = "region") +
scale_size_area(max_size = 16, name = "population_m") + # area ∝ value
geom_text(data = utils::head(d, 5), aes(label = .data[["country"]]), size = 3, show.legend = FALSE) +
scale_x_log10() +
labs(x = "gdp_per_capita_k", y = "life_expectancy") +
theme_cs
print(p)
Needs ggplot2 · reads bubble-demo.csv · app theme from the optional codesplashr helper
-- Bubble chart — Codesplash Chart Lab (recipe "bubble")-- controls: logX=true, scale=1, labels=5-- bubbles largest first; radius relative to the largest bubble = sqrt(v / v_max) (area ∝ value)
SELECT "region", "country", "gdp_per_capita_k", "life_expectancy", "population_m",
sqrt("population_m" / max("population_m") OVER ()) AS radius_rel
FROM read_csv('bubble-demo.csv')
WHERE "gdp_per_capita_k" IS NOT NULL AND "life_expectancy" IS NOT NULL AND "population_m" > 0 AND "gdp_per_capita_k" > 0
ORDER BY "population_m" DESC;
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
# 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 plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
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"])
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 = make_subplots(rows=2, cols=2, column_widths=[0.8, 0.2], row_heights=[0.2, 0.8], shared_xaxes=True, shared_yaxes=True, horizontal_spacing=0.01, vertical_spacing=0.01)
for i, (lv, m, col) in enumerate(groups): # marker shape per group, as in the app
fig.add_scatter(x=xv[m], y=yv[m], mode="markers", name=lv, marker=dict(color=col, symbol=SERIES_MARKERS[i % 8], size=5, opacity=0.75), row=2, col=1)
ex, ey = np.histogram_bin_edges(xv, bins="fd"), np.histogram_bin_edges(yv, bins="fd") # numpy edges, [a, b)
cx, _ = np.histogram(xv, ex)
cy, _ = np.histogram(yv, ey)
fig.add_bar(x=(ex[:-1] + ex[1:]) / 2, y=cx, width=np.diff(ex), marker_color=PALETTE[0], showlegend=False, row=1, col=1)
fig.add_bar(y=(ey[:-1] + ey[1:]) / 2, x=cy, width=np.diff(ey), orientation="h", marker_color=PALETTE[0], showlegend=False, row=2, col=2)
fig.update_layout(bargap=0, xaxis3_title="bill_length_mm", yaxis3_title="flipper_length_mm")
fig.show()
Needs pandas, numpy, plotly, scipy · reads scatter-marginal-demo.csv · app theme from the optional codesplash helper
# Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")# controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("scatter-marginal-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("Adelie", "Chinstrap", "Gentoo"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
bandwidth <- function(v, rule = "nrd0") {
switch(rule, nrd0 = bw.nrd0(v), nrd = bw.nrd(v), scott = sd(v) * length(v)^(-1 / 5))
}
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is # installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["species"]], "cs_declared") <- TRUE # stored level order
d <- df[!is.na(df[["bill_length_mm"]]) & !is.na(df[["flipper_length_mm"]]), , drop = FALSE] # rows missing x or y are dropped everywhere
xr <- range(d[["bill_length_mm"]]); yr <- range(d[["flipper_length_mm"]])
main <- ggplot(d, aes(x = .data[["bill_length_mm"]], y = .data[["flipper_length_mm"]])) +
geom_point(aes(colour = .data[["species"]], shape = .data[["species"]]), size = 1.5, alpha = 0.75) + # shape per group, as in the app
scale_colour_manual(values = cs_cat, name = "species") + scale_shape_manual(values = cs_shapes, name = "species") +
coord_cartesian(xlim = xr, ylim = yr) +
labs(x = "bill_length_mm", y = "flipper_length_mm") + theme_cs
bx <- np_edges(d[["bill_length_mm"]], "fd"); by <- np_edges(d[["flipper_length_mm"]], "fd") # numpy edges, [a, b)
top <- ggplot(d, aes(.data[["bill_length_mm"]])) + geom_histogram(breaks = bx, closed = "left", fill = cs_cat[1], colour = "white") +
coord_cartesian(xlim = xr) + theme_void()
right <- ggplot(d, aes(.data[["flipper_length_mm"]])) + geom_histogram(breaks = by, closed = "left", fill = cs_cat[1], colour = "white") +
coord_flip(xlim = yr) + theme_void()
arrange(list(top, main, right), layout = matrix(c(1, NA, 2, 3), 2, byrow = TRUE), widths = c(4, 1), heights = c(1, 4))
Needs ggplot2 · reads scatter-marginal-demo.csv · app theme from the optional codesplashr helper
-- Scatter with marginals — Codesplash Chart Lab (recipe "scatter-marginal")-- controls: marginal=histogram, bins=fd, bandwidth=nrd0, fit=none, size=2.5-- marginal histograms: numpy-style equal-width bins over each variable's [min, max]-- "group" NULL = all rows; per-species counts share the overall edges
(
WITH v AS (SELECT "bill_length_mm"::DOUBLE AS x, "species"::VARCHAR AS grp FROM read_csv('scatter-marginal-demo.csv') WHERE "bill_length_mm" IS NOT NULL AND isfinite("bill_length_mm"::DOUBLE)),
s AS (SELECT min(x) AS lo, max(x) AS hi, count(*) AS n, quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1 FROM v),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(2 * iqr * pow(n, -1.0 / 3), 0)))::INTEGER, 1) AS k FROM s),
b AS (SELECT least(floor((x - lo) / NULLIF((hi - lo) / k, 0)), k - 1)::INTEGER AS bin, grp FROM v, k)
SELECT 'bill_length_mm' AS variable, grp AS "group", coalesce(bin, 0) AS bin,
lo + coalesce(bin, 0) * (hi - lo) / k AS x0, lo + (coalesce(bin, 0) + 1) * (hi - lo) / k AS x1, count(*) AS count
FROM b, k GROUP BY GROUPING SETS ((bin, lo, hi, k), (grp, bin, lo, hi, k))
)
UNION ALL
(
WITH v AS (SELECT "flipper_length_mm"::DOUBLE AS x, "species"::VARCHAR AS grp FROM read_csv('scatter-marginal-demo.csv') WHERE "flipper_length_mm" IS NOT NULL AND isfinite("flipper_length_mm"::DOUBLE)),
s AS (SELECT min(x) AS lo, max(x) AS hi, count(*) AS n, quantile_cont(x, 0.75) - quantile_cont(x, 0.25) AS iqr,
stddev_pop(x) AS sd0, skewness(x) AS g1 FROM v),
k AS (SELECT lo, hi, n, coalesce(greatest(1, ceil((hi - lo) / NULLIF(2 * iqr * pow(n, -1.0 / 3), 0)))::INTEGER, 1) AS k FROM s),
b AS (SELECT least(floor((x - lo) / NULLIF((hi - lo) / k, 0)), k - 1)::INTEGER AS bin, grp FROM v, k)
SELECT 'flipper_length_mm' AS variable, grp AS "group", coalesce(bin, 0) AS bin,
lo + coalesce(bin, 0) * (hi - lo) / k AS x0, lo + (coalesce(bin, 0) + 1) * (hi - lo) / k AS x1, count(*) AS count
FROM b, k GROUP BY GROUPING SETS ((bin, lo, hi, k), (grp, bin, lo, hi, k))
)
ORDER BY variable, "group" NULLS FIRST, bin;
Needs ggplot2 · reads connected-scatter-demo.csv · app theme from the optional codesplashr helper
-- Connected scatter — Codesplash Chart Lab (recipe "connected-scatter")-- controls: gradient=true, arrows=true, labelEvery=5-- the path in time order: each row with the next point and the segment midpoint (arrow position)
SELECT "year", "unemployment_pct", "inflation_pct",
lead("unemployment_pct") OVER w AS x_next, lead("inflation_pct") OVER w AS y_next,
("unemployment_pct" + lead("unemployment_pct") OVER w) / 2 AS arrow_x, ("inflation_pct" + lead("inflation_pct") OVER w) / 2 AS arrow_y
FROM read_csv('connected-scatter-demo.csv')
WHERE "unemployment_pct" IS NOT NULL AND "inflation_pct" IS NOT NULL AND "year" IS NOT NULL
WINDOW w AS (ORDER BY "year")
ORDER BY "year";
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
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")# controls: bins=sturges
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"]
k = len(VARS)
per_panel = int(np.ceil(4000 / max(1, k * (k - 1) // 2)))
fig = make_subplots(rows=k, cols=k, horizontal_spacing=0.02, vertical_spacing=0.02)
LEVELS = freq_levels(df["species"])
for i, vy in enumerate(VARS):
for j, vx in enumerate(VARS):
if i == j:
v = df[vx].dropna().to_numpy(dtype=float)
edges = np.histogram_bin_edges(v, bins="sturges")
counts, _ = np.histogram(v, edges)
fig.add_bar(x=(edges[:-1] + edges[1:]) / 2, y=counts, width=np.diff(edges), marker_color=PALETTE[0], showlegend=False, row=i + 1, col=j + 1)
elif i > j:
pts = stride(df[[vx, vy, "species"]].dropna(subset=[vx, vy]), per_panel)
fig.add_scatter(x=pts[vx], y=pts[vy], mode="markers", marker=dict(size=4, opacity=0.7, color=[PALETTE[LEVELS.index(v) % 8] if v in LEVELS else PALETTE[7] for v in pts["species"].astype(str)]), showlegend=False, row=i + 1, col=j + 1)
else:
both = df[[vx, vy]].dropna()
text = [f"r = {both[vx].corr(both[vy]):.2f}"]
g = df.loc[both.index, "species"].astype(str)
text += [f"{lv}: {both[g == lv][vx].corr(both[g == lv][vy]):.2f}" for lv in LEVELS if (g == lv).sum() > 2]
fig.add_annotation(text="<br>".join(text), showarrow=False, font_size=11, xref=f"x{i * k + j + 1} domain", yref=f"y{i * k + j + 1} domain", x=0.5, y=0.5)
if i == k - 1:
fig.update_xaxes(title_text=vx, row=i + 1, col=j + 1)
if j == 0:
fig.update_yaxes(title_text=vy, row=i + 1, col=j + 1)
fig.update_layout(bargap=0, height=180 * k, width=180 * k)
fig.show()
Needs pandas, numpy, plotly · reads pair-plot-demo.csv · app theme from the optional codesplash helper
# Pair plot — Codesplash Chart Lab (recipe "pair-plot")# controls: bins=sturges
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pair-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("Adelie", "Chinstrap", "Gentoo"))
np_edges <- function(x, rule = "fd", k = NULL) {
# numpy.histogram_bin_edges: equal-width edges from min to max (the app's convention)
n <- length(x); lo <- min(x); hi <- max(x); ptp <- hi - lo
if (is.null(k)) {
width <- switch(rule,
fd = 2 * IQR(x, type = 7) * n^(-1 / 3),
sturges = ptp / (log2(n) + 1),
scott = (24 * sqrt(pi) / n)^(1 / 3) * sqrt(mean((x - mean(x))^2)),
rice = ptp / (2 * n^(1 / 3)),
sqrt = ptp / sqrt(n),
doane = {
sg1 <- sqrt(6 * (n - 2) / ((n + 1) * (n + 3)))
g1 <- mean(((x - mean(x)) / sqrt(mean((x - mean(x))^2)))^3)
ptp / (1 + log2(n) + log2(1 + abs(g1) / sg1))
})
k <- if (is.finite(width) && width > 0) max(1, ceiling(ptp / width)) else 1
}
if (ptp == 0) return(c(lo - 0.5, hi + 0.5))
seq(lo, hi, length.out = k + 1)
}
stride <- function(frame, k) {
if (nrow(frame) <= k) return(frame)
frame[floor((seq_len(k) - 1) * nrow(frame) / k) + 1, , drop = FALSE]
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["species"]], "cs_declared") <- TRUE # stored level order
vars <- c("bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g")
k <- length(vars)
per_panel <- ceiling(4000 / max(1, k * (k - 1) / 2)) # the app's 4,000-point budget
fac <- function(v) factor(v, levels = vars)
# Lower panels: scatters; diagonal: histograms rescaled into the panel's y range; upper: Pearson r
pts <- do.call(rbind, lapply(seq_len(k), function(i) do.call(rbind, lapply(seq_len(k), function(j) {
if (i <= j) return(NULL)
s <- stride(df[stats::complete.cases(df[c(vars[j], vars[i])]), , drop = FALSE], per_panel)
data.frame(col = vars[j], row = vars[i], x = s[[vars[j]]], y = s[[vars[i]]], g = as.character(s[["species"]]))
}))))
bars <- do.call(rbind, lapply(vars, function(v) {
x <- df[[v]][is.finite(df[[v]])]
e <- np_edges(x, "sturges")
n <- as.vector(table(cut(x, e, right = FALSE, include.lowest = TRUE)))
data.frame(col = v, row = v, xmin = utils::head(e, -1), xmax = e[-1], ymin = min(x), ymax = min(x) + n / max(n) * diff(range(x)))
}))
rs <- do.call(rbind, lapply(seq_len(k), function(i) do.call(rbind, lapply(seq_len(k), function(j) {
if (i >= j) return(NULL)
r <- stats::cor(df[[vars[j]]], df[[vars[i]]], use = "pairwise.complete.obs")
by <- sapply(freq_levels(df[["species"]]), function(lv) { m <- as.character(df[["species"]]) %in% lv
sprintf("%s: %.2f", lv, stats::cor(df[[vars[j]]][m], df[[vars[i]]][m], use = "pairwise.complete.obs")) })
data.frame(col = vars[j], row = vars[i], x = mean(range(df[[vars[j]]], na.rm = TRUE)), y = mean(range(df[[vars[i]]], na.rm = TRUE)), label = paste(c(sprintf("r = %.2f", r), by), collapse = "\n"))
}))))
pts$col <- fac(pts$col); pts$row <- fac(pts$row); bars$col <- fac(bars$col); bars$row <- fac(bars$row)
rs$col <- fac(rs$col); rs$row <- fac(rs$row)
p <- ggplot() +
geom_point(data = pts, aes(x, y, colour = g), size = 0.8, alpha = 0.7) +
scale_colour_manual(values = cs_cat, name = "species") +
geom_rect(data = bars, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), fill = cs_cat[1], colour = "white", linewidth = 0.2) +
geom_text(data = rs, aes(x, y, label = label), size = 3.5) +
facet_grid(row ~ col, scales = "free", switch = "both") +
labs(x = NULL, y = NULL) +
theme_cs + theme(strip.placement = "outside")
print(p)
Needs ggplot2 · reads pair-plot-demo.csv · app theme from the optional codesplashr helper
-- Pair plot — Codesplash Chart Lab (recipe "pair-plot")-- controls: bins=sturges-- Pearson r for every pair over pairwise-complete rows (the upper panels); "group" NULL = all rows, else per species
SELECT 'bill_length_mm' AS a, 'bill_depth_mm' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "bill_depth_mm") AS r, regr_count("bill_length_mm", "bill_depth_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_length_mm' AS a, 'flipper_length_mm' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "flipper_length_mm") AS r, regr_count("bill_length_mm", "flipper_length_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_length_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("bill_length_mm", "body_mass_g") AS r, regr_count("bill_length_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_depth_mm' AS a, 'flipper_length_mm' AS b, "species"::VARCHAR AS "group", corr("bill_depth_mm", "flipper_length_mm") AS r, regr_count("bill_depth_mm", "flipper_length_mm") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'bill_depth_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("bill_depth_mm", "body_mass_g") AS r, regr_count("bill_depth_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"))
UNION ALL
SELECT 'flipper_length_mm' AS a, 'body_mass_g' AS b, "species"::VARCHAR AS "group", corr("flipper_length_mm", "body_mass_g") AS r, regr_count("flipper_length_mm", "body_mass_g") AS n FROM read_csv('pair-plot-demo.csv') GROUP BY GROUPING SETS ((), ("species"));
Find the darkest cells off the diagonal: the strongest correlations.
Check colour for sign: one hue for positive, the other for negative.
Use clustered order to see blocks of variables that move together.
1Callout 1: A dark off-diagonal cell: a strong correlation.
2Callout 2: The other hue: a negative correlation.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
fig = go.Figure(go.Heatmap(z=r.to_numpy(), x=list(r.columns), y=list(r.index), zmin=-1, zmax=1,
colorscale=[[0, DIV[0]], [0.5, DIV[1]], [1, DIV[2]]],
text=r.map(apa_r).to_numpy(), texttemplate="%{text}", hovertemplate="%{y} × %{x}: %{z:.3f}<extra></extra>"))
fig.update_layout(yaxis_autorange="reversed", width=120 + 50 * len(VARS), height=100 + 45 * len(VARS))
fig.show()
Needs pandas, numpy, plotly · reads corr-heatmap-demo.csv · app theme from the optional codesplash helper
# Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")# controls: method=pearson, cluster=true, triangle=full, values=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("corr-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
cluster_order <- function(m) {
# average linkage on 1 - |r|; merged clusters are appended last (the app's leaf order)
d <- 1 - abs(ifelse(is.na(m), 0, m))
clusters <- as.list(seq_len(nrow(d)))
while (length(clusters) > 1) {
best <- c(1, 2); best_d <- Inf
for (a in seq_len(length(clusters) - 1)) for (b in (a + 1):length(clusters)) {
dist <- mean(d[clusters[[a]], clusters[[b]]])
if (dist < best_d) { best <- c(a, b); best_d <- dist }
}
merged <- c(clusters[[best[1]]], clusters[[best[2]]])
clusters <- c(clusters[-best], list(merged))
}
clusters[[1]]
}
apa_r <- function(v) ifelse(is.na(v), "", gsub("-", "\u2212", sub("^(-?)0\\.", "\\1.", sprintf("%.2f", v))))
vars <- c("income_k", "monthly_spend", "tenure_months", "site_visits", "churn_risk", "support_tickets", "age")
r <- stats::cor(df[vars], use = "pairwise.complete.obs", method = "pearson") # ranks per pair for Spearman
ord <- vars[cluster_order(r)]
cells <- expand.grid(row = ord, col = ord, stringsAsFactors = FALSE)
cells$r <- r[cbind(cells$row, cells$col)]
cells$row <- factor(cells$row, levels = rev(ord)); cells$col <- factor(cells$col, levels = ord)
p <- ggplot(cells, aes(col, row, fill = r)) +
geom_tile(colour = "white", linewidth = 0.5) +
geom_text(aes(label = apa_r(r)), size = 3) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], midpoint = 0, limits = c(-1, 1), name = "Pearson r") +
coord_equal() + labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
print(p)
Needs ggplot2 · reads corr-heatmap-demo.csv · app theme from the optional codesplashr helper
-- Correlation heatmap — Codesplash Chart Lab (recipe "corr-heatmap")-- controls: method=pearson, cluster=true, triangle=full, values=true-- Pearson r for every pair over pairwise-complete rows
SELECT 'income_k' AS a, 'monthly_spend' AS b, corr("income_k", "monthly_spend") AS r, regr_count("income_k", "monthly_spend") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'tenure_months' AS b, corr("income_k", "tenure_months") AS r, regr_count("income_k", "tenure_months") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'site_visits' AS b, corr("income_k", "site_visits") AS r, regr_count("income_k", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'churn_risk' AS b, corr("income_k", "churn_risk") AS r, regr_count("income_k", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'support_tickets' AS b, corr("income_k", "support_tickets") AS r, regr_count("income_k", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'income_k' AS a, 'age' AS b, corr("income_k", "age") AS r, regr_count("income_k", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'tenure_months' AS b, corr("monthly_spend", "tenure_months") AS r, regr_count("monthly_spend", "tenure_months") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'site_visits' AS b, corr("monthly_spend", "site_visits") AS r, regr_count("monthly_spend", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'churn_risk' AS b, corr("monthly_spend", "churn_risk") AS r, regr_count("monthly_spend", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'support_tickets' AS b, corr("monthly_spend", "support_tickets") AS r, regr_count("monthly_spend", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'monthly_spend' AS a, 'age' AS b, corr("monthly_spend", "age") AS r, regr_count("monthly_spend", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'site_visits' AS b, corr("tenure_months", "site_visits") AS r, regr_count("tenure_months", "site_visits") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'churn_risk' AS b, corr("tenure_months", "churn_risk") AS r, regr_count("tenure_months", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'support_tickets' AS b, corr("tenure_months", "support_tickets") AS r, regr_count("tenure_months", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'tenure_months' AS a, 'age' AS b, corr("tenure_months", "age") AS r, regr_count("tenure_months", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'churn_risk' AS b, corr("site_visits", "churn_risk") AS r, regr_count("site_visits", "churn_risk") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'support_tickets' AS b, corr("site_visits", "support_tickets") AS r, regr_count("site_visits", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'site_visits' AS a, 'age' AS b, corr("site_visits", "age") AS r, regr_count("site_visits", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'churn_risk' AS a, 'support_tickets' AS b, corr("churn_risk", "support_tickets") AS r, regr_count("churn_risk", "support_tickets") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'churn_risk' AS a, 'age' AS b, corr("churn_risk", "age") AS r, regr_count("churn_risk", "age") AS n FROM read_csv('corr-heatmap-demo.csv')
UNION ALL
SELECT 'support_tickets' AS a, 'age' AS b, corr("support_tickets", "age") AS r, regr_count("support_tickets", "age") AS n FROM read_csv('corr-heatmap-demo.csv');
Each cell is a strength between 0 and 1; the scale ignores direction.
Check the note at the bottom: the measure depends on the column types.
Use it to shortlist pairs, then look at each pair with a suited chart.
1Callout 1: A dark cell: a strong association.
2Callout 2: Which measure each kind of pair uses.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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"])
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)
fig = go.Figure(go.Heatmap(z=m.to_numpy(), x=list(m.columns), y=list(m.index), zmin=0, zmax=1, colorscale=[[0, SEQ[0]], [1, SEQ[-1]]],
texttemplate="%{z:.2f}", colorbar_title="assoc."))
fig.update_layout(yaxis_autorange="reversed", width=120 + 50 * len(VARS), height=100 + 45 * len(VARS))
fig.show()
Needs pandas, numpy, plotly, scipy · reads assoc-matrix-demo.csv · app theme from the optional codesplash helper
# Association matrix — Codesplash Chart Lab (recipe "assoc-matrix")# controls: numeric=pearson, cluster=false, triangle=full, values=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("assoc-matrix-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["churned"]] <- as.logical(df[["churned"]])
df[["segment"]] <- factor(df[["segment"]], levels = c("Consumer", "SMB", "Enterprise"))
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
df[["region"]] <- factor(df[["region"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
cluster_order <- function(m) {
# average linkage on 1 - |r|; merged clusters are appended last (the app's leaf order)
d <- 1 - abs(ifelse(is.na(m), 0, m))
clusters <- as.list(seq_len(nrow(d)))
while (length(clusters) > 1) {
best <- c(1, 2); best_d <- Inf
for (a in seq_len(length(clusters) - 1)) for (b in (a + 1):length(clusters)) {
dist <- mean(d[clusters[[a]], clusters[[b]]])
if (dist < best_d) { best <- c(a, b); best_d <- dist }
}
merged <- c(clusters[[best[1]]], clusters[[best[2]]])
clusters <- c(clusters[-best], list(merged))
}
clusters[[1]]
}
cramers_v <- function(a, b) {
# bias-corrected Cramér's V (Bergsma 2013) over rows with both values
t <- table(a, b); n <- sum(t); r <- nrow(t); k <- ncol(t)
if (n == 0 || r < 2 || k < 2) return(NA_real_)
chi2 <- suppressWarnings(stats::chisq.test(t, correct = FALSE)$statistic)
phi2 <- max(0, chi2 / n - (r - 1) * (k - 1) / (n - 1))
den <- min(r - (r - 1)^2 / (n - 1) - 1, k - (k - 1)^2 / (n - 1) - 1)
if (den > 0) sqrt(phi2 / den) else NA_real_
}
eta <- function(y, g) {
# correlation ratio: sqrt(SS_between / SS_total)
if (length(y) < 3 || length(unique(g)) < 2) return(NA_real_)
m <- mean(y)
ssb <- sum(tapply(y, g, function(s) length(s) * (mean(s) - m)^2))
sst <- sum((y - m)^2)
if (sst > 0) sqrt(ssb / sst) else NA_real_
}
association <- function(a, b, a_num, b_num, method) {
ok <- !is.na(a) & !is.na(b) # pairwise-complete rows
a <- a[ok]; b <- b[ok]
if (a_num && b_num) return(if (length(a) > 2) abs(stats::cor(a, b, method = method)) else NA_real_)
if (a_num) return(eta(a, as.character(b)))
if (b_num) return(eta(b, as.character(a)))
cramers_v(as.character(a), as.character(b))
}
vars <- c("income_k", "monthly_spend", "tenure_months", "age", "segment", "plan", "region", "churned")
is_num <- vars %in% c("income_k", "monthly_spend", "tenure_months", "age") # booleans count as categorical
m <- matrix(1, length(vars), length(vars), dimnames = list(vars, vars))
for (i in seq_along(vars)) for (j in seq_along(vars)) if (i != j)
m[i, j] <- association(df[[vars[i]]], df[[vars[j]]], is_num[i], is_num[j], "pearson")
ord <- vars
cells <- expand.grid(row = ord, col = ord, stringsAsFactors = FALSE)
cells$v <- m[cbind(cells$row, cells$col)]
cells$row <- factor(cells$row, levels = rev(ord)); cells$col <- factor(cells$col, levels = ord)
p <- ggplot(cells, aes(col, row, fill = v)) +
geom_tile(colour = "white", linewidth = 0.5) +
geom_text(aes(label = sprintf("%.2f", v)), size = 3) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], limits = c(0, 1), name = "|r|, V or η") +
coord_equal() + labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
print(p)
Needs ggplot2 · reads assoc-matrix-demo.csv · app theme from the optional codesplashr 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.
Each line is one row, crossing every axis at its value.
Lines running parallel between two axes: those variables move together; lines crossing in an X: they move oppositely.
Drag on an axis to select a range and see those rows light up.
1Callout 1: Each axis is scaled to its own minimum and maximum.
2Callout 2: Lines crossing in an X: the two variables move oppositely.
3Callout 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
# Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
levels = freq_levels(df["origin"])
code = d["origin"].astype(str).map({lv: i for i, lv in enumerate(levels)}).fillna(len(levels))
fig = go.Figure(go.Parcoords(
dimensions=[dict(label=v, values=d[v], range=[df[v].min(), df[v].max()]) for v in VARS],
line=dict(color=code, colorscale=[[i / max(1, len(levels)), PALETTE[i % 8]] for i in range(len(levels) + 1)], cmin=0, cmax=max(1, len(levels))),
))
# plotly's Parcoords leaves rows with a missing value out (the app breaks the line instead)
fig.show()
Needs pandas, numpy, plotly · reads parallel-coords-demo.csv · app theme from the optional codesplash helper
Needs ggplot2 · reads parallel-coords-demo.csv · app theme from the optional codesplashr helper
-- Parallel coordinates — Codesplash Chart Lab (recipe "parallel-coords")-- controls: defaults-- every variable min–max scaled to [0, 1] on its own range (one polyline per row)
SELECT row_number() OVER () AS row, "origin",
("mpg" - min("mpg") OVER ()) / NULLIF(max("mpg") OVER () - min("mpg") OVER (), 0) AS "mpg",
("cylinders" - min("cylinders") OVER ()) / NULLIF(max("cylinders") OVER () - min("cylinders") OVER (), 0) AS "cylinders",
("displacement" - min("displacement") OVER ()) / NULLIF(max("displacement") OVER () - min("displacement") OVER (), 0) AS "displacement",
("horsepower" - min("horsepower") OVER ()) / NULLIF(max("horsepower") OVER () - min("horsepower") OVER (), 0) AS "horsepower",
("weight" - min("weight") OVER ()) / NULLIF(max("weight") OVER () - min("weight") OVER (), 0) AS "weight",
("acceleration" - min("acceleration") OVER ()) / NULLIF(max("acceleration") OVER () - min("acceleration") OVER (), 0) AS "acceleration"
FROM read_csv('parallel-coords-demo.csv');
Read the overall shape: too many points for individuals, so density is what you see.
Use the colours to compare where groups sit.
Look for sharp edges, which often mark caps or rounding in the data.
1Callout 1: Solid mass: lowering the opacity shows the density inside it.
2Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
# Scattergl draws with WebGL, so hundreds of thousands of points stay interactive
for i, lv in enumerate(freq_levels(d["service"])):
m = d["service"].astype(str) == lv
fig.add_trace(go.Scattergl(x=d["distance_km"][m], y=d["fare_usd"][m], mode="markers", name=lv, marker=dict(color=PALETTE[i % len(PALETTE)], size=3, opacity=0.3)))
fig.update_layout(xaxis_title="distance_km", yaxis_title="fare_usd")
fig.show()
Needs pandas, numpy, plotly · reads scatter-large-demo.csv · app theme from the optional codesplash helper
# Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")# controls: renderer=auto, size=1.5, opacity=0.3
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("scatter-large-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["service"]] <- factor(df[["service"]], levels = c("Economy", "Comfort", "XL"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["service"]], "cs_declared") <- TRUE # stored level order
d <- df[!is.na(df[["distance_km"]]) & !is.na(df[["fare_usd"]]), , drop = FALSE]
# every row is drawn; shape 16 (solid, no outline) is the fastest point glyph on raster devices
p <- ggplot(d, aes(.data[["distance_km"]], .data[["fare_usd"]])) +
geom_point(aes(colour = .data[["service"]]), shape = 16, size = 0.525, alpha = 0.3) +
scale_colour_manual(values = cs_cat, name = "service") +
guides(colour = guide_legend(override.aes = list(size = 3, alpha = 1))) +
labs(x = "distance_km", y = "fare_usd", subtitle = paste(format(nrow(d), big.mark = ","), "points")) +
theme_cs
print(p)
Needs ggplot2 · reads scatter-large-demo.csv · app theme from the optional codesplashr helper
-- Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")-- controls: renderer=auto, size=1.5, opacity=0.3-- density on a 400 × 300 pixel grid: what the canvas paint accumulates through opacity (per service)
WITH v AS (SELECT "distance_km"::DOUBLE AS x, "fare_usd"::DOUBLE AS y, "service" AS "service" FROM read_csv('scatter-large-demo.csv') WHERE "distance_km" IS NOT NULL AND "fare_usd" IS NOT NULL),
r AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1 FROM v)
SELECT "service", least(floor((x - x0) / NULLIF(x1 - x0, 0) * 400), 399)::INTEGER AS px,
least(floor((y - y0) / NULLIF(y1 - y0, 0) * 300), 299)::INTEGER AS py,
count(*) AS n
FROM v, r
GROUP BY ALL
ORDER BY "service", py, px;
Read the band thickness for each series; the bottom band shares a flat baseline.
Switch to 100% to see the mix change without the total's growth.
1Callout 1: Top edge: the total.
2Callout 2: Bottom band: the easiest series to read, because its baseline is flat.
3Callout 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
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")# controls: percent=false, series=6
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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 = go.Figure()
for s, color, h in zip(series, colors, hatches):
fig.add_scatter(x=wide.index, y=wide[s], name=s, mode="lines", stackgroup="one", line=dict(width=0.5, color=color), fillcolor=color, fillpattern=dict(shape=h, fgcolor=HATCH_INK, fillmode="overlay"))
fig.update_layout(xaxis_title="month", yaxis_title="revenue_k", legend_title_text="product_line")
fig.show()
Needs pandas, numpy, plotly · reads area-stacked-demo.csv · app theme from the optional codesplash helper
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")# controls: percent=false, series=6
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("area-stacked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["product_line"]] <- factor(df[["product_line"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
ok <- !is.na(df[["month"]])
times <- sort(unique(df[["month"]][ok]))
ti <- match(df[["month"]][ok], times)
s <- as.character(df[["product_line"]][ok])
s[is.na(s)] <- "(missing)"
v <- df[["revenue_k"]][ok]
v[!is.finite(v)] <- 0
totals <- tapply(v, s, sum)
ranked <- names(totals)[order(-totals, names(totals))] # largest total first
keep <- if (length(ranked) > 6) head(ranked, 6 - 1) else ranked # beyond the limit → "Other"
series <- c(keep, if (length(ranked) > length(keep)) "Other")
s <- ifelse(s %in% keep, s, "Other")
m <- tapply(v, list(ti, factor(s, levels = series)), sum)
m[is.na(m)] <- 0
top <- m
for (j in seq_len(ncol(m))[-1]) top[, j] <- top[, j - 1] + m[, j] # first series at the bottom
long <- data.frame(time = rep(times, ncol(m)), series = factor(rep(series, each = length(times)), levels = series),
ymin = as.vector(top - m), ymax = as.vector(top))
fill <- setNames(rep(cs_cat, length.out = length(series)), series)
fill[series == "Other"] <- "#9aa0a6"
fill <- setNames(cs_textures(unname(fill), idx = ifelse(series == "Other", 8, seq_along(series))), series) # texture per layer, as in the app
p <- ggplot(long, aes(time, ymin = ymin, ymax = ymax, fill = series)) +
geom_ribbon(alpha = 0.9) +
scale_fill_manual(values = fill, name = "product_line") +
labs(x = "month", y = "revenue_k") +
theme_cs
print(p)
Needs ggplot2 · reads area-stacked-demo.csv · app theme from the optional codesplashr helper
-- Stacked area — Codesplash Chart Lab (recipe "area-stacked")-- controls: percent=false, series=6-- value per (time, series); series ranked by total (largest first), beyond 6 pooled into 'Other'
WITH d AS (
SELECT "month" AS t, coalesce("product_line"::VARCHAR, '(missing)') AS s,
CASE WHEN isfinite("revenue_k") THEN "revenue_k" ELSE 0 END AS v
FROM read_csv('area-stacked-demo.csv') WHERE "month" IS NOT NULL
),
r AS (SELECT s, row_number() OVER (ORDER BY sum(v) DESC, s) AS rk, count(*) OVER () AS k FROM d GROUP BY s),
p AS (
SELECT d.t, CASE WHEN r.k <= 6 OR r.rk < 6 THEN d.s ELSE 'Other' END AS series, r.rk, d.v
FROM d JOIN r USING (s)
)
SELECT t, series, sum(v) AS value, sum(v) / sum(sum(v)) OVER (PARTITION BY t) AS share
FROM p
GROUP BY t, series
ORDER BY t, min(rk);
Compare large blocks; use labels for the small ones.
1Callout 1: A big rectangle: a large share of the total.
2Callout 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
# Treemap — Codesplash Chart Lab (recipe "treemap")# controls: maxChildren=10
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
nodes = tree_nodes(df, ["category", "subcategory"], "revenue", max_children=10)
PHI = (1 + 5 ** 0.5) / 2 # d3's golden-ratio squarify target
OTHER = "#9aa0a6" # pooled levels
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}
fig = go.Figure(go.Treemap(
ids=nodes["id"], labels=nodes["label"], parents=["" if p == "All" else p for p in nodes["parent"]],
values=nodes["value"], branchvalues="total", sort=True,
marker=dict(colors=[top_color[t] for t in nodes["top"]]),
tiling=dict(packing="squarify", squarifyratio=PHI, pad=2),
hovertemplate="%{id}<br>%{value:,.4g} (%{percentRoot:.1%} of total)<extra></extra>",
))
fig.update_layout(margin=dict(t=30, l=10, r=10, b=10))
fig.show()
Needs pandas, numpy, plotly · reads treemap-demo.csv · app theme from the optional codesplash helper
# Treemap — Codesplash Chart Lab (recipe "treemap")# controls: maxChildren=10
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("treemap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["category"]] <- factor(df[["category"]])
df[["subcategory"]] <- factor(df[["subcategory"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
tree_nodes <- function(frame, levels, size = NULL, 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 <- if (is.null(size)) rep(1, nrow(frame)) else suppressWarnings(as.numeric(frame[[size]]))
w[!is.finite(w)] <- 0
keep <- w > 0
paths <- lapply(levels, function(l) {
v <- as.character(frame[[l]])[keep]
ifelse(is.na(v), "(missing)", v)
})
w <- w[keep]
out <- list()
walk <- function(idx, depth, parent, top) {
if (depth > length(levels)) return(invisible(NULL))
key <- paths[[depth]][idx]
sums <- tapply(w[idx], key, sum)
o <- order(-sums, names(sums))
kids <- names(sums)[o]
vals <- as.numeric(sums)[o]
m <- if (length(kids) > max_children) max_children - 1 else length(kids)
e <- data.frame(label = kids[seq_len(m)], value = vals[seq_len(m)], pooled = FALSE)
if (length(kids) > m) e <- rbind(e, data.frame(label = "Other", value = sum(vals[-seq_len(m)]), pooled = TRUE))
e <- e[order(-e$value, e$pooled), ] # d3 re-sorts siblings by value; "Other" last among ties
for (k in seq_len(nrow(e))) {
id <- paste(parent, e$label[k], sep = " \u203a ")
tp <- if (is.null(top)) e$label[k] else top
out[[length(out) + 1]] <<- data.frame(id = id, label = e$label[k], parent = parent, value = e$value[k], depth = depth, top = tp)
if (!e$pooled[k]) walk(idx[key == e$label[k]], depth + 1, id, tp)
}
}
walk(seq_along(w), 1, "All", NULL)
do.call(rbind, out)
}
squarify <- function(values, x0, y0, x1, y1, ratio = (1 + sqrt(5)) / 2) {
# d3.treemapSquarify: rows grow while their worst aspect ratio improves (Bruls et al. 2000)
out <- matrix(NA_real_, length(values), 4)
i0 <- 1
n <- length(values)
value <- sum(values)
while (i0 <= n) {
dx <- max(x1 - x0, 1e-9)
dy <- 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 <- s + v; lo <- min(lo, v); hi <- max(hi, v); best <- r; i1 <- i1 + 1
}
rows <- i0:(i1 - 1)
if (dx < dy) { # a strip across the top, nodes side by side
yb <- y0 + dy * s / value
xs <- x0 + dx * cumsum(c(0, values[rows])) / s
out[rows, ] <- cbind(head(xs, -1), y0, tail(xs, -1), yb)
y0 <- yb
} else { # a strip down the left, nodes stacked
xb <- x0 + dx * s / value
ys <- y0 + dy * cumsum(c(0, values[rows])) / s
out[rows, ] <- cbind(x0, head(ys, -1), xb, tail(ys, -1))
x0 <- xb
}
value <- value - s
i0 <- i1
}
out
}
layout_treemap <- function(nodes, W = 960, H = 540, pad = 2, header = 17) {
# nested squarified rectangles in a W × H canvas (y down), 2 px padding, 17 px header on top-level groups
nodes$x0 <- nodes$y0 <- nodes$x1 <- nodes$y1 <- NA_real_
parents <- unique(nodes$parent)
place <- function(parent, x0, y0, x1, y1) {
k <- which(nodes$parent == parent)
if (!length(k)) return(invisible(NULL))
r <- squarify(nodes$value[k], x0, y0, x1, y1)
for (j in seq_along(k)) {
b <- r[j, ] + c(pad, pad, -pad, -pad) / 2
nodes[k[j], c("x0", "y0", "x1", "y1")] <<- as.list(b)
if (nodes$id[k[j]] %in% parents) {
top <- if (nodes$depth[k[j]] == 1 && b[3] - b[1] > 40) header else pad
place(nodes$id[k[j]], b[1] + pad, b[2] + top, b[3] - pad, b[4] - pad)
}
}
}
place("All", 0, 0, W, H)
nodes
}
nodes <- tree_nodes(df, c("category", "subcategory"), "revenue", max_children = 10)
nodes <- layout_treemap(nodes)
tops <- nodes$label[nodes$depth == 1]
top_color <- setNames(rep(cs_cat, length.out = length(tops)), tops)
top_color[tops == "Other"] <- "#9aa0a6"
nodes$fill <- top_color[nodes$top]
nodes$alpha <- c(1, 0.72, 0.5, 0.36)[pmin(nodes$depth, 4)] # lighter for deeper levels
nodes$leaf <- !(nodes$id %in% nodes$parent)
total <- sum(nodes$value[nodes$depth == 1])
leaves <- nodes[nodes$leaf, ]
groups <- nodes[!nodes$leaf & nodes$depth == 1, ]
p <- ggplot() +
geom_rect(data = groups, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = fill), alpha = 0.18) +
geom_rect(data = leaves, aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1, fill = fill), alpha = 0.88) +
geom_text(data = groups[groups$x1 - groups$x0 > 40, ], aes(x = x0 + 4, y = y0 + 3, label = label), hjust = 0, vjust = 1, size = 2.8, fontface = "bold") +
geom_text(data = leaves[leaves$x1 - leaves$x0 > 60 & leaves$y1 - leaves$y0 > 22, ],
aes(x = x0 + 4, y = y0 + 4, label = sprintf("%s\n%.1f%%", label, 100 * value / total)), hjust = 0, vjust = 1, size = 2.3, colour = "white", lineheight = 0.9) +
scale_fill_identity() +
scale_y_reverse() + # y down, like the SVG
coord_fixed() +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads treemap-demo.csv · app theme from the optional codesplashr helper
-- Treemap — Codesplash Chart Lab (recipe "treemap")-- controls: maxChildren=10-- node totals for every prefix of the hierarchy (ROLLUP) and each node's rank among its siblings;-- the app pools siblings with rank ≥ 10 into "Other" when a parent has more than 10 children
WITH d AS (SELECT coalesce("category"::VARCHAR, '(missing)') AS "category", coalesce("subcategory"::VARCHAR, '(missing)') AS "subcategory", CASE WHEN isfinite("revenue") THEN "revenue" ELSE 0 END AS w FROM read_csv('treemap-demo.csv')),
nodes AS (
SELECT "category", "subcategory", (1 - grouping("category")) + (1 - grouping("subcategory")) AS depth, sum(w) AS value
FROM d
WHERE w > 0
GROUP BY ROLLUP ("category", "subcategory")
)
SELECT *, row_number() OVER (
PARTITION BY depth, CASE WHEN depth > 1 THEN "category" END
ORDER BY value DESC, "category", "subcategory"
) AS sibling_rank -- rank among siblings (same parent path), ties alphabetical
FROM nodes
ORDER BY depth, "category", "subcategory";
Needs duckdb · reads treemap-demo.csv
Layout: the d3 squarify algorithm (golden-ratio target) re-implemented inline in Python and R; padding approximates the app's.
Start at the centre: the inner ring is the top level.
Move outward: each outer ring splits the slice inside it.
Read arc length as share; the legend lists the top-level shares.
1Callout 1: The centre shows the total.
2Callout 2: Outer rings split the segment inside them.
3Callout 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
# Sunburst — Codesplash Chart Lab (recipe "sunburst")# controls: maxChildren=8
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
OTHER = "#9aa0a6" # pooled levels
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}
fig = go.Figure(go.Sunburst(
ids=nodes["id"], labels=nodes["label"], parents=["" if p == "All" else p for p in nodes["parent"]],
values=nodes["value"], branchvalues="total", sort=True,
marker=dict(colors=[top_color[t] for t in nodes["top"]]),
rotation=90, # first slice at 12 o'clock
hovertemplate="%{id}<br>%{value:,.4g} (%{percentRoot:.1%} of total)<extra></extra>",
))
fig.update_layout(margin=dict(t=30, l=10, r=10, b=10))
fig.show()
Needs pandas, numpy, plotly · reads sunburst-demo.csv · app theme from the optional codesplash helper
# Sunburst — Codesplash Chart Lab (recipe "sunburst")# controls: maxChildren=8
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("sunburst-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["category"]] <- factor(df[["category"]])
df[["subcategory"]] <- factor(df[["subcategory"]])
df[["channel"]] <- factor(df[["channel"]], levels = c("Web", "App", "Store"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
tree_nodes <- function(frame, levels, size = NULL, 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 <- if (is.null(size)) rep(1, nrow(frame)) else suppressWarnings(as.numeric(frame[[size]]))
w[!is.finite(w)] <- 0
keep <- w > 0
paths <- lapply(levels, function(l) {
v <- as.character(frame[[l]])[keep]
ifelse(is.na(v), "(missing)", v)
})
w <- w[keep]
out <- list()
walk <- function(idx, depth, parent, top) {
if (depth > length(levels)) return(invisible(NULL))
key <- paths[[depth]][idx]
sums <- tapply(w[idx], key, sum)
o <- order(-sums, names(sums))
kids <- names(sums)[o]
vals <- as.numeric(sums)[o]
m <- if (length(kids) > max_children) max_children - 1 else length(kids)
e <- data.frame(label = kids[seq_len(m)], value = vals[seq_len(m)], pooled = FALSE)
if (length(kids) > m) e <- rbind(e, data.frame(label = "Other", value = sum(vals[-seq_len(m)]), pooled = TRUE))
e <- e[order(-e$value, e$pooled), ] # d3 re-sorts siblings by value; "Other" last among ties
for (k in seq_len(nrow(e))) {
id <- paste(parent, e$label[k], sep = " \u203a ")
tp <- if (is.null(top)) e$label[k] else top
out[[length(out) + 1]] <<- data.frame(id = id, label = e$label[k], parent = parent, value = e$value[k], depth = depth, top = tp)
if (!e$pooled[k]) walk(idx[key == e$label[k]], depth + 1, id, tp)
}
}
walk(seq_along(w), 1, "All", NULL)
do.call(rbind, out)
}
partition <- function(nodes) {
# each node's span [x0, x1) as a share of the total; children split the parent's span by value
span <- list(All = c(0, 1))
pv <- c(All = sum(nodes$value[nodes$depth == 1]))
cursor <- c(All = 0)
nodes$x0 <- nodes$x1 <- NA_real_
for (i in seq_len(nrow(nodes))) { # depth-first: parents come before their children
p <- nodes$parent[i]
s <- span[[p]]
w <- (s[2] - s[1]) * nodes$value[i] / pv[[p]]
nodes$x0[i] <- s[1] + cursor[[p]]
nodes$x1[i] <- nodes$x0[i] + w
cursor[[p]] <- cursor[[p]] + w
span[[nodes$id[i]]] <- c(nodes$x0[i], nodes$x1[i])
pv[[nodes$id[i]]] <- nodes$value[i]
cursor[[nodes$id[i]]] <- 0
}
nodes
}
nodes <- tree_nodes(df, c("category", "subcategory", "channel"), "revenue", max_children = 8)
nodes <- partition(nodes)
tops <- nodes$label[nodes$depth == 1]
top_color <- setNames(rep(cs_cat, length.out = length(tops)), tops)
top_color[tops == "Other"] <- "#9aa0a6"
nodes$fill <- top_color[nodes$top]
nodes$alpha <- c(1, 0.72, 0.5, 0.36)[pmin(nodes$depth, 4)] # lighter for deeper levels
D <- 3 # rings: equal width, the hole is one ring wide
nodes$mid <- (nodes$x0 + nodes$x1) / 2
nodes$show <- (nodes$x1 - nodes$x0) * 2 * pi * (nodes$depth + 0.5) / (D + 1) > 0.18 # labels only on wide arcs
total <- sum(nodes$value[nodes$depth == 1])
p <- ggplot(nodes) +
geom_rect(aes(xmin = depth, xmax = depth + 1, ymin = x0, ymax = x1, fill = fill, alpha = alpha), colour = "white", linewidth = 0.3) +
geom_text(data = nodes[nodes$show, ], aes(x = depth + 0.5, y = mid, label = label), size = 2.2) +
annotate("text", x = 0, y = 0, label = format(round(total), big.mark = ","), fontface = "bold", size = 4) + # the centre shows the total
scale_fill_identity() +
scale_alpha_identity() +
scale_x_continuous(limits = c(0, D + 1)) +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0)) +
coord_polar(theta = "y", start = 0, direction = 1) + # clockwise from 12 o'clock
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads sunburst-demo.csv · app theme from the optional codesplashr helper
-- Sunburst — Codesplash Chart Lab (recipe "sunburst")-- controls: maxChildren=8-- node totals for every prefix of the hierarchy (ROLLUP) and each node's rank among its siblings;-- the app pools siblings with rank ≥ 8 into "Other" when a parent has more than 8 children
WITH d AS (SELECT coalesce("category"::VARCHAR, '(missing)') AS "category", coalesce("subcategory"::VARCHAR, '(missing)') AS "subcategory", coalesce("channel"::VARCHAR, '(missing)') AS "channel", CASE WHEN isfinite("revenue") THEN "revenue" ELSE 0 END AS w FROM read_csv('sunburst-demo.csv')),
nodes AS (
SELECT "category", "subcategory", "channel", (1 - grouping("category")) + (1 - grouping("subcategory")) + (1 - grouping("channel")) AS depth, sum(w) AS value
FROM d
WHERE w > 0
GROUP BY ROLLUP ("category", "subcategory", "channel")
)
SELECT *, row_number() OVER (
PARTITION BY depth, CASE WHEN depth > 1 THEN "category" END, CASE WHEN depth > 2 THEN "subcategory" END
ORDER BY value DESC, "category", "subcategory", "channel"
) AS sibling_rank -- rank among siblings (same parent path), ties alphabetical
FROM nodes
ORDER BY depth, "category", "subcategory", "channel";
Needs duckdb · reads sunburst-demo.csv
plotly's sunburst lays slices out counter-clockwise; the app (and the matplotlib/ggplot2 versions) go clockwise from 12 o'clock.
Read columns left to right: each column is one level deeper.
Read a rectangle's height as its share.
Follow one colour rightward to see how that group breaks down.
1Callout 1: Leftmost column: the top level.
2Callout 2: Next column: the split inside it.
3Callout 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
# Icicle — Codesplash Chart Lab (recipe "icicle")# controls: maxChildren=8
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
OTHER = "#9aa0a6" # pooled levels
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}
fig = go.Figure(go.Icicle(
ids=nodes["id"], labels=nodes["label"], parents=["" if p == "All" else p for p in nodes["parent"]],
values=nodes["value"], branchvalues="total", sort=True,
marker=dict(colors=[top_color[t] for t in nodes["top"]]),
tiling=dict(orientation="h"), # levels left to right
hovertemplate="%{id}<br>%{value:,.4g} (%{percentRoot:.1%} of total)<extra></extra>",
))
fig.update_layout(margin=dict(t=30, l=10, r=10, b=10))
fig.show()
Needs pandas, numpy, plotly · reads icicle-demo.csv · app theme from the optional codesplash helper
# Icicle — Codesplash Chart Lab (recipe "icicle")# controls: maxChildren=8
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("icicle-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["category"]] <- factor(df[["category"]])
df[["subcategory"]] <- factor(df[["subcategory"]])
df[["channel"]] <- factor(df[["channel"]], levels = c("Web", "App", "Store"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
tree_nodes <- function(frame, levels, size = NULL, 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 <- if (is.null(size)) rep(1, nrow(frame)) else suppressWarnings(as.numeric(frame[[size]]))
w[!is.finite(w)] <- 0
keep <- w > 0
paths <- lapply(levels, function(l) {
v <- as.character(frame[[l]])[keep]
ifelse(is.na(v), "(missing)", v)
})
w <- w[keep]
out <- list()
walk <- function(idx, depth, parent, top) {
if (depth > length(levels)) return(invisible(NULL))
key <- paths[[depth]][idx]
sums <- tapply(w[idx], key, sum)
o <- order(-sums, names(sums))
kids <- names(sums)[o]
vals <- as.numeric(sums)[o]
m <- if (length(kids) > max_children) max_children - 1 else length(kids)
e <- data.frame(label = kids[seq_len(m)], value = vals[seq_len(m)], pooled = FALSE)
if (length(kids) > m) e <- rbind(e, data.frame(label = "Other", value = sum(vals[-seq_len(m)]), pooled = TRUE))
e <- e[order(-e$value, e$pooled), ] # d3 re-sorts siblings by value; "Other" last among ties
for (k in seq_len(nrow(e))) {
id <- paste(parent, e$label[k], sep = " \u203a ")
tp <- if (is.null(top)) e$label[k] else top
out[[length(out) + 1]] <<- data.frame(id = id, label = e$label[k], parent = parent, value = e$value[k], depth = depth, top = tp)
if (!e$pooled[k]) walk(idx[key == e$label[k]], depth + 1, id, tp)
}
}
walk(seq_along(w), 1, "All", NULL)
do.call(rbind, out)
}
partition <- function(nodes) {
# each node's span [x0, x1) as a share of the total; children split the parent's span by value
span <- list(All = c(0, 1))
pv <- c(All = sum(nodes$value[nodes$depth == 1]))
cursor <- c(All = 0)
nodes$x0 <- nodes$x1 <- NA_real_
for (i in seq_len(nrow(nodes))) { # depth-first: parents come before their children
p <- nodes$parent[i]
s <- span[[p]]
w <- (s[2] - s[1]) * nodes$value[i] / pv[[p]]
nodes$x0[i] <- s[1] + cursor[[p]]
nodes$x1[i] <- nodes$x0[i] + w
cursor[[p]] <- cursor[[p]] + w
span[[nodes$id[i]]] <- c(nodes$x0[i], nodes$x1[i])
pv[[nodes$id[i]]] <- nodes$value[i]
cursor[[nodes$id[i]]] <- 0
}
nodes
}
nodes <- tree_nodes(df, c("category", "subcategory", "channel"), "revenue", max_children = 8)
nodes <- partition(nodes)
tops <- nodes$label[nodes$depth == 1]
top_color <- setNames(rep(cs_cat, length.out = length(tops)), tops)
top_color[tops == "Other"] <- "#9aa0a6"
nodes$fill <- top_color[nodes$top]
nodes$alpha <- c(1, 0.72, 0.5, 0.36)[pmin(nodes$depth, 4)] # lighter for deeper levels
LEVELS <- c("category", "subcategory", "channel")
p <- ggplot(nodes) +
geom_rect(aes(xmin = depth - 1, xmax = depth, ymin = 1 - x1, ymax = 1 - x0, fill = fill, alpha = alpha), colour = "white", linewidth = 0.4) +
geom_text(data = nodes[nodes$x1 - nodes$x0 > 0.035, ], aes(x = depth - 0.97, y = 1 - (x0 + x1) / 2, label = paste(label, format(round(value), big.mark = ","))), hjust = 0, size = 2.3) +
scale_fill_identity() +
scale_alpha_identity() +
scale_x_continuous(breaks = seq_along(LEVELS) - 0.5, labels = LEVELS, position = "top", expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL, y = NULL) +
theme_cs +
theme(axis.text.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(), axis.ticks = element_blank())
print(p)
Needs ggplot2 · reads icicle-demo.csv · app theme from the optional codesplashr helper
-- Icicle — Codesplash Chart Lab (recipe "icicle")-- controls: maxChildren=8-- node totals for every prefix of the hierarchy (ROLLUP) and each node's rank among its siblings;-- the app pools siblings with rank ≥ 8 into "Other" when a parent has more than 8 children
WITH d AS (SELECT coalesce("category"::VARCHAR, '(missing)') AS "category", coalesce("subcategory"::VARCHAR, '(missing)') AS "subcategory", coalesce("channel"::VARCHAR, '(missing)') AS "channel", CASE WHEN isfinite("revenue") THEN "revenue" ELSE 0 END AS w FROM read_csv('icicle-demo.csv')),
nodes AS (
SELECT "category", "subcategory", "channel", (1 - grouping("category")) + (1 - grouping("subcategory")) + (1 - grouping("channel")) AS depth, sum(w) AS value
FROM d
WHERE w > 0
GROUP BY ROLLUP ("category", "subcategory", "channel")
)
SELECT *, row_number() OVER (
PARTITION BY depth, CASE WHEN depth > 1 THEN "category" END, CASE WHEN depth > 2 THEN "subcategory" END
ORDER BY value DESC, "category", "subcategory", "channel"
) AS sibling_rank -- rank among siblings (same parent path), ties alphabetical
FROM nodes
ORDER BY depth, "category", "subcategory", "channel";
Follow the floating bars: each adds or subtracts from where the last ended.
End at the closing total, and check the subtotals along the way.
1Callout 1: The opening total.
2Callout 2: A floating bar: an increase or a decrease.
3Callout 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
# Waterfall — Codesplash Chart Lab (recipe "waterfall")# controls: end=true, labels=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"}
measure = {"total": "absolute", "subtotal": "total", "increase": "relative", "decrease": "relative"}
fig = go.Figure(go.Waterfall(
x=bars["step"], y=[0 if k == "subtotal" else v for k, v in zip(bars["kind"], bars["value"])],
measure=[measure[k] for k in bars["kind"]],
# the closing total is an "absolute" bar at the running level
increasing=dict(marker_color=KIND_COLOR["increase"]), decreasing=dict(marker_color=KIND_COLOR["decrease"]),
totals=dict(marker_color=KIND_COLOR["total"]), connector=dict(line=dict(dash="dash", width=1)),
textposition="outside", texttemplate=["%{delta:+,.4g}" if k in ("increase", "decrease") else "%{final:,.4g}" for k in bars["kind"]],
))
fig.update_layout(yaxis_title="change_m", showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads waterfall-demo.csv · app theme from the optional codesplash helper
# Waterfall — Codesplash Chart Lab (recipe "waterfall")# controls: end=true, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("waterfall-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["is_total"]] <- as.logical(df[["is_total"]])
df[["driver"]] <- factor(df[["driver"]], levels = c("FY2025 revenue", "Price", "Volume", "Mix", "Gross", "FX", "Churn", "New logos"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
step <- as.character(df[["driver"]])
step[is.na(step)] <- "(missing)"
v <- suppressWarnings(as.numeric(df[["change_m"]]))
v[!is.finite(v)] <- NA
is_total <- df[["is_total"]] %in% TRUE
ord <- c(intersect(levels(df[["driver"]]), step), setdiff(unique(step), levels(df[["driver"]]))) # declared order first
rows <- list()
running <- 0
for (s in ord) {
vals <- v[step == s]
value <- if (any(!is.na(vals))) sum(vals, na.rm = TRUE) else NA # summed per step
if (any(is_total[step == s])) { # totals with a value set the level; without one they are subtotals
if (!is.na(value)) running <- value
rows[[length(rows) + 1]] <- data.frame(step = s, kind = if (is.na(value)) "subtotal" else "total", value = running, start = 0, end = running)
} else {
delta <- if (is.na(value)) 0 else value
rows[[length(rows) + 1]] <- data.frame(step = s, kind = if (delta >= 0) "increase" else "decrease", value = delta, start = running, end = running + delta)
running <- running + delta
}
}
rows[[length(rows) + 1]] <- data.frame(step = "End", kind = "total", value = running, start = 0, end = running) # closing total
bars <- do.call(rbind, rows)
bars$i <- seq_len(nrow(bars))
kind_color <- c(increase = "#187c49", decrease = "#c9302d", total = cs_cat[1], subtotal = grDevices::adjustcolor(cs_cat[1], 0.55))
p <- ggplot(bars) +
geom_rect(aes(xmin = i - 0.36, xmax = i + 0.36, ymin = pmin(start, end), ymax = pmax(start, end), fill = kind)) +
geom_segment(data = bars[-nrow(bars), ], aes(x = i + 0.36, xend = i + 0.64, y = end, yend = end), linetype = "dashed", linewidth = 0.3) +
geom_text(aes(x = i, y = pmax(start, end), label = ifelse(kind %in% c("increase", "decrease"), sprintf("%+.4g", value), sprintf("%.4g", value))), vjust = -0.5, size = 2.5) +
geom_hline(yintercept = 0, linewidth = 0.3) +
scale_fill_manual(values = kind_color, name = NULL) +
scale_x_continuous(breaks = bars$i, labels = bars$step) +
labs(x = NULL, y = "change_m") +
theme_cs +
theme(axis.text.x = element_text(angle = 30, hjust = 1))
print(p)
Needs ggplot2 · reads waterfall-demo.csv · app theme from the optional codesplashr helper
-- Waterfall — Codesplash Chart Lab (recipe "waterfall")-- controls: end=true, labels=true-- bridge geometry: per-step sums in declared order; totals with a value reset the running level
WITH s AS (SELECT *, row_number() OVER () AS _row FROM read_csv('waterfall-demo.csv')),
lv(level, rk) AS (VALUES ('FY2025 revenue', 1), ('Price', 2), ('Volume', 3), ('Mix', 4), ('Gross', 5), ('FX', 6), ('Churn', 7), ('New logos', 8)),
steps AS (
SELECT coalesce(s."driver"::VARCHAR, '(missing)') AS step,
sum(CASE WHEN isfinite(s."change_m") THEN s."change_m" END) AS value,
bool_or(coalesce(s."is_total", false)) AS is_total,
coalesce(min(lv.rk), 1e9 + min(s._row)) AS ord
FROM s
LEFT JOIN lv ON lv.level = s."driver"::VARCHAR
GROUP BY 1
),
g AS (SELECT *, sum(CASE WHEN is_total AND value IS NOT NULL THEN 1 ELSE 0 END) OVER (ORDER BY ord) AS grp FROM steps),
r AS (
SELECT *,
coalesce(max(CASE WHEN is_total AND value IS NOT NULL THEN value END) OVER (PARTITION BY grp), 0)
+ sum(CASE WHEN is_total THEN 0 ELSE coalesce(value, 0) END) OVER (PARTITION BY grp ORDER BY ord) AS level_end
FROM g
)
SELECT step,
CASE WHEN is_total AND value IS NOT NULL THEN 'total' WHEN is_total THEN 'subtotal'
WHEN coalesce(value, 0) >= 0 THEN 'increase' ELSE 'decrease' END AS kind,
CASE WHEN is_total THEN level_end ELSE coalesce(value, 0) END AS change,
CASE WHEN is_total THEN 0 ELSE level_end - coalesce(value, 0) END AS start,
level_end AS "end"
FROM r
ORDER BY ord;
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
# Funnel — Codesplash Chart Lab (recipe "funnel")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
fig = go.Figure(go.Funnel(y=list(sums.index), x=sums.to_numpy(), marker_color=PALETTE[0],
textinfo="value+percent initial+percent previous")) # overall and step conversion
fig.show()
Needs pandas, numpy, plotly · reads funnel-demo.csv · app theme from the optional codesplash helper
# Funnel — Codesplash Chart Lab (recipe "funnel")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("funnel-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["stage"]] <- factor(df[["stage"]], levels = c("Visited", "Viewed product", "Added to cart", "Checkout", "Purchased"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
k <- as.character(df[["stage"]])
v <- rep(1, length(k)) # no value column: count rows
v[!is.finite(v)] <- 0
ok <- !is.na(k)
ord <- c(intersect(levels(df[["stage"]]), k[ok]), setdiff(unique(k[ok]), levels(df[["stage"]]))) # declared order first
sums <- tapply(v[ok], k[ok], sum)[ord]
f <- data.frame(stage = names(sums), value = as.numeric(sums))
f$overall <- f$value / f$value[1] # conversion from the first stage
f$step <- f$value / c(f$value[1], head(f$value, -1)) # conversion from the previous stage
f$y <- rev(seq_len(nrow(f))) # first stage on top
wmax <- max(f$value)
p <- ggplot(f) +
geom_rect(aes(xmin = -value / 2, xmax = value / 2, ymin = y - 0.36, ymax = y + 0.36), fill = cs_cat[1]) + # width ∝ value, centred
geom_text(aes(x = 0, y = y, label = format(round(value), big.mark = ",")), colour = "white", size = 2.8, fontface = "bold") +
geom_text(aes(x = wmax / 2 * 1.04, y = y, label = sprintf("%.1f%% of first · %.1f%% of previous", 100 * overall, 100 * step)), hjust = 0, size = 2.5) +
scale_y_continuous(breaks = f$y, labels = f$stage) +
scale_x_continuous(limits = c(-wmax / 2 * 1.05, wmax * 1.2)) +
labs(x = NULL, y = NULL) +
theme_cs +
theme(axis.text.x = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads funnel-demo.csv · app theme from the optional codesplashr helper
-- Funnel — Codesplash Chart Lab (recipe "funnel")-- controls: defaults-- value per stage (declared order) with overall and step conversion
WITH s AS (SELECT *, row_number() OVER () AS _row FROM read_csv('funnel-demo.csv')),
lv(level, rk) AS (VALUES ('Visited', 1), ('Viewed product', 2), ('Added to cart', 3), ('Checkout', 4), ('Purchased', 5)),
stages AS (
SELECT s."stage"::VARCHAR AS stage,
count(*) AS value,
coalesce(min(lv.rk), 1e9 + min(s._row)) AS ord
FROM s
LEFT JOIN lv ON lv.level = s."stage"::VARCHAR
WHERE s."stage" IS NOT NULL
GROUP BY 1
)
SELECT stage, value,
value / first_value(value) OVER (ORDER BY ord) AS overall_rate,
value / coalesce(lag(value) OVER (ORDER BY ord), value) AS step_rate,
coalesce(lag(value) OVER (ORDER BY ord) - value, 0) AS lost
FROM stages
ORDER BY ord;
Compare with 25% and 50%: those angles are the easiest to judge.
Use the legend for exact percentages.
1Callout 1: Largest first, starting at twelve o'clock.
2Callout 2: The centre shows the total.
3Callout 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
# Pie / donut — Codesplash Chart Lab (recipe "pie")# controls: donut=true, labels=true, top=6
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Pie(labels=s["label"], values=s["value"], sort=False, direction="clockwise", rotation=0, # from 12 o'clock
hole=0.58, marker=dict(colors=colors),
text=[f"{p:.0%}" if p >= 0.06 else "" for p in s["share"]], textinfo="text"))
fig.show()
Needs pandas, numpy, plotly · reads pie-demo.csv · app theme from the optional codesplash helper
# Pie / donut — Codesplash Chart Lab (recipe "pie")# controls: donut=true, labels=true, top=6
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pie-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["browser"]] <- factor(df[["browser"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
k <- as.character(df[["browser"]])
v <- rep(1, length(k)) # no value column: count rows
v[!is.finite(v)] <- 0
ok <- !is.na(k)
ord <- unique(k[ok]) # first appearance
sums <- tapply(v[ok], k[ok], sum)[ord]
s <- data.frame(label = names(sums), value = as.numeric(sums))
s <- s[s$value > 0, ]
s <- s[order(-s$value, s$label), ] # largest first, ties alphabetical
if (nrow(s) > 6) s <- rbind(head(s, 6 - 1), data.frame(label = "Other", value = sum(s$value[-seq_len(6 - 1)])))
s$share <- s$value / sum(s$value)
s$end <- cumsum(s$share)
s$start <- s$end - s$share
fill <- setNames(rep(cs_cat, length.out = nrow(s)), s$label)
fill[s$label == "Other"] <- "#9aa0a6"
legend <- sprintf("%s %.1f%%", s$label, 100 * s$share)
p <- ggplot(s) +
geom_rect(aes(xmin = 0.58, xmax = 1, ymin = start, ymax = end, fill = label), colour = "white", linewidth = 0.4) +
geom_text(aes(x = 0.79, y = (start + end) / 2, label = ifelse(share >= 0.06, sprintf("%.0f%%", 100 * share), "")), colour = "white", size = 2.8) + # labels on slices ≥ 6 %
scale_fill_manual(values = fill, breaks = s$label, labels = legend, name = NULL) +
scale_x_continuous(limits = c(0, 1)) +
coord_polar(theta = "y", start = 0, direction = 1) + # clockwise from 12 o'clock
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads pie-demo.csv · app theme from the optional codesplashr helper
-- Pie / donut — Codesplash Chart Lab (recipe "pie")-- controls: donut=true, labels=true, top=6-- shares per category: top 5 by value plus 'Other' (when there are more than 6)
WITH sums AS (
SELECT "browser"::VARCHAR AS label, count(*) AS value
FROM read_csv('pie-demo.csv') WHERE "browser" IS NOT NULL
GROUP BY 1 HAVING value > 0
),
ranked AS (SELECT *, row_number() OVER (ORDER BY value DESC, label) AS rk, count(*) OVER () AS k FROM sums),
pooled AS (
SELECT CASE WHEN k <= 6 OR rk < 6 THEN label ELSE 'Other' END AS label, sum(value) AS value, min(rk) AS rk
FROM ranked GROUP BY 1
)
SELECT label, value, value / sum(value) OVER () AS share
FROM pooled
ORDER BY rk;
Read the overall direction first, then the repeating ups and downs.
Compare series at the same date, and check the band for how uncertain each one is.
Look at what happens around marked events, without assuming they caused it.
1Callout 1: A series' peak; read it against the others at the same date.
2Callout 2: Band: the uncertainty or range around the line.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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)
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
PERIOD, BAND = "week", "ci"
series = [(lv, df[df["region"].astype(str) == lv]) for lv in freq_levels(df["region"], 8)]
fig = go.Figure()
for i, (name, d) in enumerate(series):
s = resample(d, "date", "sales", PERIOD)
col = PALETTE[i % len(PALETTE)]
if BAND != "none":
lo, hi = (s["lo"], s["hi"]) if BAND == "ci" else (s["min"], s["max"])
fig.add_scatter(x=s["t"], y=lo, mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=s["t"], y=hi, mode="lines", line_width=0, fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if len(series) > 1 else "solid")) # dash 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():
fig.add_shape(type="line", x0=e["date"], x1=e["date"], y0=0, y1=1, yref="paper", line=dict(color=REF, dash="dash", width=1))
fig.add_annotation(x=e["date"], y=1, yref="paper", text=f"{e["event"]} · {e["date"]:%Y-%m-%d}", showarrow=False, xanchor="left", yanchor="top", font_size=10)
fig.update_layout(xaxis_title="date (UTC)", yaxis_title="sales")
fig.show()
Needs pandas, numpy, plotly, scipy · reads line-demo.csv · app theme from the optional codesplash helper
# Line chart — Codesplash Chart Lab (recipe "line")# controls: period=week, band=ci, points=false, events=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("line-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
df[["event"]] <- factor(df[["event"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, 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)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "week"; band <- "ci" # without resampling, rows sharing a timestamp are averaged, no band
series <- lapply(stats::setNames(nm = freq_levels(df[["region"]], 8)), function(lv) df[as.character(df[["region"]]) %in% lv, , drop = FALSE])
stats_df <- do.call(rbind, lapply(names(series), function(nm) cbind(series = nm, resample_stats(series[[nm]][["date"]], series[[nm]][["sales"]], period))))
stats_df$series <- factor(stats_df$series, levels = names(series))
if (band == "minmax") { stats_df$lo <- stats_df$min; stats_df$hi <- stats_df$max }
p <- ggplot(stats_df, aes(t, mean, colour = series, fill = series)) +
{ if (band != "none") geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.15, colour = NA) } +
geom_line(aes(linetype = series), linewidth = 0.8) + # dash per series, as in the app
geom_vline(data = unique(df[!is.na(df[["event"]]) & df[["event"]] != "", c("date", "event")]), aes(xintercept = .data[["date"]]), colour = ref_col, linetype = "dashed") +
geom_text(data = unique(df[!is.na(df[["event"]]) & df[["event"]] != "", c("date", "event")]), aes(x = .data[["date"]], y = Inf, label = paste(.data[["event"]], format(.data[["date"]], "%Y-%m-%d"), sep = " · ")), hjust = -0.05, vjust = 1.5, size = 3, inherit.aes = FALSE) +
scale_colour_manual(values = cs_cat, name = "region") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, name = "region") +
labs(x = "date (UTC)", y = "sales") +
theme_cs
print(p)
Needs ggplot2 · reads line-demo.csv · app theme from the optional codesplashr helper
-- Line chart — Codesplash Chart Lab (recipe "line")-- controls: period=week, band=ci, points=false, events=true-- per-period statistics (UTC); CI = mean ± t(0.975, n − 1)·se is computed on the client
SELECT "region", date_trunc('week', "date") AS t,
count("sales") AS n, avg("sales") AS mean, stddev_samp("sales") AS sd,
stddev_samp("sales") / sqrt(count("sales")) AS se, min("sales") AS min, max("sales") AS max,
string_agg(DISTINCT "event", ', ') FILTER (WHERE "event" <> '') AS events
FROM read_csv('line-demo.csv')
WHERE "date" IS NOT NULL AND "sales" IS NOT NULL
GROUP BY ALL
ORDER BY ALL;
Where areas overlap, follow the edges: the series aren't stacked.
Check the baseline: a filled area implies a meaningful zero.
1Callout 1: This series' top edge is its value.
2Callout 2: Overlap: both series are measured from zero.
3Callout 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
# Area chart — Codesplash Chart Lab (recipe "area")# controls: period=week, zero=true, opacity=0.2
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
PERIOD = "week"
series = [(lv, df[df["platform"].astype(str) == lv]) for lv in freq_levels(df["platform"], 8)]
fig = go.Figure()
for i, (name, d) in enumerate(series):
s = resample(d, "day", "active_users", PERIOD)
col = PALETTE[i % len(PALETTE)]
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line_color=col, fill="tozeroy", fillcolor=rgba(col, 0.2))
fig.update_layout(xaxis_title="day (UTC)", yaxis_title="active_users")
fig.show()
Needs pandas, numpy, plotly, scipy · reads area-demo.csv · app theme from the optional codesplash helper
# Area chart — Codesplash Chart Lab (recipe "area")# controls: period=week, zero=true, opacity=0.2
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("area-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["day"]] <- as.POSIXct(df[["day"]], tz = "UTC")
df[["platform"]] <- factor(df[["platform"]], levels = c("Web", "App"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["platform"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, 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)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "week"
series <- lapply(stats::setNames(nm = freq_levels(df[["platform"]], 8)), function(lv) df[as.character(df[["platform"]]) %in% lv, , drop = FALSE])
stats_df <- do.call(rbind, lapply(names(series), function(nm) cbind(series = nm, resample_stats(series[[nm]][["day"]], series[[nm]][["active_users"]], period))))
stats_df$series <- factor(stats_df$series, levels = names(series))
stats_df$base <- 0 # filled down to zero: area ∝ value
p <- ggplot(stats_df, aes(t, mean, colour = series, fill = series)) +
geom_ribbon(aes(ymin = base, ymax = mean), alpha = 0.2, colour = NA) + # overlapping, not stacked
geom_line(linewidth = 0.7) +
scale_colour_manual(values = cs_cat, name = "platform") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, name = "platform") +
labs(x = "day (UTC)", y = "active_users") +
theme_cs
print(p)
Needs ggplot2 · reads area-demo.csv · app theme from the optional codesplashr helper
-- Area chart — Codesplash Chart Lab (recipe "area")-- controls: period=week, zero=true, opacity=0.2-- period mean per series (UTC); the area fills from zero
SELECT "platform", date_trunc('week', "day") AS t, avg("active_users") AS mean, count("active_users") AS n
FROM read_csv('area-demo.csv')
WHERE "day" IS NOT NULL AND "active_users" IS NOT NULL
GROUP BY ALL
ORDER BY ALL;
Read a flat run as a level holding until the next change.
Read a vertical jump as the moment the level changed.
Compare when series change, not only how much.
1Callout 1: A vertical drop: the value changed at this moment.
2Callout 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
# Step chart — Codesplash Chart Lab (recipe "step")# controls: mode=value, markers=false, zero=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
series = [(lv, df[df["sku"].astype(str) == lv]) for lv in freq_levels(df["sku"], 8)]
end = df["timestamp"].max()
fig = go.Figure()
for i, (name, d) in enumerate(series):
d = d.dropna(subset=["timestamp"] + (["on_hand"] if MODE != "count" else [])).sort_values("timestamp", kind="stable")
s = d.groupby("timestamp")["on_hand"].mean() if MODE == "value" else (d.groupby("timestamp")["on_hand"].sum().cumsum() if MODE == "cumsum" else d.groupby("timestamp").size().cumsum())
fig.add_scatter(x=list(s.index) + [end], y=list(s.to_numpy()) + [s.iloc[-1]], mode="lines", line_shape="hv", name=name, line_color=PALETTE[i % len(PALETTE)])
fig.update_yaxes(rangemode="tozero")
fig.update_layout(xaxis_title="timestamp (UTC)")
fig.show()
Needs pandas, numpy, plotly · reads step-demo.csv · app theme from the optional codesplash helper
# Step chart — Codesplash Chart Lab (recipe "step")# controls: mode=value, markers=false, zero=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("step-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["timestamp"]] <- as.POSIXct(df[["timestamp"]], tz = "UTC")
df[["sku"]] <- factor(df[["sku"]], levels = c("A-100", "B-220"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["sku"]], "cs_declared") <- TRUE # stored level order
mode <- "value" # "value" (step-after), "cumsum" or "count" (cumulative rows)
series <- lapply(stats::setNames(nm = freq_levels(df[["sku"]], 8)), function(lv) df[as.character(df[["sku"]]) %in% lv, , drop = FALSE])
end <- max(df[["timestamp"]], na.rm = TRUE) # the last level extends to the end of the axis
steps <- do.call(rbind, lapply(names(series), function(nm) {
d <- series[[nm]]
d <- d[!is.na(d[["timestamp"]]) & (mode == "count" | !is.na(d[["on_hand"]])), , drop = FALSE]
d <- d[order(d[["timestamp"]]), , drop = FALSE]
t <- d[["timestamp"]]
v <- switch(mode, value = tapply(d[["on_hand"]], t, mean), cumsum = cumsum(tapply(d[["on_hand"]], t, sum)), count = cumsum(tapply(t, t, length)))
tt <- sort(unique(t))
data.frame(series = nm, t = c(tt, end), v = c(as.numeric(v), utils::tail(as.numeric(v), 1)))
}))
steps$series <- factor(steps$series, levels = names(series))
p <- ggplot(steps, aes(t, v, colour = series)) +
geom_step(direction = "hv", linewidth = 0.8) + # right-continuous (step-after)
expand_limits(y = 0) +
scale_colour_manual(values = cs_cat, name = "sku") +
labs(x = "timestamp (UTC)", y = if (mode == "value") "on_hand" else if (mode == "cumsum") "cumulative on_hand" else "cumulative rows") +
theme_cs
print(p)
Needs ggplot2 · reads step-demo.csv · app theme from the optional codesplashr helper
-- Step chart — Codesplash Chart Lab (recipe "step")-- controls: mode=value, markers=false, zero=true-- one level per timestamp (rows sharing a timestamp averaged) plus the cumulative sum and row count
SELECT "sku", "timestamp" AS t,
avg("on_hand") AS value,
sum(sum("on_hand")) OVER (PARTITION BY "sku" ORDER BY "timestamp") AS cumsum,
sum(count(*)) OVER (PARTITION BY "sku" ORDER BY "timestamp") AS cumulative_rows
FROM read_csv('step-demo.csv')
WHERE "timestamp" IS NOT NULL AND "on_hand" IS NOT NULL
GROUP BY "sku", "timestamp"
ORDER BY "sku", "timestamp";
Compare shapes across panels, all with the same time axis.
With a shared y scale, compare levels too; with free scales, compare only shapes.
Read the change in each panel's corner.
1Callout 1: Panel title and its overall change.
2Callout 2: Same scale: this series sits higher than its neighbours.
3Callout 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
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")# controls: free=false, period=none, color=panel
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)]
frames = [(name, resample(d, "month", "revenue_k", PERIOD)) for name, d in series]
rows, cols = grid_shape(len(frames))
titles = [f"{name} ({s['mean'].iloc[-1] - s['mean'].iloc[0]:+.3g})" for name, s in frames]
fig = make_subplots(rows=rows, cols=cols, shared_xaxes=True, shared_yaxes="all", subplot_titles=titles, vertical_spacing=0.12)
for i, (name, s) in enumerate(frames):
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line_color=PALETTE[i % len(PALETTE)], showlegend=False, row=i // cols + 1, col=i % cols + 1)
fig.update_layout(height=220 * rows, title_text="revenue_k by product_line")
fig.show()
Needs pandas, numpy, plotly, scipy · reads small-multiples-demo.csv · app theme from the optional codesplash helper
# Small multiples — Codesplash Chart Lab (recipe "small-multiples")# controls: free=false, period=none, color=panel
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("small-multiples-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["product_line"]] <- factor(df[["product_line"]], levels = c("Analytics", "Compute", "Storage", "Security", "Networking", "Support"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["product_line"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, 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)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "none"
series <- lapply(stats::setNames(nm = freq_levels(df[["product_line"]], 12)), function(lv) df[as.character(df[["product_line"]]) %in% lv, , drop = FALSE])
panels <- do.call(rbind, lapply(names(series), function(nm) cbind(panel = nm, resample_stats(series[[nm]][["month"]], series[[nm]][["revenue_k"]], period))))
change <- tapply(panels$mean, panels$panel, function(v) utils::tail(v, 1) - v[1]) # first → last plotted value
labels <- stats::setNames(sprintf("%s (%+.3g)", names(series), change[names(series)]), names(series))
panels$panel <- factor(panels$panel, levels = names(series), labels = labels[names(series)])
k <- length(series)
cols <- if (k <= 3) max(1, k) else if (k == 4) 2 else if (k <= 6) 3 else 4 # the app's panel grid
p <- ggplot(panels, aes(t, mean, colour = panel)) +
geom_line(linewidth = 0.6, show.legend = FALSE) +
scale_colour_manual(values = rep(cs_cat, length.out = k)) +
facet_wrap(~panel, ncol = cols, scales = "fixed") + # shared y scale
labs(x = NULL, y = "revenue_k", title = "revenue_k by product_line") +
theme_cs
print(p)
Needs ggplot2 · reads small-multiples-demo.csv · app theme from the optional codesplashr helper
-- Small multiples — Codesplash Chart Lab (recipe "small-multiples")-- controls: free=false, period=none, color=panel-- per panel: the plotted (period-mean) series, with the first → last change for the header
WITH s AS (
SELECT "product_line" AS panel, "month" AS t, avg("revenue_k") AS mean
FROM read_csv('small-multiples-demo.csv')
WHERE "month" IS NOT NULL AND "revenue_k" IS NOT NULL AND "product_line" IS NOT NULL
GROUP BY ALL
)
SELECT panel, t, mean,
last_value(mean) OVER w - first_value(mean) OVER w AS change
FROM s
WINDOW w AS (PARTITION BY panel ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY panel, t;
Look for columns or rows that stand out: holidays and weekly rhythms.
Blank cells mean no data, which is different from zero.
1Callout 1: Rows are weekdays.
2Callout 2: A block of darker days.
3Callout 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
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")# controls: agg=sum, scale=linear, years=3
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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":
daily = daily.rank(pct=True)
years = sorted(daily.index.year.unique())[-YEARS:]
fig = make_subplots(rows=len(years), cols=1, subplot_titles=[str(y) for y in years], vertical_spacing=0.08)
for i, year in enumerate(years):
grid, _ = calendar_grid(daily, year)
fig.add_heatmap(z=grid, y=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], zmin=0,
zmax=1 if SCALE == "quantile" else daily.max(), showscale=i == 0, xgap=1, ygap=1, row=i + 1, col=1)
fig.update_yaxes(autorange="reversed", row=i + 1, col=1)
fig.update_layout(height=170 * len(years))
fig.show()
Needs pandas, numpy, plotly · reads calendar-heatmap-demo.csv · app theme from the optional codesplash helper
# Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")# controls: agg=sum, scale=linear, years=3
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("calendar-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
agg <- "sum"; scale <- "linear"; years_shown <- 3
t <- as.POSIXct(df[["date"]], tz = "UTC")
ok <- !is.na(t) & !is.na(df[["commits"]])
day <- as.Date(format(t[ok], "%Y-%m-%d", tz = "UTC")) # UTC calendar day
daily <- if (agg == "count") tapply(day, day, length) else tapply(df[["commits"]][ok], day, if (agg == "mean") mean else sum)
daily <- stats::setNames(as.numeric(daily), names(daily))
if (scale == "quantile") daily <- rank(daily) / length(daily) # rank among days with data
all_days <- seq(min(as.Date(names(daily))), max(as.Date(names(daily))), by = "day") # empty days inside the range
cal <- data.frame(day = all_days, value = unname(daily[format(all_days)]))
cal$year <- as.integer(format(cal$day, "%Y"))
cal <- cal[cal$year %in% utils::tail(sort(unique(cal$year)), years_shown), ]
jan1 <- as.Date(sprintf("%d-01-01", cal$year))
origin <- jan1 - (as.POSIXlt(jan1)$wday + 6) %% 7 # Monday on or before 1 January
cal$week <- as.integer(cal$day - origin) %/% 7
cal$dow <- factor((as.POSIXlt(cal$day)$wday + 6) %% 7, levels = 0:6, labels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
p <- ggplot(cal, aes(week, dow, fill = value)) +
geom_tile(colour = "white", linewidth = 0.3) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], na.value = grey_col, limits = c(0, if (scale == "quantile") 1 else max(daily)), name = if (agg == "count") "rows" else paste(agg, "commits")) +
scale_y_discrete(limits = rev) +
facet_wrap(~year, ncol = 1) +
coord_equal() + labs(x = "week of year", y = NULL) +
theme_cs + theme(panel.grid = element_blank())
print(p)
Needs ggplot2 · reads calendar-heatmap-demo.csv · app theme from the optional codesplashr helper
-- Calendar heatmap — Codesplash Chart Lab (recipe "calendar-heatmap")-- controls: agg=sum, scale=linear, years=3-- one cell per UTC day: weeks counted from the Monday on or before 1 January, ISO weekday rows
WITH d AS (
SELECT "date"::DATE AS day, sum("commits") AS value, count(*) AS n
FROM read_csv('calendar-heatmap-demo.csv')
WHERE "date" IS NOT NULL AND "commits" IS NOT NULL
GROUP BY ALL
)
SELECT day, year(day) AS year, isodow(day) - 1 AS dow,
datediff('day', make_date(year(day), 1, 1) - to_days(CAST(isodow(make_date(year(day), 1, 1)) - 1 AS INTEGER)), day) // 7 AS week,
value, n
FROM d
ORDER BY day;
Needs ggplot2 · reads dow-hour-demo.csv · app theme from the optional codesplashr helper
-- Weekday × hour heatmap — Codesplash Chart Lab (recipe "dow-hour")-- controls: agg=count-- 7 × 24 grid by UTC weekday (Monday = 0) and hour, including empty cells
WITH r AS (
SELECT isodow("started_at") - 1 AS dow, hour("started_at") AS hour, "session_minutes" AS v
FROM read_csv('dow-hour-demo.csv') WHERE "started_at" IS NOT NULL
)
SELECT g.dow, h.hour, count(r.dow) AS n, avg(r.v) AS mean
FROM range(7) g(dow) CROSS JOIN range(24) h(hour)
LEFT JOIN r ON r.dow = g.dow AND r.hour = h.hour
GROUP BY ALL
ORDER BY ALL;
Needs ggplot2 · reads seasonal-subseries-demo.csv · app theme from the optional codesplashr helper
-- Seasonal subseries (cycle plot) — Codesplash Chart Lab (recipe "seasonal-subseries")-- controls: points=true-- monthly means per year and, per calendar month, the mean of those means
WITH m AS (
SELECT year("month") AS year, month("month") AS month, avg("passengers_k") AS value
FROM read_csv('seasonal-subseries-demo.csv') WHERE "month" IS NOT NULL AND "passengers_k" IS NOT NULL
GROUP BY ALL
)
SELECT month, year, value, avg(value) OVER (PARTITION BY month) AS month_mean
FROM m
ORDER BY month, year;
Each point is one value against the value k steps earlier.
A tight diagonal: today's value is close to the earlier one (strong autocorrelation).
A shapeless cloud: the series looks random at that lag.
1Callout 1: A tight diagonal: strong dependence at this lag.
2Callout 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
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")# controls: lag=1, colorTime=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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:]
r = np.corrcoef(prev, cur)[0, 1]
fig = go.Figure(go.Scatter(x=prev, y=cur, mode="markers", marker=dict(size=6, opacity=0.8, color=np.arange(len(cur)), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]])))
lo, hi = min(prev.min(), cur.min()), max(prev.max(), cur.max())
fig.add_scatter(x=[lo, hi], y=[lo, hi], mode="lines", line=dict(color=REF, dash="dash"), showlegend=False)
fig.update_layout(title=f"lag {k}: r = {r:.3f}", xaxis_title=f"temp_c[t − {k}]", yaxis_title="temp_c[t]", showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads lag-plot-demo.csv · app theme from the optional codesplash helper
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")# controls: lag=1, colorTime=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("lag-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[!is.na(df[["date"]]) & !is.na(df[["temp_c"]]), , drop = FALSE]
d <- d[order(d[["date"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["temp_c"]]
k <- max(1, min(1, max(1, length(v) - 2)))
pairs <- data.frame(prev = utils::head(v, -k), cur = utils::tail(v, -k))
pairs$t <- seq_len(nrow(pairs))
r <- stats::cor(pairs$prev, pairs$cur) # Pearson r of the plotted pairs
p <- ggplot(pairs, aes(prev, cur)) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_point(aes(colour = t), size = 1.4, alpha = 0.8) +
scale_colour_gradient(low = seq_ramp[1], high = seq_ramp[2], guide = "none") +
labs(x = paste0("temp_c", "[t − ", k, "]"), y = "temp_c[t]", title = sprintf("lag %d: r = %.3f", k, r)) +
coord_equal() + theme_cs
print(p)
Needs ggplot2 · reads lag-plot-demo.csv · app theme from the optional codesplashr helper
-- Lag plot — Codesplash Chart Lab (recipe "lag-plot")-- controls: lag=1, colorTime=true-- lag-1 pairs in time order and their Pearson r
WITH s AS (
SELECT "temp_c" AS cur, lag("temp_c", 1) OVER (ORDER BY "date") AS prev
FROM read_csv('lag-plot-demo.csv')
WHERE "temp_c" IS NOT NULL AND "date" IS NOT NULL
)
SELECT prev, cur, corr(prev, cur) OVER () AS r
FROM s
WHERE prev IS NOT NULL;
Read each bar as the correlation between the series and itself at that lag.
Bars outside the dashed band are larger than noise would usually give.
Slowly fading ACF suggests a trend; a spike at the seasonal lag suggests a season; PACF cut-offs suggest an AR order.
1Callout 1: Lag 1: the correlation with the previous value.
2Callout 2: Dashed band: the range for white noise.
3Callout 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
# ACF & PACF — Codesplash Chart Lab (recipe "acf")# controls: show=both, lagMax=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.stats import norm
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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))
panels = []
panels.append(("ACF", np.arange(L + 1), acf(v, L)))
panels.append(("PACF", np.arange(1, L + 1), pacf(v, L)))
fig = make_subplots(rows=len(panels), cols=1, shared_xaxes=True, subplot_titles=[p[0] for p in panels])
for i, (name, lags, vals) in enumerate(panels):
fig.add_bar(x=lags, y=vals, width=0.25, marker_color=[GREY if k == 0 else PALETTE[0] for k in lags], showlegend=False, row=i + 1, col=1)
for b in (bound, -bound):
fig.add_hline(y=b, line=dict(color=REF, dash="dash", width=1), row=i + 1, col=1)
fig.update_layout(title=f"Autocorrelation of demand (n = {len(v)})", height=260 * len(panels))
fig.show()
Needs pandas, numpy, plotly, scipy · reads acf-demo.csv · app theme from the optional codesplash helper
# ACF & PACF — Codesplash Chart Lab (recipe "acf")# controls: show=both, lagMax=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("acf-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[!is.na(df[["month"]]) & !is.na(df[["demand"]]), , drop = FALSE]
d <- d[order(d[["month"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["demand"]]
L <- max(1, min(length(v) - 1, floor(10 * log10(length(v))))) # R default
bound <- stats::qnorm(0.975) / sqrt(length(v)) # ±qnorm(0.975)/√n white-noise limits
panels <- rbind(
data.frame(panel = "ACF", lag = 0:L, value = as.numeric(stats::acf(v, lag.max = L, plot = FALSE, demean = TRUE)$acf)),
data.frame(panel = "PACF", lag = 1:L, value = as.numeric(stats::pacf(v, lag.max = L, plot = FALSE)$acf)) # Durbin–Levinson
)
panels$panel <- factor(panels$panel, levels = c("ACF", "PACF"))
p <- ggplot(panels, aes(lag, value)) +
geom_hline(yintercept = 0, colour = ref_col) +
geom_hline(yintercept = c(-bound, bound), colour = ref_col, linetype = "dashed") +
geom_segment(aes(xend = lag, yend = 0, colour = lag == 0), linewidth = 1, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = grey_col)) + # lag 0 = 1 in grey
facet_wrap(~panel, ncol = 1) +
labs(x = "lag (observations)", y = NULL, title = sprintf("Autocorrelation of demand (n = %d)", length(v))) +
theme_cs
print(p)
Needs ggplot2 · reads acf-demo.csv · app theme from the optional codesplashr helper
-- ACF & PACF — Codesplash Chart Lab (recipe "acf")-- controls: show=both, lagMax=0-- ACF (R acf, denominator n at every lag) by a self-join on the time order; PACF needs the client
WITH s AS (
SELECT row_number() OVER (ORDER BY "month") AS i, "demand"::DOUBLE AS v
FROM read_csv('acf-demo.csv') WHERE "demand" IS NOT NULL AND "month" IS NOT NULL
),
m AS (SELECT avg(v) AS mean, count(*) AS n FROM s),
d AS (SELECT i, v - mean AS dev FROM s, m),
tot AS (SELECT sum(dev * dev) AS c0 FROM d),
lags AS (SELECT i - 1 AS k FROM s, m WHERE i - 1 <= greatest(1, least(n - 1, floor(10 * log10(n))))::INTEGER)
SELECT lags.k AS lag, sum(a.dev * b.dev) / any_value(tot.c0) AS acf,
1.959963984540054 / sqrt(any_value(m.n)) AS bound -- qnorm(0.975)/√n
FROM lags
JOIN d a ON true
JOIN d b ON b.i = a.i + lags.k
CROSS JOIN tot
CROSS JOIN m
GROUP BY lags.k
ORDER BY lags.k;
Read the band as recent variability: a wider band means a more volatile period.
Check the flagged points: they break from recent behaviour.
1Callout 1: The rolling mean: the local level.
2Callout 2: Band: a wider band means higher recent variability.
3Callout 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
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")# controls: window=30, k=2, outliers=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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, SD on n − 1
t = d["day"].to_numpy()
fig = go.Figure()
fig.add_scatter(x=t, y=mean - k * sd, mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=t, y=mean + k * sd, mode="lines", line_width=0, fill="tonexty", fillcolor="rgba(41,113,198,0.15)", name=f"± {k}·SD")
fig.add_scatter(x=t, y=v, mode="lines", line=dict(color=GREY, width=1), name="p95_ms")
fig.add_scatter(x=t, y=mean, mode="lines", line=dict(color=PALETTE[0], width=2), name=f"rolling mean ({w})")
out = (np.abs(v - mean) > k * sd).to_numpy()
fig.add_scatter(x=t[out], y=v[out], mode="markers", marker=dict(color=PALETTE[3], size=7), name="outside band")
fig.show()
Needs pandas, numpy, plotly · reads rolling-demo.csv · app theme from the optional codesplash helper
# Rolling statistics — Codesplash Chart Lab (recipe "rolling")# controls: window=30, k=2, outliers=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("rolling-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["day"]] <- as.POSIXct(df[["day"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[!is.na(df[["day"]]) & !is.na(df[["p95_ms"]]), , drop = FALSE]
d <- d[order(d[["day"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["p95_ms"]]
w <- max(2, min(30, length(v))); k <- 2
roll <- function(v, w, f) vapply(seq_along(v), function(i) if (i < w) NA_real_ else f(v[(i - w + 1):i]), numeric(1))
r <- data.frame(t = d[["day"]], v = v, mean = roll(v, w, mean), sd = roll(v, w, stats::sd)) # trailing windows, SD on n - 1
r$out <- !is.na(r$mean) & abs(r$v - r$mean) > k * r$sd
p <- ggplot(r, aes(t)) +
geom_ribbon(aes(ymin = mean - k * sd, ymax = mean + k * sd), fill = cs_cat[1], alpha = 0.15, na.rm = TRUE) +
geom_line(aes(y = v), colour = grey_col) +
geom_line(aes(y = mean), colour = cs_cat[1], linewidth = 0.9, na.rm = TRUE) +
geom_point(data = function(d) d[d$out, ], aes(y = v), colour = cs_cat[4], size = 1.6) +
labs(x = "day", y = "p95_ms", subtitle = sprintf("rolling mean and ±%s·SD over %d observations", k, w)) +
theme_cs
print(p)
Needs ggplot2 · reads rolling-demo.csv · app theme from the optional codesplashr helper
-- Rolling statistics — Codesplash Chart Lab (recipe "rolling")-- controls: window=30, k=2, outliers=true-- trailing window of 30 observations (complete windows only), SD on n − 1, band ± 2·SD
WITH s AS (
SELECT "day" AS t, "p95_ms" AS v,
count(*) OVER w AS n_w, avg("p95_ms") OVER w AS mean, stddev_samp("p95_ms") OVER w AS sd
FROM read_csv('rolling-demo.csv')
WHERE "p95_ms" IS NOT NULL AND "day" IS NOT NULL
WINDOW w AS (ORDER BY "day" ROWS BETWEEN 29 PRECEDING AND CURRENT ROW)
)
SELECT t, v,
CASE WHEN n_w = 30 THEN mean END AS rolling_mean,
CASE WHEN n_w = 30 THEN sd END AS rolling_sd,
n_w = 30 AND abs(v - mean) > 2 * sd AS outside_band
FROM s;
Use the strip at the bottom to see the whole series.
Drag the window on the strip to choose the detail above.
Check the date range and point count in the corner.
1Callout 1: Detail: the selected window.
2Callout 2: The draggable window on the overview.
3Callout 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
# Zoom with overview — Codesplash Chart Lab (recipe "zoom-overview")# controls: initialDays=180, area=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])
d = df.dropna(subset=["date", "close"]).sort_values("date")
end = d["date"].max()
start = end - pd.Timedelta(days=180)
fig = go.Figure(go.Scatter(x=d["date"], y=d["close"], mode="lines", line_color=PALETTE[0], fill="tozeroy"))
# plotly's range slider is the overview; drag it to choose the detail window
fig.update_xaxes(range=[start, end], rangeslider_visible=True)
fig.update_yaxes(autorange=True, fixedrange=False, title_text="close")
fig.show()
Needs pandas, numpy, plotly · reads zoom-overview-demo.csv · app theme from the optional codesplash helper
# Zoom with overview — Codesplash Chart Lab (recipe "zoom-overview")# controls: initialDays=180, area=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("zoom-overview-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is # installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
d <- df[!is.na(df[["date"]]) & !is.na(df[["close"]]), , drop = FALSE]
d <- d[order(d[["date"]]), , drop = FALSE]
end <- max(d[["date"]]); start <- end - 180 * 86400 # the last N days
win <- d[d[["date"]] >= start, , drop = FALSE]
detail <- ggplot(win, aes(.data[["date"]], .data[["close"]])) +
geom_ribbon(aes(ymin = min(.data[["close"]]), ymax = .data[["close"]]), fill = cs_cat[1], alpha = 0.15) +
geom_line(colour = cs_cat[1]) + labs(x = NULL, y = "close") + theme_cs
overview <- ggplot(d, aes(.data[["date"]], .data[["close"]])) +
annotate("rect", xmin = start, xmax = end, ymin = -Inf, ymax = Inf, fill = cs_cat[1], alpha = 0.2) +
geom_line(colour = ref_col, linewidth = 0.3) + labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.y = element_blank())
arrange(list(detail, overview), layout = matrix(1:2, 2), heights = c(3, 1))
Needs ggplot2 · reads zoom-overview-demo.csv · app theme from the optional codesplashr helper
-- Zoom with overview — Codesplash Chart Lab (recipe "zoom-overview")-- controls: initialDays=180, area=true-- the detail window: the last 180 days of the series (the overview is the full table)
SELECT "date", "close"
FROM read_csv('zoom-overview-demo.csv')
WHERE "close" IS NOT NULL
AND "date" >= (SELECT max("date") FROM read_csv('zoom-overview-demo.csv')) - INTERVAL 180 DAY
ORDER BY "date";
2Callout 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
# Series with break marker — Codesplash Chart Lab (recipe "series-line")# controls: marker=0, points=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = ordered(df, X, [Y, G])
groups = levels_of(d[G]) if G else [None]
fig = go.Figure()
for i, g in enumerate(groups):
s = d if g is None else d[d[G].astype(str) == str(g)]
fig.add_scatter(x=time_of(s, X), y=s[Y], mode="lines+markers" if POINTS and i == 0 else "lines", name=str(g) if g is not None else Y,
line=dict(color=PALETTE[i % len(PALETTE)], width=1.6), marker=dict(size=4))
first = d if G is None else d[d[G].astype(str) == str(groups[0])]
if 0 < MARKER <= len(first):
fig.add_vline(x=time_of(first, X).iloc[MARKER - 1], line=dict(color=REF, dash="dash"), annotation_text="estimated break")
fig.update_layout(xaxis_title="month", yaxis_title=Y, showlegend=bool(G))
fig.show()
Needs pandas, numpy, plotly · reads series-line-demo.csv · app theme from the optional codesplash helper
# Series with break marker — Codesplash Chart Lab (recipe "series-line")# controls: marker=0, points=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("series-line-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "month"
y_col <- "index"
g_col <- NULL
MARKER <- 0 # break after this position (0 = none)
POINTS <- FALSE
d <- ordered(df, x_col, c(y_col, g_col))
d$t <- time_of(d, x_col)
if (!is.null(g_col) && is.null(x_col)) d$t <- ave(seq_len(nrow(d)), as.character(d[[g_col]]), FUN = seq_along) # each series' own positions
first <- if (is.null(g_col)) d else d[as.character(d[[g_col]]) == levels_of(d[[g_col]])[1], , drop = FALSE]
p <- ggplot(d, aes(t, .data[[y_col]])) +
{ if (is.null(g_col)) geom_line(colour = cs_cat[1], linewidth = 0.8) else geom_line(aes(colour = factor(.data[[g_col]], levels = levels_of(.data[[g_col]]))), linewidth = 0.8) } +
{ if (POINTS) geom_point(data = first, colour = cs_cat[1], size = 0.8) } +
{ if (MARKER > 0 && MARKER <= nrow(first)) geom_vline(xintercept = first$t[MARKER], colour = ref_col, linetype = "dashed") } +
scale_colour_manual(values = cs_cat, name = NULL) + labs(x = "month", y = y_col) + theme_cs
print(p)
Needs ggplot2 · reads series-line-demo.csv · app theme from the optional codesplashr helper
Read Trend for the long-run direction and Seasonal for the repeating shape.
Read Remainder last: structure left there means the decomposition missed something.
1Callout 1: Observed: the series as measured.
2Callout 2: Trend: the long-run path.
3Callout 3: Seasonal: the repeating shape.
4Callout 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
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")# controls: multiplicative=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
from plotly.subplots import make_subplots
d = ordered(df, X, [OBS, TR, SE, RE])
t = time_of(d, X)
fig = make_subplots(rows=4, cols=1, shared_xaxes=True, subplot_titles=["Observed", "Trend", "Seasonal", "Remainder"])
fig.add_scatter(x=t, y=d[OBS], mode="lines", line=dict(color="black", width=1.2), row=1, col=1)
fig.add_scatter(x=t, y=d[TR], mode="lines", line=dict(color=PALETTE[0], width=1.6), row=2, col=1)
fig.add_scatter(x=t, y=d[SE], mode="lines", line=dict(color=PALETTE[0], width=1.6), row=3, col=1)
base = 1.0 if MULT else 0.0
fig.add_bar(x=t, y=d[RE] - base, base=base, marker_color=PALETTE[0], row=4, col=1)
fig.update_layout(showlegend=False, height=650)
fig.show()
Needs pandas, numpy, plotly · reads stl-decomposition-demo.csv · app theme from the optional codesplash helper
# Seasonal decomposition — Codesplash Chart Lab (recipe "stl-decomposition")# controls: multiplicative=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("stl-decomposition-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "month"
obs <- "sales"
tr <- "trend"
se <- "seasonal"
re <- "remainder"
MULT <- FALSE
d <- ordered(df, x_col, c(obs, tr, se, re))
t <- time_of(d, x_col)
panel <- c("Observed", "Trend", "Seasonal", "Remainder")
long <- data.frame(t = rep(t, 4), value = c(d[[obs]], d[[tr]], d[[se]], d[[re]]), panel = factor(rep(panel, each = nrow(d)), levels = panel))
base <- if (MULT) 1 else 0
p <- ggplot(long, aes(t, value)) +
geom_line(data = long[long$panel != "Remainder", ], colour = cs_cat[1], linewidth = 0.7) +
geom_segment(data = long[long$panel == "Remainder", ], aes(xend = t, y = base, yend = value), colour = cs_cat[1], alpha = 0.7) +
facet_wrap(~panel, ncol = 1, scales = "free_y") + labs(x = "month", y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads stl-decomposition-demo.csv · app theme from the optional codesplashr helper
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
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")# controls: horizon=1, loss=squared
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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]
lim = float(np.nanmax(np.abs(M))) if np.isfinite(M).any() else 1.0
fig = go.Figure(go.Heatmap(z=M, x=FORECASTS, y=FORECASTS, colorscale="RdBu", zmin=-lim, zmax=lim, text=np.round(M, 2), texttemplate="%{text}"))
fig.update_layout(yaxis_autorange="reversed", xaxis_title="compared with", yaxis_title="forecast")
fig.show()
Needs pandas, numpy, plotly, scipy · reads dm-matrix-demo.csv · app theme from the optional codesplash helper
# Diebold–Mariano matrix — Codesplash Chart Lab (recipe "dm-matrix")# controls: horizon=1, loss=squared
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("dm-matrix-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
actual_col <- "actual"
forecasts <- c("model A", "model B", "model C")
H <- 1
LOSS <- "squared"
dm_hln <- function(y, a, b, h = 1, loss = "squared") {
d <- if (loss == "squared") (y - a)^2 - (y - b)^2 else abs(y - a) - abs(y - b)
n <- length(d)
dc <- d - mean(d)
v <- sum(vapply(0:(h - 1), function(k) (if (k == 0) 1 else 2) * sum(dc[(k + 1):n] * dc[1:(n - k)]) / n, 0)) / n
if (!(v > 0)) return(0)
mean(d) / sqrt(v) * sqrt((n + 1 - 2 * h + h * (h - 1) / n) / n)
}
d <- df[stats::complete.cases(df[, c(actual_col, forecasts)]), , drop = FALSE]
grid <- expand.grid(row = forecasts, col = forecasts, stringsAsFactors = FALSE)
grid$dm <- mapply(function(a, b) if (a == b) NA else dm_hln(d[[actual_col]], d[[a]], d[[b]], H, LOSS), grid$row, grid$col)
lim <- max(abs(grid$dm), na.rm = TRUE)
p <- ggplot(grid, aes(factor(col, levels = forecasts), factor(row, levels = rev(forecasts)), fill = dm)) + geom_tile(colour = "white") +
geom_text(aes(label = ifelse(is.na(dm), "", sprintf("%.2f", dm))), size = 3) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], limits = c(-lim, lim), na.value = grey_col, name = "DM") +
labs(x = "compared with", y = "forecast") + theme_cs
print(p)
Needs ggplot2 · reads dm-matrix-demo.csv · app theme from the optional codesplashr helper
Read the curve as the rank-sum contrast between before and after each date.
The largest absolute value marks the most probable change.
Crossing the dashed line means the change is beyond chance at that level.
1Callout 1: The largest |U|: the most likely change point.
2Callout 2: The significance limit.
3Callout 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
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")# controls: alpha=0.05
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
K, loc = np.abs(u).max(), int(np.argmax(np.abs(u)))
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)
t = time_of(d, X).iloc[: n - 1]
fig = go.Figure(go.Scatter(x=t, y=u, mode="lines", line=dict(color=PALETTE[0])))
fig.add_hrect(y0=-crit, y1=crit, fillcolor=GREY, opacity=0.3, line_width=0)
fig.add_scatter(x=[t.iloc[loc]], y=[u[loc]], mode="markers", marker=dict(color="#ce5342", size=9), showlegend=False)
fig.update_layout(title=f"Pettitt K = {K:.0f}, p ≈ {p:.3g}", xaxis_title="month", yaxis_title="U_t", showlegend=False)
fig.show()
Needs pandas, numpy, plotly, scipy · reads pettitt-u-demo.csv · app theme from the optional codesplash helper
# Pettitt's change-point curve — Codesplash Chart Lab (recipe "pettitt-u")# controls: alpha=0.05
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pettitt-u-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "month"
y_col <- "level"
ALPHA <- 0.05
d <- ordered(df, x_col, y_col)
v <- d[[y_col]]
n <- length(v)
u <- 2 * cumsum(rank(v))[1:(n - 1)] - seq_len(n - 1) * (n + 1) # as trend::pettitt.test
K <- max(abs(u))
loc <- which.max(abs(u))
pv <- min(1, 2 * exp(-6 * K^2 / (n^3 + n^2)))
crit <- sqrt(-log(ALPHA / 2) * (n^3 + n^2) / 6)
pu <- data.frame(t = time_of(d, x_col)[1:(n - 1)], u = u)
p <- ggplot(pu, aes(t, u)) + annotate("rect", xmin = -Inf, xmax = Inf, ymin = -crit, ymax = crit, fill = grey_col, alpha = 0.3) +
geom_hline(yintercept = c(-crit, crit), colour = ref_col, linetype = "dashed") + geom_line(colour = cs_cat[1]) +
geom_point(data = pu[loc, ], colour = "#ce5342", size = 2.5) +
labs(x = "month", y = "U_t", title = sprintf("Pettitt K = %.0f, p ≈ %.3g", K, pv)) + theme_cs
print(p)
Needs ggplot2 · reads pettitt-u-demo.csv · app theme from the optional codesplashr helper
Read the dashed lines as the estimated change dates.
Compare levels and whether variability differs across segments.
1Callout 1: A dashed line: an estimated change.
2Callout 2: This segment's mean.
3Callout 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
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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()
fig = go.Figure(go.Scatter(x=t, y=d[Y], mode="lines", line=dict(color=PALETTE[0], width=1.2), name=Y))
for r, g in d.groupby(run, sort=True):
tt = t[g.index]
fig.add_scatter(x=[tt.iloc[0], tt.iloc[-1]], y=[g[Y].mean()] * 2, mode="lines", line=dict(color=PALETTE[3 % len(PALETTE)], width=3), showlegend=False)
fig.update_layout(xaxis_title="week", yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads segment-means-demo.csv · app theme from the optional codesplash helper
# Series with segment means — Codesplash Chart Lab (recipe "segment-means")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("segment-means-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["week"]] <- as.POSIXct(df[["week"]], tz = "UTC")
df[["segment"]] <- factor(df[["segment"]], levels = c("1", "2", "3"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "week"
y_col <- "level"
seg_col <- "segment"
d <- ordered(df, x_col, c(y_col, seg_col))
d$t <- time_of(d, x_col)
seg <- if (is.null(seg_col)) rep("1", nrow(d)) else as.character(d[[seg_col]])
d$run <- cumsum(c(TRUE, seg[-1] != seg[-length(seg)])) # consecutive runs of the same label
runs <- do.call(rbind, lapply(split(d, d$run), function(g) data.frame(t0 = g$t[1], t1 = g$t[nrow(g)], mean = mean(g[[y_col]]))))
p <- ggplot(d, aes(t, .data[[y_col]])) + geom_line(colour = cs_cat[1], alpha = 0.7) +
geom_segment(data = runs, aes(x = t0, xend = t1, y = mean, yend = mean), colour = cs_cat[min(4, length(cs_cat))], linewidth = 1.3, inherit.aes = FALSE) +
labs(x = "week", y = y_col) + theme_cs
print(p)
Needs ggplot2 · reads segment-means-demo.csv · app theme from the optional codesplashr helper
Read the line as the coefficient re-estimated as more rows arrive.
The band shows how uncertain it is at each size: wide early, narrower later.
A steady drift away from the dashed line suggests the relationship is changing.
1Callout 1: Early estimates: unstable and uncertain.
2Callout 2: The final estimate on all rows.
3Callout 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
# Recursive coefficient estimates — Codesplash Chart Lab (recipe "recursive-coef")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if LO and HI:
fig.add_scatter(x=t, y=d[HI], mode="lines", line=dict(width=0), showlegend=False)
fig.add_scatter(x=t, y=d[LO], mode="lines", line=dict(width=0), fill="tonexty", fillcolor="rgba(30, 90, 200, 0.16)", name="± 1.96 SE")
fig.add_scatter(x=t, y=d[Y], mode="lines", line=dict(color=PALETTE[0], width=1.8), name="estimate on the first r rows")
fig.add_hline(y=d[Y].iloc[-1], line=dict(color=REF, dash="dash"))
fig.update_layout(xaxis_title="row", yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads recursive-coef-demo.csv · app theme from the optional codesplash helper
# Recursive coefficient estimates — Codesplash Chart Lab (recipe "recursive-coef")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("recursive-coef-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- "row"
y_col <- "slope"
lo_col <- "lower"
hi_col <- "upper"
d <- ordered(df, x_col, y_col)
d$t <- time_of(d, x_col)
p <- ggplot(d, aes(t, .data[[y_col]])) +
{ if (!is.null(lo_col) && !is.null(hi_col)) geom_ribbon(aes(ymin = .data[[lo_col]], ymax = .data[[hi_col]]), fill = cs_cat[1], alpha = 0.16) } +
geom_hline(yintercept = d[[y_col]][nrow(d)], colour = ref_col, linetype = "dashed") + geom_line(colour = cs_cat[1], linewidth = 0.9) +
labs(x = "row", y = y_col) + theme_cs
print(p)
Needs ggplot2 · reads recursive-coef-demo.csv · app theme from the optional codesplashr helper
Read each panel as one series' response to a one-off shock in another.
Follow the path from period zero: how large, how long, which sign.
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
# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")# controls: scope=auto
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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")
from plotly.subplots import make_subplots
H = "steps"
V = "response"
R = "responding series"
S = "shock"
LO = "low"
HI = "high"
responses = list(pd.unique(df[R]))
shocks = list(pd.unique(df[S]))
fig = make_subplots(rows=len(responses), cols=len(shocks), shared_xaxes=True, column_titles=[f"Shock: {s}" for s in shocks], row_titles=[str(r) for r in responses])
for i, r in enumerate(responses):
for j, s in enumerate(shocks):
d = df[(df[R] == r) & (df[S] == s)].sort_values(H)
if LO and HI:
fig.add_trace(go.Scatter(x=list(d[H]) + list(d[H])[::-1], y=list(d[HI]) + list(d[LO])[::-1], fill="toself", fillcolor="rgba(70,110,200,0.2)", line=dict(width=0), showlegend=False, hoverinfo="skip"), row=i + 1, col=j + 1)
fig.add_trace(go.Scatter(x=d[H], y=d[V], mode="lines", line=dict(color=PALETTE[0]), showlegend=False), row=i + 1, col=j + 1)
fig.add_hline(y=0, line=dict(color=REF, width=1), row=i + 1, col=j + 1)
fig.show()
Needs pandas, numpy, plotly · reads impulse-response-demo.csv · app theme from the optional codesplash helper
# Impulse responses — Codesplash Chart Lab (recipe "impulse-response")# controls: scope=auto
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("impulse-response-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["responding series"]] <- factor(df[["responding series"]], levels = c("sales", "ad spend", "price"))
df[["shock"]] <- factor(df[["shock"]], levels = c("sales", "ad spend", "price"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
H <- "steps"
V <- "response"
R <- "responding series"
S <- "shock"
LO <- "low"
HI <- "high"
d <- data.frame(h = df[[H]], v = df[[V]], response = df[[R]], shock = df[[S]])
if (!is.null(LO) && !is.null(HI)) { d$lo <- df[[LO]]; d$hi <- df[[HI]] }
d <- d[order(d$h), ]
p <- ggplot(d, aes(h, v))
if (!is.null(d$lo)) p <- p + geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.2)
p <- p + geom_hline(yintercept = 0, colour = ref_col, linewidth = 0.3) +
geom_line(colour = cs_cat[1], linewidth = 0.6) +
facet_grid(response ~ shock, scales = "free_y", labeller = labeller(shock = function(s) paste("Shock:", s))) +
labs(x = "steps after the shock", y = NULL)
print(p)
Needs ggplot2 · reads impulse-response-demo.csv · app theme from the optional codesplashr helper
Read each bar as how often actuals fell in that part of their forecast distribution.
Flat means calibrated.
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
# PIT histogram — Codesplash Chart Lab (recipe "pit-histogram")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Bar(x=(edges[:-1] + edges[1:]) / 2, y=share, width=np.diff(edges) * 0.96, marker_color=PALETTE[0], name="share in the bin"))
fig.add_hline(y=1 / len(share), line_dash="dash", line_color="#6b7280", annotation_text="well calibrated")
fig.update_layout(xaxis_title="where the actual fell in its forecast distribution", yaxis_title="share of forecasts")
fig.show()
Needs pandas, numpy, plotly · reads pit-histogram-demo.csv · app theme from the optional codesplash helper
# PIT histogram — Codesplash Chart Lab (recipe "pit-histogram")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pit-histogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
SHARE <- "share"
share <- ifelse(is.na(df[[SHARE]]), 0, df[[SHARE]])
d <- data.frame(mid = (seq_along(share) - 0.5) / length(share), share = share)
p <- ggplot(d, aes(mid, share)) +
geom_col(width = 0.96 / length(share), fill = cs_cat[1]) +
geom_hline(yintercept = 1 / length(share), linetype = "dashed", colour = "#6b7280") +
labs(x = "where the actual fell in its forecast distribution", y = "share of forecasts")
print(p)
Needs ggplot2 · reads pit-histogram-demo.csv · app theme from the optional codesplashr helper
Start with the top panel: the forecast itself, the sum of the parts below it.
Read the first part as the level and its slow movement; it starts from the last observed value.
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
# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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")
from plotly.subplots import make_subplots
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))
fig = make_subplots(rows=len(names) + 1, cols=1, shared_xaxes=True, subplot_titles=["Forecast (sum of the parts)"] + [str(n) for n in names])
fig.add_trace(go.Scatter(x=total.index, y=total, mode="lines+markers", line=dict(color="black", width=2), name="forecast"), row=1, col=1)
for k, name in enumerate(names):
fig.add_trace(go.Scatter(x=wide.index, y=wide[name], mode="lines+markers", line=dict(color=PALETTE[k % len(PALETTE)]), name=str(name)), row=k + 2, col=1)
fig.update_layout(showlegend=False, height=200 * (len(names) + 1))
fig.show()
Needs pandas, numpy, plotly · reads forecast-components-demo.csv · app theme from the optional codesplash helper
# Forecast by part — Codesplash Chart Lab (recipe "forecast-components")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("forecast-components-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["part"]] <- factor(df[["part"]], levels = c("trend", "seasonality"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
T <- "month"
V <- "passengers (thousands)"
P <- "part"
names <- if (is.factor(df[[P]])) levels(droplevels(df[[P]])) else unique(as.character(df[[P]]))
d <- data.frame(t = df[[T]], v = df[[V]], part = as.character(df[[P]]))
total <- aggregate(v ~ t, data = d, FUN = sum) # the forecast: the parts add up to it
total$part <- "Forecast (sum of the parts)"
d <- rbind(total[, c("t", "v", "part")], d)
d$part <- factor(d$part, levels = c("Forecast (sum of the parts)", names))
p <- ggplot(d, aes(t, v, colour = part)) +
geom_line(linewidth = 0.6) + geom_point(size = 1) +
facet_wrap(~ part, ncol = 1, scales = "free_y") +
scale_colour_manual(values = c("black", cs_cat[seq_along(names)]), guide = "none") +
labs(x = T, y = V)
print(p)
Needs ggplot2 · reads forecast-components-demo.csv · app theme from the optional codesplashr helper
Read the dark line as the history and the coloured line as the median forecast.
Read the widest band as the central 80% (10% to 90%), the narrower ones as smaller central shares.
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
# Quantile fan — Codesplash Chart Lab (recipe "quantile-fan")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
x = list(fc.index)
fig = go.Figure(go.Scatter(x=hist[T], y=hist[V], mode="lines", line=dict(color="black"), name="history"))
for q in [l for l in levels if l < 0.5]:
mirror = min(levels, key=lambda l: abs(l - (1 - q)))
if abs(mirror - (1 - q)) < 1e-6:
fig.add_trace(go.Scatter(x=x + x[::-1], y=list(fc[mirror]) + list(fc[q])[::-1], fill="toself", fillcolor="rgba(70,110,200,0.18)", line=dict(width=0), name=f"{q:.0%}–{mirror:.0%}"))
mid = min(levels, key=lambda l: abs(l - 0.5))
fig.add_trace(go.Scatter(x=x, y=fc[mid], mode="lines", line=dict(color=PALETTE[0], width=2), name="median"))
fig.show()
Needs pandas, numpy, plotly · reads quantile-fan-demo.csv · app theme from the optional codesplash helper
# Quantile fan — Codesplash Chart Lab (recipe "quantile-fan")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("quantile-fan-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
T <- "month"
V <- "passengers (thousands)"
Q <- "quantile"
hist <- df[is.na(df[[Q]]), , drop = FALSE]
fc <- df[!is.na(df[[Q]]), , drop = FALSE]
lv <- sort(unique(fc[[Q]]))
bands <- do.call(rbind, lapply(lv[lv < 0.5], function(q) {
m <- lv[which.min(abs(lv - (1 - q)))]
if (abs(m - (1 - q)) > 1e-6) return(NULL)
lo <- fc[fc[[Q]] == q, ]; hi <- fc[fc[[Q]] == m, ]
data.frame(t = lo[[T]], lo = lo[[V]], hi = hi[match(lo[[T]], hi[[T]]), V], band = sprintf("%g–%g%%", 100 * q, 100 * m))
}))
mid <- fc[fc[[Q]] == lv[which.min(abs(lv - 0.5))], ]
p <- ggplot() +
geom_ribbon(data = bands, aes(t, ymin = lo, ymax = hi, group = band), fill = cs_cat[1], alpha = 0.18) +
geom_line(data = hist, aes(.data[[T]], .data[[V]]), colour = "black", linewidth = 0.5) +
geom_line(data = mid, aes(.data[[T]], .data[[V]]), colour = cs_cat[1], linewidth = 0.8) +
labs(x = T, y = V)
print(p)
Needs ggplot2 · reads quantile-fan-demo.csv · app theme from the optional codesplashr helper
Data quality
Missingness, outliers and types — the profiler's charts.
Scan the tiles for a first look at each column: kind, missing share and distinct count.
Read the mini chart for shape: a histogram for numbers, top values for categories.
Look for surprises: a spike, a red missing bar, one value dominating.
1Callout 1: Column name and its inferred kind.
2Callout 2: A mini histogram: spikes and long tails stand out.
3Callout 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
# Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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))
kinds = {n: infer_kind(df[n], KINDS[n]) for n in COLS}
titles = [f"{n} · {kinds[n]} · {df[n].isna().mean():.0%} missing" for n in COLS]
fig = make_subplots(rows=rows, cols=cols, subplot_titles=titles, vertical_spacing=0.12)
for i, name in enumerate(COLS):
what, a, b = tile(df[name], kinds[name])
r, cc = i // cols + 1, i % cols + 1
colour = PALETTE[KIND_COLOUR[kinds[name]]]
if what == "bins":
fig.add_bar(x=(b[:-1] + b[1:]) / 2, y=a, width=np.diff(b), marker_color=colour, showlegend=False, row=r, col=cc)
elif what == "levels":
fig.add_bar(y=[l for l, _ in a][::-1], x=[n for _, n in a][::-1], orientation="h", marker_color=colour, showlegend=False, row=r, col=cc)
fig.update_xaxes(showticklabels=False)
fig.update_annotations(font_size=10)
fig.update_layout(height=200 * rows, bargap=0.05)
fig.show()
Needs pandas, numpy, plotly · reads column-sparkline-demo.csv · app theme from the optional codesplash helper
Needs ggplot2 · reads column-sparkline-demo.csv · app theme from the optional codesplashr helper
-- Column sparklines — Codesplash Chart Lab (recipe "column-sparkline")-- controls: defaults-- one summary row per column: missing share, distinct values and range
SELECT 'signup_date' AS "column", 'temporal' AS kind, count(*) AS n, count(*) - count("signup_date") AS missing,
(count(*) - count("signup_date")) / count(*) AS missing_share, count(DISTINCT "signup_date") AS "distinct",
min("signup_date")::VARCHAR AS min, max("signup_date")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'age' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("age") AS missing,
(count(*) - count("age")) / count(*) AS missing_share, count(DISTINCT "age") AS "distinct",
min("age")::VARCHAR AS min, max("age")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'income' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("income") AS missing,
(count(*) - count("income")) / count(*) AS missing_share, count(DISTINCT "income") AS "distinct",
min("income")::VARCHAR AS min, max("income")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'region' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("region") AS missing,
(count(*) - count("region")) / count(*) AS missing_share, count(DISTINCT "region") AS "distinct",
min("region")::VARCHAR AS min, max("region")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'plan' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("plan") AS missing,
(count(*) - count("plan")) / count(*) AS missing_share, count(DISTINCT "plan") AS "distinct",
min("plan")::VARCHAR AS min, max("plan")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'churned' AS "column", 'boolean' AS kind, count(*) AS n, count(*) - count("churned") AS missing,
(count(*) - count("churned")) / count(*) AS missing_share, count(DISTINCT "churned") AS "distinct",
min("churned")::VARCHAR AS min, max("churned")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'satisfaction' AS "column", 'numeric' AS kind, count(*) AS n, count(*) - count("satisfaction") AS missing,
(count(*) - count("satisfaction")) / count(*) AS missing_share, count(DISTINCT "satisfaction") AS "distinct",
min("satisfaction")::VARCHAR AS min, max("satisfaction")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv')
UNION ALL
SELECT 'comments' AS "column", 'categorical' AS kind, count(*) AS n, count(*) - count("comments") AS missing,
(count(*) - count("comments")) / count(*) AS missing_share, count(DISTINCT "comments") AS "distinct",
min("comments")::VARCHAR AS min, max("comments")::VARCHAR AS max FROM read_csv('column-sparkline-demo.csv');
Needs ggplot2 · reads missing-matrix-demo.csv · app theme from the optional codesplashr helper
-- Missing-value matrix — Codesplash Chart Lab (recipe "missing-matrix")-- controls: sort=false-- missing share per column in bands of ⌈n / 400⌉ consecutive rows (table order)
WITH r AS (SELECT row_number() OVER () - 1 AS i, * FROM read_csv('missing-matrix-demo.csv')),
p AS (SELECT CASE WHEN count(*) > 400 THEN ceil(count(*) / 400) ELSE 1 END AS per FROM r)
SELECT i // per AS band,
avg(("age" IS NULL)::INTEGER) AS "age",
avg(("region" IS NULL)::INTEGER) AS "region",
avg(("income" IS NULL)::INTEGER) AS "income",
avg(("last_purchase" IS NULL)::INTEGER) AS "last_purchase",
avg(("satisfaction" IS NULL)::INTEGER) AS "satisfaction",
avg(("nps" IS NULL)::INTEGER) AS "nps",
avg(("comments" IS NULL)::INTEGER) AS "comments"
FROM r, p
GROUP BY ALL
ORDER BY band;
Each cell is the correlation between two columns' missing-value indicators.
A dark cell: these two columns go missing together.
Read clusters as groups of fields collected or lost together.
1Callout 1: A dark cell: the two columns go missing together.
2Callout 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
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")# controls: cluster=true, values=true, lower=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
ind = ind.loc[:, (ind.sum() > 0) & (ind.sum() < len(ind))]
r = ind.corr()
order = cluster_order(r.to_numpy())
r = r.iloc[order, order]
fig = go.Figure(go.Heatmap(z=r.to_numpy(), x=list(r.columns), y=list(r.index), zmin=-1, zmax=1, colorscale=[[0, DIV[0]], [0.5, DIV[1]], [1, DIV[2]]],
text=r.map(apa_r).to_numpy(), texttemplate="%{text}", colorbar_title="nullity r"))
fig.update_layout(yaxis_autorange="reversed")
fig.show()
Needs pandas, numpy, plotly · reads nullity-corr-demo.csv · app theme from the optional codesplash helper
# Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")# controls: cluster=true, values=true, lower=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("nullity-corr-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["last_purchase"]] <- as.POSIXct(df[["last_purchase"]], tz = "UTC")
df[["churned"]] <- as.logical(df[["churned"]])
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
df[["comments"]] <- factor(df[["comments"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
cluster_order <- function(m) {
# average linkage on 1 - |r|; merged clusters are appended last (the app's leaf order)
d <- 1 - abs(ifelse(is.na(m), 0, m))
clusters <- as.list(seq_len(nrow(d)))
while (length(clusters) > 1) {
best <- c(1, 2); best_d <- Inf
for (a in seq_len(length(clusters) - 1)) for (b in (a + 1):length(clusters)) {
dist <- mean(d[clusters[[a]], clusters[[b]]])
if (dist < best_d) { best <- c(a, b); best_d <- dist }
}
merged <- c(clusters[[best[1]]], clusters[[best[2]]])
clusters <- c(clusters[-best], list(merged))
}
clusters[[1]]
}
apa_r <- function(v) ifelse(is.na(v), "", gsub("-", "\u2212", sub("^(-?)0\\.", "\\1.", sprintf("%.2f", v))))
cols <- c("age", "region", "income", "last_purchase", "satisfaction", "nps", "comments", "churned")
ind <- sapply(df[cols], is.na) * 1 # 1 = missing (NULL or not-a-number)
ind <- ind[, colSums(ind) > 0 & colSums(ind) < nrow(ind), drop = FALSE] # drop complete / all-missing columns
r <- stats::cor(ind) # Pearson on indicators = φ
ord <- colnames(r)[cluster_order(r)]
cells <- expand.grid(row = ord, col = ord, stringsAsFactors = FALSE)
cells$r <- r[cbind(cells$row, cells$col)]
cells$row <- factor(cells$row, levels = rev(ord)); cells$col <- factor(cells$col, levels = ord)
p <- ggplot(cells, aes(col, row, fill = r)) +
geom_tile(colour = "white", linewidth = 0.5) +
geom_text(aes(label = apa_r(r)), size = 3) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], midpoint = 0, limits = c(-1, 1), name = "nullity r") +
coord_equal() + labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
print(p)
Needs ggplot2 · reads nullity-corr-demo.csv · app theme from the optional codesplashr helper
-- Nullity correlation — Codesplash Chart Lab (recipe "nullity-corr")-- controls: cluster=true, values=true, lower=false-- φ between missingness indicators for every pair (NULL when a column is complete or all missing)
SELECT 'age' AS a, 'region' AS b, corr(("age" IS NULL)::INTEGER, ("region" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'income' AS b, corr(("age" IS NULL)::INTEGER, ("income" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'last_purchase' AS b, corr(("age" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'satisfaction' AS b, corr(("age" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'nps' AS b, corr(("age" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'comments' AS b, corr(("age" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'age' AS a, 'churned' AS b, corr(("age" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'income' AS b, corr(("region" IS NULL)::INTEGER, ("income" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'last_purchase' AS b, corr(("region" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'satisfaction' AS b, corr(("region" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'nps' AS b, corr(("region" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'comments' AS b, corr(("region" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'region' AS a, 'churned' AS b, corr(("region" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'last_purchase' AS b, corr(("income" IS NULL)::INTEGER, ("last_purchase" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'satisfaction' AS b, corr(("income" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'nps' AS b, corr(("income" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'comments' AS b, corr(("income" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'income' AS a, 'churned' AS b, corr(("income" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'satisfaction' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("satisfaction" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'nps' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'comments' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'last_purchase' AS a, 'churned' AS b, corr(("last_purchase" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'nps' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("nps" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'comments' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'satisfaction' AS a, 'churned' AS b, corr(("satisfaction" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'nps' AS a, 'comments' AS b, corr(("nps" IS NULL)::INTEGER, ("comments" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'nps' AS a, 'churned' AS b, corr(("nps" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv')
UNION ALL
SELECT 'comments' AS a, 'churned' AS b, corr(("comments" IS NULL)::INTEGER, ("churned" IS NULL)::INTEGER) AS r FROM read_csv('nullity-corr-demo.csv');
Read a dot column as a combination of columns missing together.
Read the bar above it as how many rows have that exact combination.
Read the small bars at the left for each column's total.
1Callout 1: Height: rows with exactly this pattern.
2Callout 2: Joined dots: the columns missing together.
3Callout 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
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")# controls: top=12
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = make_subplots(rows=2, cols=2, column_widths=[0.2, 0.8], row_heights=[0.6, 0.4], shared_xaxes="columns", shared_yaxes="rows", horizontal_spacing=0.01, vertical_spacing=0.02)
fig.add_bar(x=list(range(len(top))), y=[n for _, n in top], marker_color=[PALETTE[0] if k.count("1") == 1 else PALETTE[4] for k, _ in top], text=[n for _, n in top], showlegend=False, row=1, col=2)
for j, (k, _) in enumerate(top):
fig.add_scatter(x=[j] * len(used), y=used, mode="markers+lines", marker=dict(size=10, color=[REF if ch == "1" else GREY for ch in k]), line=dict(width=0), showlegend=False, row=2, col=2)
fig.add_bar(y=used, x=[size[c] for c in used], orientation="h", marker_color=REF, showlegend=False, row=2, col=1)
fig.update_xaxes(autorange="reversed", row=2, col=1)
fig.update_yaxes(autorange="reversed", row=2, col=2)
fig.update_layout(title=f"{complete:,} complete rows", height=520)
fig.show()
Needs pandas, numpy, plotly · reads upset-demo.csv · app theme from the optional codesplash helper
# UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")# controls: top=12
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("upset-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["last_purchase"]] <- as.POSIXct(df[["last_purchase"]], tz = "UTC")
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
df[["comments"]] <- factor(df[["comments"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is # installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
cols <- c("age", "region", "income", "last_purchase", "satisfaction", "nps", "comments")
miss <- sapply(df[cols], is.na) # NULL and not-a-number both count as missing
size <- colSums(miss)
used <- cols[size > 0][order(-size[size > 0], match(cols[size > 0], cols))] # sets by missing count
key <- apply(miss[, used, drop = FALSE] * 1, 1, paste, collapse = "")
complete <- sum(!grepl("1", key))
tab <- table(key[grepl("1", key)]) # each incomplete row once, under its exact set
pat <- data.frame(key = names(tab), n = as.vector(tab), stringsAsFactors = FALSE)
pat$k <- nchar(gsub("0", "", pat$key))
pat <- pat[order(-pat$n, pat$k, -xtfrm(pat$key)), ] # count, fewer columns, key descending
rest <- pat[-seq_len(min(12, nrow(pat))), ]
pat <- utils::head(pat, 12)
pat$x <- seq_len(nrow(pat))
dots <- do.call(rbind, lapply(seq_len(nrow(pat)), function(j) data.frame(x = j, set = used, on = strsplit(pat$key[j], "")[[1]] == "1")))
dots$set <- factor(dots$set, levels = rev(used))
bars <- ggplot(pat, aes(x, n, fill = k > 1)) + geom_col(show.legend = FALSE) +
geom_text(aes(label = n), vjust = -0.3, size = 2.6) +
scale_fill_manual(values = c(`FALSE` = cs_cat[1], `TRUE` = cs_cat[5])) + # single- vs multi-column patterns
scale_x_continuous(limits = c(0.5, nrow(pat) + 0.5)) +
labs(x = NULL, y = "rows", subtitle = sprintf("%d complete rows%s", complete, if (nrow(rest)) sprintf(" · %d more patterns (%d rows)", nrow(rest), sum(rest$n)) else "")) +
theme_cs + theme(axis.text.x = element_blank())
matrix <- ggplot(dots, aes(x, set)) +
geom_line(data = dots[dots$on, ], aes(group = x), colour = ref_col) +
geom_point(aes(colour = on), size = 2.6, show.legend = FALSE) +
scale_colour_manual(values = c(`FALSE` = grey_col, `TRUE` = ref_col)) +
scale_x_continuous(limits = c(0.5, nrow(pat) + 0.5)) +
labs(x = NULL, y = NULL) + theme_cs + theme(axis.text.x = element_blank(), panel.grid = element_blank())
sets <- ggplot(data.frame(set = factor(used, levels = rev(used)), n = size[used]), aes(n, set)) +
geom_col(fill = ref_col) + scale_x_reverse() + labs(x = "missing", y = NULL) +
theme_cs + theme(axis.text.y = element_blank())
arrange(list(bars, matrix, sets), layout = matrix(c(NA, 1, 3, 2), 2, byrow = TRUE), widths = c(1, 4), heights = c(2, 1.3))
Needs ggplot2 · reads upset-demo.csv · app theme from the optional codesplashr helper
-- UpSet of missing patterns — Codesplash Chart Lab (recipe "upset")-- controls: top=12-- exclusive missing patterns: each incomplete row counted once under the exact set of missing columns
WITH p AS (
SELECT list_filter([CASE WHEN "age" IS NULL THEN 'age' END, CASE WHEN "region" IS NULL THEN 'region' END, CASE WHEN "income" IS NULL THEN 'income' END, CASE WHEN "last_purchase" IS NULL THEN 'last_purchase' END, CASE WHEN "satisfaction" IS NULL THEN 'satisfaction' END, CASE WHEN "nps" IS NULL THEN 'nps' END, CASE WHEN "comments" IS NULL THEN 'comments' END], lambda x: x IS NOT NULL) AS missing
FROM read_csv('upset-demo.csv')
)
SELECT missing, count(*) AS rows
FROM p
WHERE len(missing) > 0
GROUP BY missing
ORDER BY rows DESC, len(missing);
Read a cell as the share missing in that column within that group.
Compare a row across groups: differences suggest missingness depends on the group.
Check the group sizes in the headers before reading small groups.
1Callout 1: This column's missing share in one group.
2Callout 2: A row that differs across groups: not missing completely at random.
3Callout 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
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
fig = go.Figure(go.Heatmap(z=share.to_numpy(), x=groups, y=COLS, zmin=0, zmax=max(0.05, float(share.max().max())),
colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], texttemplate="%{z:.0%}", colorbar_tickformat=".0%"))
fig.update_layout(title="Missing share by plan", yaxis_autorange="reversed")
fig.show()
Needs pandas, numpy, plotly · reads missing-by-group-demo.csv · app theme from the optional codesplash helper
# Missing by group — Codesplash Chart Lab (recipe "missing-by-group")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("missing-by-group-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["last_purchase"]] <- as.POSIXct(df[["last_purchase"]], tz = "UTC")
df[["comments"]] <- factor(df[["comments"]])
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
cols <- c("age", "income", "last_purchase", "satisfaction", "nps", "comments")
g <- ifelse(is.na(df[["plan"]]), "(missing)", as.character(df[["plan"]])) # a missing group value forms its own column
groups <- utils::head(intersect(c("Basic", "Plus", "Pro"), g), 10) # declared level order
if (any(g == "(missing)")) groups <- c(groups, "(missing)")
keep <- g %in% groups
share <- sapply(cols, function(cl) tapply(is.na(df[[cl]][keep]), g[keep], mean))[groups, , drop = FALSE]
cells <- data.frame(group = rep(groups, ncol(share)), column = rep(cols, each = length(groups)), share = as.vector(share))
cells$group <- factor(cells$group, levels = groups); cells$column <- factor(cells$column, levels = rev(cols))
p <- ggplot(cells, aes(group, column, fill = share)) +
geom_tile(colour = "white") +
geom_text(aes(label = sprintf("%.0f%%", 100 * share)), size = 2.8) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[2], limits = c(0, max(0.05, max(cells$share))), labels = function(v) sprintf("%.0f%%", 100 * v)) +
labs(x = NULL, y = NULL, title = "Missing share by plan") +
theme_cs + theme(panel.grid = element_blank())
print(p)
Needs ggplot2 · reads missing-by-group-demo.csv · app theme from the optional codesplashr helper
-- Missing by group — Codesplash Chart Lab (recipe "missing-by-group")-- controls: defaults-- missing share per column within each group; a missing group value is its own group
SELECT coalesce("plan"::VARCHAR, '(missing)') AS "group", count(*) AS n,
avg(("age" IS NULL)::INTEGER) AS "age",
avg(("income" IS NULL)::INTEGER) AS "income",
avg(("last_purchase" IS NULL)::INTEGER) AS "last_purchase",
avg(("satisfaction" IS NULL)::INTEGER) AS "satisfaction",
avg(("nps" IS NULL)::INTEGER) AS "nps",
avg(("comments" IS NULL)::INTEGER) AS "comments"
FROM read_csv('missing-by-group-demo.csv')
GROUP BY ALL
ORDER BY n DESC;
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
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")# controls: log=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
y = votes + np.random.default_rng(11).uniform(-0.3, 0.3, len(v))
fig = go.Figure(go.Scatter(x=v, y=y, mode="markers", marker=dict(size=6, color=votes, colorscale=[[0, GREY], [0.34, PALETTE[1]], [0.67, PALETTE[3]], [1, DIV[0]]], cmin=0, cmax=3), text=[f"{k} rules" for k in votes]))
for lo, hi, colour, dash in [(q1 - 1.5 * iqr, q3 + 1.5 * iqr, REF, "solid"), (m - 3 * s, m + 3 * s, PALETTE[0], "dash"), (med - 3.5 * scale, med + 3.5 * scale, PALETTE[2], "dot")]:
for xv in (lo, hi):
fig.add_vline(x=xv, line=dict(color=colour, dash=dash, width=1.3))
fig.update_layout(yaxis=dict(tickvals=[0, 1, 2, 3], ticktext=["0 rules", "1 rule", "2 rules", "3 rules"]), xaxis_title="response_ms")
fig.show()
Needs pandas, numpy, plotly · reads outlier-consensus-demo.csv · app theme from the optional codesplash helper
# Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")# controls: log=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("outlier-consensus-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
v <- df[["response_ms"]][!is.na(df[["response_ms"]])]
q <- stats::quantile(v, c(0.25, 0.75), type = 7); iqr <- q[[2]] - q[[1]]
tukey <- v < q[[1]] - 1.5 * iqr | v > q[[2]] + 1.5 * iqr
m <- mean(v); s <- stats::sd(v)
z <- if (length(v) > 10 && s > 0) abs(v - m) > 3 * s else rep(FALSE, length(v)) # not applied when n <= 10
med <- stats::median(v); mad_raw <- stats::mad(v, constant = 1)
scale <- if (mad_raw > 0) 1.4826 * mad_raw else 1.253314 * mean(abs(v - med)) # meanAD when MAD = 0
modz <- if (scale > 0) abs(v - med) > 3.5 * scale else rep(FALSE, length(v))
votes <- tukey + z + modz # consensus 0-3: screening hints, never automatic deletions
set.seed(11) # deterministic jitter within each band
pts <- data.frame(v = v, votes = votes, y = votes + stats::runif(length(v), -0.3, 0.3))
fences <- data.frame(x = c(q[[1]] - 1.5 * iqr, q[[2]] + 1.5 * iqr, m - 3 * s, m + 3 * s, med - 3.5 * scale, med + 3.5 * scale),
rule = rep(c("Tukey 1.5×IQR", "|z| = 3", "|mod z| = 3.5"), each = 2))
p <- ggplot(pts, aes(v, y)) +
geom_vline(data = fences, aes(xintercept = x, linetype = rule, colour = rule)) +
geom_point(aes(fill = factor(votes)), shape = 21, colour = "transparent", size = 1.8, alpha = 0.85) +
scale_fill_manual(values = c(`0` = grey_col, `1` = cs_cat[2], `2` = cs_cat[4], `3` = div_ramp[1]), guide = "none") +
scale_colour_manual(values = c("Tukey 1.5×IQR" = ref_col, "|z| = 3" = cs_cat[1], "|mod z| = 3.5" = cs_cat[3]), name = NULL) +
scale_linetype_manual(values = c("Tukey 1.5×IQR" = "solid", "|z| = 3" = "dashed", "|mod z| = 3.5" = "dotted"), name = NULL) +
scale_y_continuous(breaks = 0:3, labels = sprintf("%d rules · %d", 0:3, tabulate(votes + 1, 4))) +
labs(x = "response_ms", y = NULL) +
theme_cs
print(p)
Needs ggplot2 · reads outlier-consensus-demo.csv · app theme from the optional codesplashr helper
-- Outlier consensus — Codesplash Chart Lab (recipe "outlier-consensus")-- controls: log=false-- per value: Tukey (type-7 quartiles), z (n > 10, SD on n − 1) and modified-z flags and their consensus
WITH v AS (SELECT "response_ms"::DOUBLE AS x FROM read_csv('outlier-consensus-demo.csv') WHERE "response_ms" IS NOT NULL),
s AS (
SELECT quantile_cont(x, 0.25) AS q1, quantile_cont(x, 0.75) AS q3, avg(x) AS m, stddev_samp(x) AS sd,
median(x) AS med, count(*) AS n
FROM v
),
d AS (SELECT median(abs(x - med)) AS mad, avg(abs(x - med)) AS mean_ad FROM v, s),
r AS (SELECT *, CASE WHEN mad > 0 THEN 1.4826 * mad ELSE 1.253314 * mean_ad END AS scale FROM s, d)
SELECT x,
(x < q1 - 1.5 * (q3 - q1) OR x > q3 + 1.5 * (q3 - q1)) AS tukey,
coalesce(n > 10 AND sd > 0 AND abs(x - m) > 3 * sd, false) AS z,
coalesce(scale > 0 AND abs(x - med) > 3.5 * scale, false) AS modified_z,
tukey::INTEGER + z::INTEGER + modified_z::INTEGER AS votes
FROM v, r
ORDER BY votes DESC, x;
Needs ggplot2 · reads type-composition-demo.csv · app theme from the optional codesplashr helper
-- Column type composition — Codesplash Chart Lab (recipe "type-composition")-- controls: defaults-- inferred kind per column: physical kind refined to id-like (all distinct, n ≥ 20) and text
SELECT 'customer_id' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("customer_id"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("customer_id"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "customer_id") > 0.5 * count("customer_id")) THEN 'text'
WHEN count("customer_id") >= 20 AND count(DISTINCT "customer_id") = count("customer_id") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'email' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("email"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("email"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "email") > 0.5 * count("email")) THEN 'text'
WHEN count("email") >= 20 AND count(DISTINCT "email") = count("email") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'signup_date' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'last_purchase' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'last_login' AS "column", 'temporal' AS physical,
'temporal' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'age' AS "column", 'numeric' AS physical,
CASE WHEN count("age") >= 20 AND count(DISTINCT "age") = count("age") AND bool_and("age" = round("age")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'income' AS "column", 'numeric' AS physical,
CASE WHEN count("income") >= 20 AND count(DISTINCT "income") = count("income") AND bool_and("income" = round("income")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'spend_30d' AS "column", 'numeric' AS physical,
CASE WHEN count("spend_30d") >= 20 AND count(DISTINCT "spend_30d") = count("spend_30d") AND bool_and("spend_30d" = round("spend_30d")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'visits_30d' AS "column", 'numeric' AS physical,
CASE WHEN count("visits_30d") >= 20 AND count(DISTINCT "visits_30d") = count("visits_30d") AND bool_and("visits_30d" = round("visits_30d")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'tenure_days' AS "column", 'numeric' AS physical,
CASE WHEN count("tenure_days") >= 20 AND count(DISTINCT "tenure_days") = count("tenure_days") AND bool_and("tenure_days" = round("tenure_days")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'discount_pct' AS "column", 'numeric' AS physical,
CASE WHEN count("discount_pct") >= 20 AND count(DISTINCT "discount_pct") = count("discount_pct") AND bool_and("discount_pct" = round("discount_pct")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'satisfaction' AS "column", 'numeric' AS physical,
CASE WHEN count("satisfaction") >= 20 AND count(DISTINCT "satisfaction") = count("satisfaction") AND bool_and("satisfaction" = round("satisfaction")) THEN 'id-like' ELSE 'numeric' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'region' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("region"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("region"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "region") > 0.5 * count("region")) THEN 'text'
WHEN count("region") >= 20 AND count(DISTINCT "region") = count("region") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'plan' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("plan"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("plan"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "plan") > 0.5 * count("plan")) THEN 'text'
WHEN count("plan") >= 20 AND count(DISTINCT "plan") = count("plan") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'device' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("device"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("device"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "device") > 0.5 * count("device")) THEN 'text'
WHEN count("device") >= 20 AND count(DISTINCT "device") = count("device") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'country' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("country"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("country"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "country") > 0.5 * count("country")) THEN 'text'
WHEN count("country") >= 20 AND count(DISTINCT "country") = count("country") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'churned' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'newsletter' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'mobile_app' AS "column", 'boolean' AS physical,
'boolean' AS kind
FROM read_csv('type-composition-demo.csv')
UNION ALL
SELECT 'comments' AS "column", 'categorical' AS physical,
CASE WHEN avg(length("comments"::VARCHAR)) > 30
OR (avg(len(regexp_split_to_array(trim("comments"::VARCHAR), '\s+'))) > 3 AND count(DISTINCT "comments") > 0.5 * count("comments")) THEN 'text'
WHEN count("comments") >= 20 AND count(DISTINCT "comments") = count("comments") THEN 'id-like' ELSE 'categorical' END AS kind
FROM read_csv('type-composition-demo.csv');
Needs duckdb · reads type-composition-demo.csv
Inference & models
Analysis results: estimates with intervals, survival curves, ROC, power and model diagnostics.
Read each point as the model's estimated mean at that level, adjusted for other terms.
Read the bars as their intervals.
With a second factor, compare the lines: non-parallel lines suggest an interaction.
1Callout 1: An adjusted mean and its interval.
2Callout 2: The gap between lines changes across levels.
3Callout 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
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")# controls: lines=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[X, M])
xs = levels_of(d[X])
traces = levels_of(d[TR]) if TR else [None]
fig = go.Figure()
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)) for v in g[X]]).sort_values("_p")
err = dict(type="data", symmetric=False, array=g[HI] - g[M], arrayminus=g[M] - g[LO]) if LO and HI else None
fig.add_scatter(x=g[X].astype(str), y=g[M], mode="lines+markers" if LINES else "markers", name=str(t) if t is not None else M,
error_y=err, marker=dict(color=PALETTE[j % len(PALETTE)], size=8), line=dict(color=PALETTE[j % len(PALETTE)]))
fig.update_xaxes(categoryorder="array", categoryarray=xs, title=X)
fig.update_layout(yaxis_title=M, legend_title_text=TR or "")
fig.show()
Needs pandas, numpy, plotly · reads emm-plot-demo.csv · app theme from the optional codesplash helper
# Estimated marginal means — Codesplash Chart Lab (recipe "emm-plot")# controls: lines=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("emm-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["dose"]] <- factor(df[["dose"]], levels = c("0.5 mg", "1 mg", "2 mg"))
df[["supplement"]] <- factor(df[["supplement"]], levels = c("orange juice", "ascorbic acid"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "dose"
m_col <- "tooth length (EMM)"
lo_col <- "lower"
hi_col <- "upper"
tr_col <- "supplement"
show_lines <- TRUE
d <- df[!is.na(df[[x_col]]) & !is.na(df[[m_col]]), ]
d <- data.frame(x = factor(as.character(d[[x_col]]), levels = levels_of(d[[x_col]])), m = d[[m_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
tr = if (is.null(tr_col)) "" else factor(as.character(d[[tr_col]]), levels = levels_of(d[[tr_col]])))
dodge <- position_dodge(width = 0.25)
p <- ggplot(d, aes(x, m, colour = tr, group = tr)) +
{ if (!all(is.na(d$lo))) geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.12, position = dodge) } +
{ if (show_lines) geom_line(position = dodge) } +
geom_point(size = 2.6, position = dodge) +
scale_colour_manual(values = cs_cat, guide = if (is.null(tr_col)) "none" else "legend") +
labs(x = x_col, y = m_col, colour = tr_col) + theme_cs
print(p)
Needs ggplot2 · reads emm-plot-demo.csv · app theme from the optional codesplashr helper
Read the height as the estimated share still event-free at that time.
Read across at 50% to find each group's median time.
Check the number at risk below: few at risk makes the right end unreliable.
1Callout 1: Dotted guide: the median survival time.
2Callout 2: A tick: a censored subject, not an event.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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
fig = make_subplots(rows=2 if show_risk else 1, cols=1, shared_xaxes=True, row_heights=[0.8, 0.2] if show_risk else None, vertical_spacing=0.06)
tmax = max(float(d[T].max()) for _, d in series)
ticks = np.linspace(0, tmax, 6)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
if CI and LO and HI:
fig.add_scatter(x=d[T], y=d[LO], mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip", row=1, col=1)
fig.add_scatter(x=d[T], y=d[HI], mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip", row=1, col=1)
fig.add_scatter(x=d[T], y=d[SV], mode="lines", name=name or SV, line=dict(color=col, width=2, shape="hv"), row=1, col=1)
if TICKS and NC:
cz = d[d[NC] > 0]
fig.add_scatter(x=cz[T], y=cz[SV], mode="markers", marker=dict(symbol="line-ns-open", size=9, color=col), showlegend=False, row=1, col=1)
below = d[d[SV] <= 0.5]
if MEDIAN and len(below):
tm = float(below[T].iloc[0])
fig.add_scatter(x=[0, tm, tm], y=[0.5, 0.5, 0], mode="lines", line=dict(color=col, dash="dot", width=1), showlegend=False, row=1, col=1)
if show_risk:
counts = []
for t in ticks:
nxt = d[(d[T] >= t) & d[NR].notna()]
counts.append(str(int(nxt[NR].iloc[0])) if len(nxt) else "0")
fig.add_scatter(x=ticks, y=[name or "at risk"] * len(ticks), mode="text", text=counts, textfont=dict(color=col, size=11), showlegend=False, row=2, col=1)
fig.update_yaxes(range=[0, 1.02], title=SV, row=1, col=1)
fig.update_xaxes(title=T, row=2 if show_risk else 1, col=1)
fig.show()
Needs pandas, numpy, plotly · reads km-curve-demo.csv · app theme from the optional codesplash helper
# Kaplan–Meier curve — Codesplash Chart Lab (recipe "km-curve")# controls: ci=true, riskTable=true, censorTicks=true, median=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("km-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("standard", "new therapy"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is # installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
t_col <- "months"
s_col <- "survival"
lo_col <- "lower"
hi_col <- "upper"
g_col <- "arm"
nr_col <- "n.risk"
nc_col <- "n.censor"
show_ci <- TRUE; censor_ticks <- TRUE; show_median <- TRUE
d <- data.frame(t = df[[t_col]], s = df[[s_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d$nr <- if (is.null(nr_col)) NA_real_ else df[[nr_col]]
d$nc <- if (is.null(nc_col)) 0 else df[[nc_col]]
d <- d[!is.na(d$t) & !is.na(d$s), ]
d <- d[order(d$g, d$t), ]
d$t_end <- stats::ave(d$t, d$g, FUN = function(v) c(v[-1], v[length(v)])) # step to the next time
med <- do.call(rbind, lapply(split(d, d$g, drop = TRUE), function(s) { b <- s[s$s <= 0.5, ]; if (nrow(b)) data.frame(g = s$g[1], tm = b$t[1]) else NULL }))
p <- ggplot(d, aes(t, s, colour = g, fill = g)) +
{ if (show_ci && !all(is.na(d$lo))) geom_rect(aes(xmin = t, xmax = t_end, ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } +
geom_step(linewidth = 0.9) +
{ if (censor_ticks) geom_point(data = d[d$nc > 0, ], shape = 3, size = 2) } +
{ if (show_median && !is.null(med)) geom_segment(data = med, aes(x = 0, xend = tm, y = 0.5, yend = 0.5, colour = g), inherit.aes = FALSE, linetype = "dotted") } +
{ if (show_median && !is.null(med)) geom_segment(data = med, aes(x = tm, xend = tm, y = 0.5, yend = 0, colour = g), inherit.aes = FALSE, linetype = "dotted") } +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
coord_cartesian(ylim = c(0, 1.02)) + labs(x = t_col, y = s_col, colour = NULL) + theme_cs
ticks <- pretty(c(0, max(d$t)))
ticks <- ticks[ticks <= max(d$t)]
at_risk <- do.call(rbind, lapply(split(d, d$g, drop = TRUE), function(s) data.frame(g = s$g[1], t = ticks,
n = vapply(ticks, function(tt) { nxt <- s[s$t >= tt & !is.na(s$nr), ]; if (nrow(nxt)) nxt$nr[1] else 0 }, numeric(1))))) # risk set of the next time ≥ t
tab <- ggplot(at_risk, aes(t, g, label = n, colour = g)) + geom_text(size = 3) +
scale_colour_manual(values = cs_cat, guide = "none") + scale_y_discrete(limits = rev) +
coord_cartesian(xlim = range(d$t)) + labs(x = t_col, y = NULL) + theme_cs
arrange(list(p + labs(x = NULL), tab), layout = matrix(1:2, ncol = 1), heights = c(4, 1))
Needs ggplot2 · reads km-curve-demo.csv · app theme from the optional codesplashr helper
Read the height as the chance this event has happened by that time.
Compare causes: when other events compete, each curve stays below what a one-minus-survival curve would give.
Read the two curves' sum as the chance of any event.
1Callout 1: The cumulative chance of this event.
2Callout 2: A competing event.
3Callout 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
# Cumulative incidence (competing risks) — Codesplash Chart Lab (recipe "cif-curve")# controls: ci=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
if CI and LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape="hv"), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape="hv"), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape="hv"))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads cif-curve-demo.csv · app theme from the optional codesplash helper
Read each point as a cutoff's false-positive rate and true-positive rate.
Closer to the top-left corner is better; the diagonal is no better than chance.
Read AUC in the legend, then mark the cutoff you would really use.
1Callout 1: The chosen cutoff: its sensitivity and specificity.
2Callout 2: Diagonal: a score with no ability to separate.
3Callout 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
# ROC curve — Codesplash Chart Lab (recipe "roc-curve")# controls: diagonal=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if DIAGONAL:
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color="grey", dash="dash", width=1), name="chance", showlegend=False)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
auc = trapezoid(d[FPR], d[TPR])
fig.add_scatter(x=d[FPR], y=d[TPR], mode="lines", line=dict(color=col, width=2), name=f"{name + ' ' if name else ''}AUC {auc:.3f}")
if OPT:
o = d[truthy(d[OPT])]
fig.add_scatter(x=o[FPR], y=o[TPR], mode="markers", marker=dict(size=11, color="white", line=dict(color=col, width=2)), showlegend=False)
fig.update_layout(xaxis=dict(range=[0, 1], title=FPR + " (1 − specificity)"), yaxis=dict(range=[0, 1], title=TPR + " (sensitivity)", scaleanchor="x"))
fig.show()
Needs pandas, numpy, plotly · reads roc-curve-demo.csv · app theme from the optional codesplash helper
Read each curve as power at each sample size or effect size.
Find where a curve crosses the target line.
Read the dropped line for the sample size needed.
1Callout 1: Where this curve crosses the target.
2Callout 2: A smaller effect needs far more data.
3Callout 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
# Power curve — Codesplash Chart Lab (recipe "power-curve")# controls: target=0.8, xLog=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_hline(y=TARGET, line=dict(color="grey", dash="dash", width=1))
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
fig.add_scatter(x=d[X], y=d[P], mode="lines", name=name or P, line=dict(color=col, width=2))
hit = d[d[P] >= TARGET]
if len(hit):
x0 = float(hit[X].iloc[0])
fig.add_scatter(x=[x0, x0], y=[0, TARGET], mode="lines+markers+text", line=dict(color=col, dash="dot", width=1),
marker=dict(size=[0, 8], color=col), text=[f"{x0:g}", ""], textposition="top right", showlegend=False)
fig.update_xaxes(type="log" if XLOG else "linear", title=X)
fig.update_yaxes(range=[0, 1], title=P)
fig.show()
Needs pandas, numpy, plotly · reads power-curve-demo.csv · app theme from the optional codesplash helper
Top left: residuals should scatter evenly around zero with no curve.
Top right: points should follow the line if residuals are near normal.
Bottom left: a flat smooth means equal spread. Bottom right: look for high leverage plus a large residual.
1Callout 1: A curved smooth: the model may miss non-linearity.
2Callout 2: Departures from the line at the ends: heavy tails.
3Callout 3: A rising smooth: spread grows with the fit.
4Callout 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
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
text = d[LAB].astype(str) if LAB else None
fig = make_subplots(rows=2, cols=2, subplot_titles=["Residuals vs fitted", "Normal Q–Q", "Scale–location", "Residuals vs leverage" if LEV else ""])
pt = dict(mode="markers", marker=dict(color=PALETTE[0], size=6, opacity=0.75), showlegend=False)
fig.add_scatter(x=d[FIT], y=d[RES], text=text, row=1, col=1, **pt)
fig.add_hline(y=0, line=dict(color=REF, dash="dash", width=1), row=1, col=1)
qs = np.sort(std.to_numpy())
th = stats.norm.ppf(ppoints(len(qs)))
q1, q3 = np.quantile(qs, [0.25, 0.75]), stats.norm.ppf([0.25, 0.75])
slope = (q1[1] - q1[0]) / (q3[1] - q3[0])
fig.add_scatter(x=th, y=qs, row=1, col=2, **pt)
fig.add_scatter(x=th, y=q1[0] + slope * (th - q3[0]), mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False, row=1, col=2)
fig.add_scatter(x=d[FIT], y=np.sqrt(np.abs(std)), text=text, row=2, col=1, **pt)
if LEV:
fig.add_scatter(x=d[LEV], y=std, text=text, row=2, col=2, **pt)
p = d[LEV].sum()
h = np.linspace(max(d[LEV].min(), 1e-3), d[LEV].max(), 100)
for D in (0.5, 1):
r = np.sqrt(D * p * (1 - h) / h)
for sign in (1, -1):
fig.add_scatter(x=h, y=sign * r, mode="lines", line=dict(color="#ce5342", dash="dot", width=1), showlegend=False, row=2, col=2)
fig.update_yaxes(range=[min(std.min(), -3) * 1.1, max(std.max(), 3) * 1.1], row=2, col=2)
fig.update_xaxes(title_text=FIT, row=1, col=1)
fig.update_xaxes(title_text="theoretical quantiles", row=1, col=2)
fig.update_xaxes(title_text=FIT, row=2, col=1)
fig.update_yaxes(title_text="√|standardized residuals|", row=2, col=1)
fig.show()
Needs pandas, numpy, plotly, scipy · reads residual-panel-demo.csv · app theme from the optional codesplash helper
# Regression diagnostics panel — Codesplash Chart Lab (recipe "residual-panel")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("residual-panel-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
arrange <- function(plots, layout, widths = NULL, heights = NULL) {
# layout: matrix of plot indices (NA = empty cell). patchwork aligns the panels when it is # installed; otherwise base grid viewports place the plots (axes may not line up exactly).
widths <- if (is.null(widths)) rep(1, ncol(layout)) else widths
heights <- if (is.null(heights)) rep(1, nrow(layout)) else heights
if (requireNamespace("patchwork", quietly = TRUE)) {
design <- paste(apply(layout, 1, function(r) paste(ifelse(is.na(r), "#", LETTERS[r]), collapse = "")), collapse = "\n")
print(patchwork::wrap_plots(plots, design = design, widths = widths, heights = heights, guides = "collect"))
return(invisible())
}
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(nrow(layout), ncol(layout),
widths = grid::unit(widths, "null"), heights = grid::unit(heights, "null"))))
for (i in seq_along(plots)) {
at <- which(layout == i, arr.ind = TRUE)
print(plots[[i]], vp = grid::viewport(layout.pos.row = unique(at[, 1]), layout.pos.col = unique(at[, 2])))
}
}
fit_col <- "fitted"
res_col <- "residual"
std_col <- "standardized residual"
lev_col <- "leverage"
cook_col <- "Cook's D"
lab_col <- NULL
d <- df[!is.na(df[[fit_col]]) & !is.na(df[[res_col]]), ]
d <- data.frame(fit = d[[fit_col]], res = d[[res_col]],
std = if (is.null(std_col)) (d[[res_col]] - mean(d[[res_col]])) / sd(d[[res_col]]) else d[[std_col]],
lev = if (is.null(lev_col)) NA_real_ else d[[lev_col]], cook = if (is.null(cook_col)) NA_real_ else d[[cook_col]],
lab = if (is.null(lab_col)) as.character(seq_len(nrow(d))) else as.character(d[[lab_col]]))
pt <- geom_point(colour = cs_cat[1], alpha = 0.75, size = 1.6)
p1 <- ggplot(d, aes(fit, res)) + geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) + pt +
labs(title = "Residuals vs fitted", x = fit_col, y = res_col) + theme_cs
p2 <- ggplot(d, aes(sample = std)) + stat_qq(colour = cs_cat[1], alpha = 0.75, size = 1.6) + stat_qq_line(linetype = "dashed", colour = ref_col) +
labs(title = "Normal Q–Q", x = "theoretical quantiles", y = "standardized residuals") + theme_cs
p3 <- ggplot(d, aes(fit, sqrt(abs(std)))) + pt + labs(title = "Scale–location", x = fit_col, y = "√|standardized residuals|") + theme_cs
p_coef <- sum(d$lev, na.rm = TRUE) # trace of the hat matrix = number of coefficients
h <- seq(max(min(d$lev, na.rm = TRUE), 1e-3), max(d$lev, na.rm = TRUE), length.out = 100)
contours <- do.call(rbind, lapply(c(0.5, 1), function(D) { r <- sqrt(D * p_coef * (1 - h) / h); rbind(data.frame(h = h, r = r, k = paste(D, "+")), data.frame(h = h, r = -r, k = paste(D, "-"))) }))
top <- head(d[order(-(if (all(is.na(d$cook))) abs(d$std) else d$cook)), ], 3)
p4 <- ggplot(d, aes(lev, std)) + geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) +
geom_line(data = contours, aes(h, r, group = k), colour = "#ce5342", linetype = "dotted") + pt +
geom_text(data = top, aes(label = lab), size = 2.6, hjust = -0.2, vjust = -0.4) +
coord_cartesian(ylim = c(min(d$std, -3), max(d$std, 3)) * 1.1) +
labs(title = "Residuals vs leverage", x = lev_col, y = "standardized residuals") + theme_cs
arrange(list(p1, p2, p3, p4), layout = matrix(1:4, 2, byrow = TRUE))
Needs ggplot2 · reads residual-panel-demo.csv · app theme from the optional codesplashr helper
Read the line as the counts the model expects, on a square-root scale.
Each bar hangs from the line: its height is the observed count.
A bar ending above or below zero marks a count the model under- or over-predicts.
1Callout 1: A bar past zero: more zeros than the model predicts.
2Callout 2: The line: the model's expected counts.
3Callout 3: Tail: are large counts well predicted?
Watch out
The square-root scale makes small mismatches visible but not proportional: read gaps with care.
Defaults
No settings: the chart draws one way.
Pinned in the code
Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
Square-root scale (Tukey 1977): each bar spans √expected − √observed to √expected, so a bar bottom below 0 means under-prediction and above 0 over-prediction.
Expected frequencies are Σᵢ P(Y = k | xᵢ) from the fitted model (Poisson, negative binomial, …).
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("rootogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
K = "visits"
OBS = "observed"
EXP = "expected (Poisson)"
d = df.dropna(subset=[K, OBS, EXP]).sort_values(K)
top = np.sqrt(d[EXP]) # bars hang from the expected frequency (square-root scale)
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(d[K], np.sqrt(d[OBS]), bottom=top - np.sqrt(d[OBS]), width=0.8, color=GREY, edgecolor=REF, linewidth=0.6)
ax.plot(d[K], top, color=PALETTE[0], linewidth=2, marker="o", ms=4, label=EXP)
ax.axhline(0, color="#ce5342", linewidth=1)
ax.set_xlabel(K)
ax.set_ylabel("√ frequency")
ax.legend(fontsize=8)
plt.show()
Needs pandas, numpy, matplotlib · reads rootogram-demo.csv · app theme from the optional codesplash helper
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("rootogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
K = "visits"
OBS = "observed"
EXP = "expected (Poisson)"
d = df.dropna(subset=[K, OBS, EXP]).sort_values(K)
top = np.sqrt(d[EXP])
fig = go.Figure()
fig.add_bar(x=d[K], y=np.sqrt(d[OBS]), base=top - np.sqrt(d[OBS]), marker=dict(color=GREY, line=dict(color=REF, width=0.6)), name=OBS)
fig.add_scatter(x=d[K], y=top, mode="lines+markers", line=dict(color=PALETTE[0], width=2), name=EXP)
fig.add_hline(y=0, line=dict(color="#ce5342", width=1))
fig.update_layout(xaxis_title=K, yaxis_title="√ frequency", bargap=0.2)
fig.show()
Needs pandas, numpy, plotly · reads rootogram-demo.csv · app theme from the optional codesplash helper
# Hanging rootogram — Codesplash Chart Lab (recipe "rootogram")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("rootogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
k_col <- "visits"
obs_col <- "observed"
exp_col <- "expected (Poisson)"
d <- df[!is.na(df[[k_col]]) & !is.na(df[[obs_col]]) & !is.na(df[[exp_col]]), ]
d <- data.frame(k = d[[k_col]], top = sqrt(d[[exp_col]]), bar = sqrt(d[[obs_col]]))
d <- d[order(d$k), ]
p <- ggplot(d) + geom_rect(aes(xmin = k - 0.4, xmax = k + 0.4, ymin = top - bar, ymax = top), fill = grey_col, colour = ref_col, linewidth = 0.3) +
geom_line(aes(k, top), colour = cs_cat[1], linewidth = 0.9) + geom_point(aes(k, top), colour = cs_cat[1], size = 1.8) +
geom_hline(yintercept = 0, colour = "#ce5342") + labs(x = k_col, y = "√ frequency") + theme_cs
print(p)
Needs ggplot2 · reads rootogram-demo.csv · app theme from the optional codesplashr helper
Read the letters: the post hoc test could not separate groups that share a letter.
Groups with no letters in common are.
1Callout 1: The letter above each group.
2Callout 2: Sharing a letter: the test could not separate them.
3Callout 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
# Compact letter display — Codesplash Chart Lab (recipe "cld-plot")# controls: sort=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[LABEL, C]).reset_index(drop=True)
if SORT:
d = d.sort_values(C).reset_index(drop=True)
err = dict(type="data", symmetric=False, array=d[HI] - d[C], arrayminus=d[C] - d[LO]) if LO and HI else None
fig = go.Figure()
fig.add_scatter(x=d[LABEL].astype(str), y=d[C], mode="markers", error_y=err, marker=dict(size=10, color=PALETTE[0]), showlegend=False)
fig.add_scatter(x=d[LABEL].astype(str), y=d[HI] if HI else d[C], mode="text", text=d[LET].astype(str), textposition="top center",
textfont=dict(size=13, color=REF), showlegend=False)
fig.update_xaxes(categoryorder="array", categoryarray=list(d[LABEL].astype(str)), title=LABEL)
fig.update_yaxes(title=C)
fig.show()
Needs pandas, numpy, plotly · reads cld-plot-demo.csv · app theme from the optional codesplash helper
# Compact letter display — Codesplash Chart Lab (recipe "cld-plot")# controls: sort=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cld-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feed"]] <- factor(df[["feed"]], levels = c("horsebean", "linseed", "soybean", "meatmeal", "casein", "sunflower"))
df[["letters"]] <- factor(df[["letters"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
label_col <- "feed"
c_col <- "mean weight (g)"
lo_col <- "lower"
hi_col <- "upper"
let_col <- "letters"
sort_groups <- FALSE
d <- df[!is.na(df[[label_col]]) & !is.na(df[[c_col]]), ]
d <- data.frame(lab = as.character(d[[label_col]]), m = d[[c_col]], lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]],
hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]], let = as.character(d[[let_col]]))
d$lab <- factor(d$lab, levels = if (sort_groups) d$lab[order(d$m)] else unique(d$lab))
d$top <- ifelse(is.na(d$hi), d$m, d$hi)
p <- ggplot(d, aes(lab, m)) +
{ if (!all(is.na(d$lo))) geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.15, colour = cs_cat[1]) } +
geom_point(size = 3, colour = cs_cat[1]) +
geom_text(aes(y = top, label = let), vjust = -0.8, fontface = "bold", colour = ref_col) + # shared letter = not significantly different
scale_y_continuous(expand = expansion(mult = c(0.05, 0.15))) + labs(x = label_col, y = c_col) + theme_cs
print(p)
Needs ggplot2 · reads cld-plot-demo.csv · app theme from the optional codesplashr helper
A thick bar joins groups whose ranks the test could not separate.
Groups with no bar joining them differ.
1Callout 1: A thick bar: ranks too close to separate.
2Callout 2: A group and its mean rank.
3Callout 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
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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())
y = np.arange(len(d))[::-1] + len(bars) + 1
fig = go.Figure()
for yi, (_, row) in zip(y, d.iterrows()):
fig.add_scatter(x=[row[R], row[R]], y=[0.5, yi], mode="lines", line=dict(color=GREY, width=1), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[R], y=y, mode="markers+text", marker=dict(size=9, color=PALETTE[0]), text=[f"{a} ({b})" for a, b in zip(d[LABEL], d[LET])],
textposition="middle right", showlegend=False)
for k, (ch, lo, hi) in enumerate(bars):
fig.add_scatter(x=[lo, hi], y=[k + 0.2, k + 0.2], mode="lines", line=dict(color=REF, width=5), name=ch, showlegend=False)
fig.update_yaxes(visible=False)
fig.update_xaxes(title=R)
fig.show()
Needs pandas, numpy, plotly · reads critical-difference-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "critical-difference")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("critical-difference-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("Placebo", "Low dose", "Mid dose", "High dose", "Max dose", "Active control"))
df[["letters"]] <- factor(df[["letters"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
label_col <- "arm"
r_col <- "mean rank"
let_col <- "letters"
d <- df[!is.na(df[[label_col]]) & !is.na(df[[r_col]]), ]
d <- data.frame(lab = as.character(d[[label_col]]), r = d[[r_col]], let = as.character(d[[let_col]]))
d <- d[order(d$r), ]
chars <- sort(unique(unlist(strsplit(d$let, ""))))
bars <- do.call(rbind, lapply(chars, function(ch) { rs <- d$r[grepl(ch, d$let, fixed = TRUE)]; if (length(rs) > 1) data.frame(ch = ch, lo = min(rs), hi = max(rs)) else NULL }))
nb <- if (is.null(bars)) 0 else nrow(bars)
d$y <- rev(seq_len(nrow(d))) + nb + 1
if (nb) bars$y <- seq_len(nb) - 1 + 0.2 # groups joined by a bar are not separated by the test
p <- ggplot(d, aes(r, y)) + geom_segment(aes(xend = r, y = 0.5, yend = y), colour = grey_col) + geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = paste0(lab, " (", let, ")")), hjust = -0.15, size = 3.2) +
{ if (nb) geom_segment(data = bars, aes(x = lo, xend = hi, y = y, yend = y), inherit.aes = FALSE, linewidth = 2, colour = ref_col, lineend = "round") } +
scale_x_continuous(expand = expansion(mult = c(0.08, 0.25))) + labs(x = r_col, y = NULL) + theme_cs +
theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank())
print(p)
Needs ggplot2 · reads critical-difference-demo.csv · app theme from the optional codesplashr helper
Read the curve as what the statistic does when the null hypothesis is true.
Find the observed value on the x axis.
The shaded area beyond it is the p-value; the red region is where the test would reject.
1Callout 1: The observed statistic.
2Callout 2: Shaded tails: the p-value.
3Callout 3: The rejection region for this α.
Watch out
The curve assumes the null is true: the shaded area isn't the probability that the null is true.
Defaults
Alternative
Two-sided
Which tail(s) count as at least as extreme as the observed value.
Also: Greater · Less
Show the rejection region
On
Shade the values that would lead this test to reject.
Pinned in the code
Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing inferential.
The density is the engine's exact or asymptotic null (t, χ², F, z, …) on a grid; the shaded area beyond the observed value is computed here by the trapezoid rule and approximates p on a fine grid.
Two-sided tails are reflected about the null's median (0 for t and z), the usual definition for symmetric nulls; the engine's p remains authoritative.
The rejection region is drawn from the engine's critical values at α when it publishes them.
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")# controls: alternative=two.sided, critical=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("null-distribution-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "t"
D = "density"
OBS = "observed"
CL = "critical low"
CH = "critical high"
ALT, SHOW_CRIT = "two.sided", True
d = df.dropna(subset=[X, D]).sort_values(X)
x, y = d[X].to_numpy(float), d[D].to_numpy(float).clip(min=0)
obs, cl, ch = first(OBS), first(CL), first(CH)
cum = np.concatenate([[0.0], np.cumsum(np.diff(x) * (y[1:] + y[:-1]) / 2)])
centre = np.interp(cum[-1] / 2, cum, x) # the null's median: two-sided tails reflect about it
tail = x >= obs if ALT == "greater" else x <= obs if ALT == "less" else np.abs(x - centre) >= abs(obs - centre)
fig, ax = plt.subplots(figsize=(8, 4.5))
if SHOW_CRIT and (cl is not None or ch is not None):
crit = (x <= (cl if cl is not None else -np.inf)) | (x >= (ch if ch is not None else np.inf))
ax.fill_between(x, y, where=crit, color="#c13e2e", alpha=0.16, lw=0, label="rejection region")
ax.fill_between(x, y, where=tail, color=PALETTE[0], alpha=0.4, lw=0, label="area beyond observed (p)")
ax.plot(x, y, color=plt.rcParams["text.color"], linewidth=1.6, label="null density")
ax.axvline(obs, color=PALETTE[0], linewidth=1.6)
ax.annotate(f"observed = {obs:g}", (obs, ax.get_ylim()[1]), xytext=(5, -12), textcoords="offset points", fontsize=9)
ax.set_xlabel(X)
ax.set_ylabel("density under H0")
ax.legend(fontsize=8, loc="upper left")
plt.show()
Needs pandas, numpy, matplotlib · reads null-distribution-demo.csv · app theme from the optional codesplash helper
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")# controls: alternative=two.sided, critical=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("null-distribution-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def first(col):
"""The first finite value of a column the engine repeats on every row (None if absent)."""
if col is None:
return None
v = pd.to_numeric(df[col], errors="coerce").dropna()
return float(v.iloc[0]) if len(v) else None
X = "t"
D = "density"
OBS = "observed"
CL = "critical low"
CH = "critical high"
ALT, SHOW_CRIT = "two.sided", True
d = df.dropna(subset=[X, D]).sort_values(X)
x, y = d[X].to_numpy(float), d[D].to_numpy(float).clip(min=0)
obs, cl, ch = first(OBS), first(CL), first(CH)
cum = np.concatenate([[0.0], np.cumsum(np.diff(x) * (y[1:] + y[:-1]) / 2)])
centre = np.interp(cum[-1] / 2, cum, x)
if ALT == "greater":
parts = [x >= obs]
elif ALT == "less":
parts = [x <= obs]
else:
parts = [x <= centre - abs(obs - centre), x >= centre + abs(obs - centre)]
fig = go.Figure()
if SHOW_CRIT:
for m in ([x <= cl] if cl is not None else []) + ([x >= ch] if ch is not None else []):
fig.add_scatter(x=x[m], y=y[m], fill="tozeroy", mode="none", fillcolor="rgba(193, 62, 46, 0.16)", name="rejection region")
for m in parts:
fig.add_scatter(x=x[m], y=y[m], fill="tozeroy", mode="none", fillcolor="rgba(8, 89, 172, 0.4)", name="area beyond observed")
fig.add_scatter(x=x, y=y, mode="lines", line=dict(color=REF, width=2), name="null density")
fig.add_vline(x=obs, line_color=PALETTE[0], annotation_text=f"observed = {obs:g}")
fig.update_layout(xaxis_title=X, yaxis_title="density under H0")
fig.show()
Needs pandas, numpy, plotly · reads null-distribution-demo.csv · app theme from the optional codesplash helper
# Null distribution — Codesplash Chart Lab (recipe "null-distribution")# controls: alternative=two.sided, critical=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("null-distribution-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
x_col <- "t"
d_col <- "density"
obs_col <- "observed"
cl_col <- "critical low"
ch_col <- "critical high"
alt <- "two.sided"; show_crit <- TRUE
d <- df[!is.na(df[[x_col]]) & !is.na(df[[d_col]]), ]
d <- data.frame(x = d[[x_col]], y = pmax(0, d[[d_col]]))
d <- d[order(d$x), ]
obs <- first_num(obs_col); cl <- first_num(cl_col); ch <- first_num(ch_col)
cum <- c(0, cumsum(diff(d$x) * (head(d$y, -1) + tail(d$y, -1)) / 2))
centre <- approx(cum, d$x, xout = max(cum) / 2)$y # the null's median
d$tail <- if (alt == "greater") d$x >= obs else if (alt == "less") d$x <= obs else abs(d$x - centre) >= abs(obs - centre)
d$side <- ifelse(d$x < centre, "low", "high")
d$crit <- (!is.na(cl) & d$x <= cl) | (!is.na(ch) & d$x >= ch)
p <- ggplot(d, aes(x, y)) +
{ if (show_crit) geom_area(data = d[d$crit, ], aes(group = side), fill = "#c13e2e", alpha = 0.16) } +
geom_area(data = d[d$tail, ], aes(group = side), fill = cs_cat[1], alpha = 0.4) +
geom_line(linewidth = 0.8) + geom_vline(xintercept = obs, colour = cs_cat[1], linewidth = 0.8) +
annotate("text", x = obs, y = max(d$y), label = paste("observed =", format(obs)), hjust = -0.05, vjust = 1, size = 3.2) +
labs(x = x_col, y = "density under H0") + theme_cs
print(p)
Needs ggplot2 · reads null-distribution-demo.csv · app theme from the optional codesplashr helper
Find the solid dot: your data's squared skewness and kurtosis.
Read the shape of the bootstrap cloud for how uncertain that position is.
See which family's point, line or region the cloud falls on.
1Callout 1: Your data.
2Callout 2: Bootstrap cloud: how much the position could vary.
3Callout 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.
Each panel shows the same histogram with one family's best fit.
Compare how each curve follows the bars, especially in the tails.
Use the fit table's AIC to rank them, then decide with the context.
1Callout 1: A curve that follows the bars closely.
2Callout 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
# Fitted densities by family — Codesplash Chart Lab (recipe "fit-overlay-grid")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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]
cols = 1 if len(fams) <= 1 else 2 if len(fams) <= 4 else 3
rows = int(np.ceil(len(fams) / cols))
fig = make_subplots(rows=rows, cols=cols, subplot_titles=[str(f) for f in fams], shared_xaxes=True, shared_yaxes=True)
for i, fam in enumerate(fams):
r, cc = i // cols + 1, i % cols + 1
fig.add_histogram(x=sample, histnorm="probability density", marker_color=GREY, opacity=0.7, showlegend=False, row=r, col=cc)
cv = curves[curves[F].astype(str) == str(fam)].sort_values(X)
fig.add_scatter(x=cv[X], y=cv[D], mode="lines", line_color=PALETTE[i % len(PALETTE)], name=str(fam), row=r, col=cc)
fig.show()
Needs pandas, numpy, plotly · reads fit-overlay-grid-demo.csv · app theme from the optional codesplash helper
Read the left of the chart: every observation by group, with the group means.
Read the floating axis at the right: the difference between groups.
Read its interval: how large the difference could plausibly be.
1Callout 1: The observations and mean of the first group.
2Callout 2: The mean difference with its interval.
3Callout 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
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
fig = go.Figure()
for i, (s, m, g) in enumerate([(a, m1, g1), (b, m2, g2)]):
fig.add_box(y=s, x=[str(g)] * len(s), boxpoints="all", jitter=0.4, pointpos=0, fillcolor="rgba(0,0,0,0)", line_color="rgba(0,0,0,0)", marker=dict(color=PALETTE[i], size=5, opacity=0.6), showlegend=False)
fig.add_scatter(x=[str(g)], y=[m], mode="markers", marker=dict(symbol="line-ew-open", size=40, color=REF), showlegend=False)
diff_label = f"{g2} − {g1}"
err = dict(type="data", symmetric=False, array=[hi - eff], arrayminus=[eff - lo]) if lo is not None and hi is not None else None
fig.add_scatter(x=[diff_label], y=[m1 + eff], error_y=err, mode="markers", marker=dict(size=11, color=PALETTE[1]), name="mean difference (anchored at the first mean)")
fig.add_hline(y=m1, line_dash="dot", line_color=REF)
fig.update_layout(yaxis_title=V, title="difference shown on the value axis, anchored at the first group's mean")
fig.show()
Needs pandas, numpy, plotly · reads estimation-plot-demo.csv · app theme from the optional codesplash helper
# Estimation plot (Gardner–Altman) — Codesplash Chart Lab (recipe "estimation-plot")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("estimation-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["supplement"]] <- factor(df[["supplement"]], levels = c("VC", "OJ"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
v_col <- "length"
g_col <- "supplement"
e_col <- "difference"
el_col <- "diff low"
eh_col <- "diff high"
d <- df[!is.na(df[[v_col]]) & !is.na(df[[g_col]]), ]
lv <- levels_of(d[[g_col]])[1:2]
d <- data.frame(y = d[[v_col]], g = factor(as.character(d[[g_col]]), levels = c(lv, "difference")))
d <- d[!is.na(d$g), ]
m <- tapply(d$y, d$g, mean)[lv]
eff <- first_num(e_col); if (is.na(eff)) eff <- unname(m[2] - m[1])
lo <- first_num(el_col); hi <- first_num(eh_col)
means <- data.frame(g = factor(lv, levels = levels(d$g)), m = unname(m))
est <- data.frame(g = factor("difference", levels = levels(d$g)), y = m[1] + eff, lo = m[1] + lo, hi = m[1] + hi)
p <- ggplot(d, aes(g, y)) + geom_point(aes(colour = g), position = position_jitter(width = 0.12, height = 0, seed = 1), alpha = 0.6, show.legend = FALSE) +
geom_crossbar(data = means, aes(g, m, ymin = m, ymax = m), width = 0.5, inherit.aes = FALSE) +
geom_hline(yintercept = m[1], linetype = "dotted", colour = ref_col) +
geom_pointrange(data = est, aes(g, y, ymin = lo, ymax = hi), colour = cs_cat[2], inherit.aes = FALSE) +
scale_x_discrete(drop = FALSE, labels = c(lv, paste(lv[2], "-", lv[1]))) +
scale_colour_manual(values = cs_cat) +
scale_y_continuous(sec.axis = sec_axis(~ . - m[1], name = "difference")) + # 0 at the first group's mean
labs(x = NULL, y = v_col) + theme_cs
print(p)
Needs ggplot2 · reads estimation-plot-demo.csv · app theme from the optional codesplashr helper
Read each point as the difference between groups at one quantile.
A flat line: the groups differ by a constant shift.
A sloped line: the difference grows or shrinks across the distribution.
1Callout 1: The lower quantiles barely differ.
2Callout 2: The upper quantiles differ more.
3Callout 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
# Shift function — Codesplash Chart Lab (recipe "shift-function")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
zone = None
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=labels, y=d[EST], mode="lines+markers", error_y=err, line=dict(color=GREY), marker=dict(size=9, color=PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
fig.add_hline(y=0, line_dash="dash", line_color=REF)
if zone is not None:
fig.add_hrect(y0=zone[0], y1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_xaxes(categoryorder="array", categoryarray=list(labels))
fig.update_yaxes(title="quantile difference")
fig.show()
Needs pandas, numpy, plotly · reads shift-function-demo.csv · app theme from the optional codesplash helper
# Shift function — Codesplash Chart Lab (recipe "shift-function")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("shift-function-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
label_col <- "quantile"
est_col <- "difference (ms)"
lo_col <- "low"
hi_col <- "high"
note_col <- NULL
fit_col <- NULL
d <- df[!is.na(df[[est_col]]), ]
d <- d[!duplicated(as.character(d[[label_col]])), ]
d <- data.frame(lab = factor(as.character(d[[label_col]]), levels = unique(as.character(d[[label_col]]))), est = d[[est_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
note = if (is.null(note_col)) NA_real_ else suppressWarnings(as.numeric(d[[note_col]])), fit = if (is.null(fit_col)) NA_real_ else d[[fit_col]])
d$note_txt <- ifelse(is.na(d$note), "", ifelse(d$note < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", d$note))))
zone <- NULL
p <- ggplot(d, aes(lab, est)) +
{ if (!is.null(zone)) annotate("rect", ymin = zone[1], ymax = zone[2], xmin = -Inf, xmax = Inf, fill = "#19966e", alpha = 0.1) } +
geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col) +
geom_line(aes(group = 1), colour = grey_col) +
{ if (all(!is.na(d$fit))) geom_line(aes(y = fit, group = 1), colour = cs_cat[2], linetype = "dashed", linewidth = 0.9) } +
geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.12, colour = cs_cat[1], na.rm = TRUE) +
geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = note_txt), vjust = -1.2, size = 3, colour = ref_col) +
labs(x = NULL, y = "quantile difference") + theme_cs
print(p)
Needs ggplot2 · reads shift-function-demo.csv · app theme from the optional codesplashr helper
Read each point as a group's standard deviation or other scale.
Read the bars as their intervals.
Compare them: do any intervals sit well apart?
1Callout 1: A group's spread with its interval.
2Callout 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
# Spread by group — Codesplash Chart Lab (recipe "variance-plot")# controls: log=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
zone = None
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=labels, y=d[EST], mode="markers", error_y=err, line=dict(color=GREY), marker=dict(size=9, color=PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
if zone is not None:
fig.add_hrect(y0=zone[0], y1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_xaxes(categoryorder="array", categoryarray=list(labels))
fig.update_yaxes(title="standard deviation", type="log" if False else "linear")
fig.show()
Needs pandas, numpy, plotly · reads variance-plot-demo.csv · app theme from the optional codesplash helper
# Spread by group — Codesplash Chart Lab (recipe "variance-plot")# controls: log=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("variance-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["group"]] <- factor(df[["group"]], levels = c("ctrl", "trt1", "trt2"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
label_col <- "group"
est_col <- "SD"
lo_col <- "low"
hi_col <- "high"
note_col <- NULL
fit_col <- NULL
d <- df[!is.na(df[[est_col]]), ]
d <- d[!duplicated(as.character(d[[label_col]])), ]
d <- data.frame(lab = factor(as.character(d[[label_col]]), levels = unique(as.character(d[[label_col]]))), est = d[[est_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
note = if (is.null(note_col)) NA_real_ else suppressWarnings(as.numeric(d[[note_col]])), fit = if (is.null(fit_col)) NA_real_ else d[[fit_col]])
d$note_txt <- ifelse(is.na(d$note), "", ifelse(d$note < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", d$note))))
zone <- NULL
p <- ggplot(d, aes(lab, est)) +
{ if (!is.null(zone)) annotate("rect", ymin = zone[1], ymax = zone[2], xmin = -Inf, xmax = Inf, fill = "#19966e", alpha = 0.1) } +
{ if (all(!is.na(d$fit))) geom_line(aes(y = fit, group = 1), colour = cs_cat[2], linetype = "dashed", linewidth = 0.9) } +
geom_errorbar(aes(ymin = lo, ymax = hi), width = 0.12, colour = cs_cat[1], na.rm = TRUE) +
geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = note_txt), vjust = -1.2, size = 3, colour = ref_col) +
{ if (FALSE) scale_y_log10() } +
labs(x = NULL, y = "standard deviation") + theme_cs
print(p)
Needs ggplot2 · reads variance-plot-demo.csv · app theme from the optional codesplashr helper
Read the two top rows as each correlation with its interval.
Read the bottom row as their difference.
If that interval crosses zero, the data are compatible with equal correlations.
1Callout 1: One correlation and its interval.
2Callout 2: The difference, with Zou's interval.
3Callout 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
# Comparing correlations — Codesplash Chart Lab (recipe "correlation-compare")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
zone = None
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=d[EST], y=labels, mode="markers+text" if notes is not None else "markers", text=notes, textposition="middle right", error_x=err, marker=dict(size=9, color=list(d["_color"]) if "_color" in d else PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
fig.add_vline(x=0, line_dash="dash", line_color=REF)
if zone is not None:
fig.add_vrect(x0=zone[0], x1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_yaxes(categoryorder="array", categoryarray=list(labels)[::-1])
fig.update_xaxes(title="correlation (difference)")
fig.show()
Needs pandas, numpy, plotly · reads correlation-compare-demo.csv · app theme from the optional codesplash helper
Compare linear measures (Pearson) with general ones (ξ, distance correlation).
A big general value with a small linear one suggests a nonlinear relationship.
1Callout 1: Pearson's r near zero: no straight-line trend.
2Callout 2: ξ high: a clear dependence of some other shape.
3Callout 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
# Dependence profile — Codesplash Chart Lab (recipe "dependence-profile")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
zone = None
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=d[EST], y=labels, mode="markers+text" if notes is not None else "markers", text=notes, textposition="middle right", error_x=err, marker=dict(size=9, color=list(d["_color"]) if "_color" in d else PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
fig.add_vline(x=0, line_dash="dash", line_color=REF)
if zone is not None:
fig.add_vrect(x0=zone[0], x1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_yaxes(categoryorder="array", categoryarray=list(labels)[::-1])
fig.update_xaxes(title="value of the measure")
fig.show()
Needs pandas, numpy, plotly · reads dependence-profile-demo.csv · app theme from the optional codesplash helper
# Dependence profile — Codesplash Chart Lab (recipe "dependence-profile")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("dependence-profile-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["measure"]] <- factor(df[["measure"]], levels = c("Pearson r", "Spearman ρ", "Kendall τ", "Chatterjee ξ", "Hoeffding D", "distance correlation", "HSIC"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
label_col <- "measure"
est_col <- "value"
lo_col <- NULL
hi_col <- NULL
note_col <- "p"
fit_col <- NULL
d <- df[!is.na(df[[est_col]]), ]
d <- d[!duplicated(as.character(d[[label_col]])), ]
d <- data.frame(lab = factor(as.character(d[[label_col]]), levels = rev(unique(as.character(d[[label_col]])))), est = d[[est_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
note = if (is.null(note_col)) NA_real_ else suppressWarnings(as.numeric(d[[note_col]])), fit = if (is.null(fit_col)) NA_real_ else d[[fit_col]])
d$note_txt <- ifelse(is.na(d$note), "", ifelse(d$note < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", d$note))))
zone <- NULL
p <- ggplot(d, aes(est, lab)) +
{ if (!is.null(zone)) annotate("rect", xmin = zone[1], xmax = zone[2], ymin = -Inf, ymax = Inf, fill = "#19966e", alpha = 0.1) } +
geom_vline(xintercept = 0, linetype = "dashed", colour = ref_col) +
{ if (all(!is.na(d$fit))) geom_line(aes(x = fit, group = 1), colour = cs_cat[2], linetype = "dashed", linewidth = 0.9) } +
geom_errorbar(aes(xmin = lo, xmax = hi), width = 0.15, orientation = "y", colour = cs_cat[1], na.rm = TRUE) +
geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = note_txt), hjust = -0.25, vjust = -0.8, size = 3, colour = ref_col) +
labs(x = "value of the measure", y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads dependence-profile-demo.csv · app theme from the optional codesplashr helper
Fully inside the margin: equivalent. Above the lower bound: non-inferior.
Crossing a boundary: inconclusive.
1Callout 1: An interval inside the margin.
2Callout 2: An interval crossing the boundary: inconclusive.
3Callout 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.
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
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[EST]).drop_duplicates(subset=[LABEL]).reset_index(drop=True)
labels = d[LABEL].astype(str)
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)
err = dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]) if LO and HI else None
notes = d["_note"] if "_note" in d else (d[NOTE].map(lambda p: "" if pd.isna(p) else ("p < .001" if p < 0.001 else f"p = {p:.3f}".replace("0.", "."))) if NOTE else None)
fig = go.Figure()
fig.add_scatter(x=d[EST], y=labels, mode="markers+text" if notes is not None else "markers", text=notes, textposition="middle right", error_x=err, marker=dict(size=9, color=list(d["_color"]) if "_color" in d else PALETTE[0]), showlegend=False)
if FIT and d[FIT].notna().all():
fig.add_scatter(x=labels, y=d[FIT], mode="lines", line=dict(color=PALETTE[1], dash="dash"), name="fitted")
fig.add_vline(x=0, line_dash="dash", line_color=REF)
if zone is not None:
fig.add_vrect(x0=zone[0], x1=zone[1], fillcolor="#19966e", opacity=0.1, line_width=0)
fig.update_yaxes(categoryorder="array", categoryarray=list(labels)[::-1])
fig.update_xaxes(title="difference (higher is better)")
fig.show()
Needs pandas, numpy, plotly · reads margin-plot-demo.csv · app theme from the optional codesplash helper
# Non-inferiority & equivalence margins — Codesplash Chart Lab (recipe "margin-plot")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("margin-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["comparison"]] <- factor(df[["comparison"]], levels = c("Site A", "Site B", "Site C", "Pooled"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
label_col <- "comparison"
est_col <- "difference"
lo_col <- "low"
hi_col <- "high"
note_col <- NULL
fit_col <- NULL
d <- df[!is.na(df[[est_col]]), ]
d <- d[!duplicated(as.character(d[[label_col]])), ]
d <- data.frame(lab = factor(as.character(d[[label_col]]), levels = rev(unique(as.character(d[[label_col]])))), est = d[[est_col]],
lo = if (is.null(lo_col)) NA_real_ else d[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else d[[hi_col]],
note = if (is.null(note_col)) NA_real_ else suppressWarnings(as.numeric(d[[note_col]])), fit = if (is.null(fit_col)) NA_real_ else d[[fit_col]])
d$note_txt <- ifelse(is.na(d$note), "", ifelse(d$note < 0.001, "p < .001", sub("^0", "", sprintf("p = %.3f", d$note))))
ml_col <- "margin"
mh_col <- NULL
ml <- first_num(ml_col); mh <- first_num(mh_col)
verdict <- function(lo, hi) { # Piaggio et al. (2012)
if (!is.na(ml) && !is.na(mh)) return(if (lo > ml && hi < mh) "equivalent" else if (hi < ml || lo > mh) "not equivalent" else "inconclusive")
m <- if (!is.na(ml)) ml else mh
if (is.na(m)) "inconclusive" else if (lo > max(0, m)) "superior" else if (lo > m) "non-inferior" else if (hi < m) "inferior" else "inconclusive"
}
d$note_txt <- mapply(verdict, d$lo, d$hi)
zone <- if (!is.na(ml) && !is.na(mh)) c(ml, mh) else if (!is.na(ml)) c(ml, max(d$hi, na.rm = TRUE)) else NULL
p <- ggplot(d, aes(est, lab)) +
{ if (!is.null(zone)) annotate("rect", xmin = zone[1], xmax = zone[2], ymin = -Inf, ymax = Inf, fill = "#19966e", alpha = 0.1) } +
geom_vline(xintercept = 0, linetype = "dashed", colour = ref_col) +
{ if (all(!is.na(d$fit))) geom_line(aes(x = fit, group = 1), colour = cs_cat[2], linetype = "dashed", linewidth = 0.9) } +
geom_errorbar(aes(xmin = lo, xmax = hi), width = 0.15, orientation = "y", colour = cs_cat[1], na.rm = TRUE) +
geom_point(size = 2.6, colour = cs_cat[1]) +
geom_text(aes(label = note_txt), hjust = -0.25, vjust = -0.8, size = 3, colour = ref_col) +
labs(x = "difference (higher is better)", y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads margin-plot-demo.csv · app theme from the optional codesplashr helper
Compare the solid fit line with the dashed identity line.
An intercept away from zero suggests constant bias; a slope away from 1, proportional bias.
1Callout 1: Fit line: how one method tracks the other.
2Callout 2: Identity line: perfect agreement.
3Callout 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
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if None not in (bl, bh, al, ah):
fig.add_scatter(x=np.r_[lim, lim[::-1]], y=np.r_[al + bh * lim, (ah + bl * lim)[::-1]], fill="toself", mode="none", fillcolor="rgba(8, 89, 172, 0.1)", name="slope CI limits")
fig.add_scatter(x=lim, y=lim, mode="lines", line=dict(color=REF, dash="dash"), name="identity")
fig.add_scatter(x=d[X], y=d[Y], mode="markers", marker=dict(color=GREY, size=6), name="pairs")
if b is not None and a is not None:
fig.add_scatter(x=lim, y=a + b * lim, mode="lines", line=dict(color=PALETTE[0], width=3), name=f"y = {a:.3g} + {b:.3g}·x")
fig.update_xaxes(range=list(lim), title=X)
fig.update_yaxes(range=list(lim), title=Y, scaleanchor="x")
fig.show()
Needs pandas, numpy, plotly · reads method-comparison-demo.csv · app theme from the optional codesplash helper
# Method comparison — Codesplash Chart Lab (recipe "method-comparison")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("method-comparison-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
first_num <- function(col) { if (is.null(col)) return(NA_real_); v <- suppressWarnings(as.numeric(df[[col]])); v <- v[is.finite(v)]; if (length(v)) v[1] else NA_real_ }
x_col <- "laboratory"
y_col <- "meter"
b_col <- "slope"
a_col <- "intercept"
bl_col <- "slope low"
bh_col <- "slope high"
al_col <- "intercept low"
ah_col <- "intercept high"
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), ]
d <- data.frame(x = d[[x_col]], y = d[[y_col]])
lim <- range(c(d$x, d$y))
b <- first_num(b_col); a <- first_num(a_col); bl <- first_num(bl_col); bh <- first_num(bh_col); al <- first_num(al_col); ah <- first_num(ah_col)
band <- data.frame(x = lim, lo = al + bh * lim, hi = ah + bl * lim) # slope limits with the opposite intercept limits
p <- ggplot(d, aes(x, y)) +
{ if (!anyNA(c(bl, bh, al, ah))) geom_ribbon(data = band, aes(x, ymin = lo, ymax = hi), inherit.aes = FALSE, fill = cs_cat[1], alpha = 0.1) } +
geom_abline(intercept = 0, slope = 1, linetype = "dashed", colour = ref_col) +
geom_point(colour = grey_col) +
{ if (!is.na(b)) geom_abline(intercept = a, slope = b, colour = cs_cat[1], linewidth = 1) } +
coord_equal(xlim = lim, ylim = lim) + labs(x = x_col, y = y_col) + theme_cs
print(p)
Needs ggplot2 · reads method-comparison-demo.csv · app theme from the optional codesplashr helper
Read one panel per predictor; the x axis is the quantile τ.
Compare the line with the dashed OLS estimate.
A rising line means the predictor's effect is stronger in the upper part of the outcome.
1Callout 1: The coefficient at low quantiles.
2Callout 2: It grows across quantiles here.
3Callout 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
# Quantile process — Codesplash Chart Lab (recipe "qr-process")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = make_subplots(rows=rows, cols=cols, subplot_titles=[str(t) for t in terms])
for i, term in enumerate(terms):
r, cc = i // cols + 1, i % cols + 1
s = (d[d[TERM].astype(str) == str(term)] if TERM else d).sort_values(T)
if LO and HI:
fig.add_scatter(x=np.r_[s[T], s[T][::-1]], y=np.r_[s[HI], s[LO][::-1]], fill="toself", mode="none", fillcolor="rgba(8, 89, 172, 0.18)", showlegend=False, row=r, col=cc)
fig.add_scatter(x=s[T], y=s[E], mode="lines+markers", line_color=PALETTE[0], showlegend=False, row=r, col=cc)
if O and s[O].notna().any():
fig.add_hline(y=float(s[O].dropna().iloc[0]), line_dash="dash", line_color=REF, row=r, col=cc)
fig.show()
Needs pandas, numpy, plotly · reads qr-process-demo.csv · app theme from the optional codesplash helper
Read the top path: exposure → mediator (a), mediator → outcome (b).
Read the bottom path: the direct effect (c′).
Read the indirect effect (a×b) at the bottom with its interval.
1Callout 1: Path a: exposure to mediator.
2Callout 2: Path b: mediator to outcome.
3Callout 3: Direct effect.
4Callout 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
# Mediation path diagram — Codesplash Chart Lab (recipe "mediation-path")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for k, (x, y) in pos.items():
fig.add_annotation(x=x, y=y, text=f"<b>{names[k]}</b>", showarrow=False, bordercolor=REF, borderpad=8, font=dict(size=13))
for (x0, y0), (x1, y1) in [((0.16, 0.32), (0.43, 0.75)), ((0.57, 0.75), (0.84, 0.32)), ((0.22, 0.25), (0.78, 0.25))]:
fig.add_annotation(x=x1, y=y1, ax=x0, ay=y0, xref="x", yref="y", axref="x", ayref="y", showarrow=True, arrowhead=2, arrowwidth=1.6, arrowcolor=PALETTE[0])
for x, y, t in [(0.27, 0.56, "a " + label("a")), (0.73, 0.56, "b " + label("b")), (0.5, 0.31, "c′ " + label("c_prime")), (0.5, 0.1, "indirect " + label("acme")), (0.5, 0.02, "total " + label("total"))]:
fig.add_annotation(x=x, y=y, text=t, showarrow=False, font=dict(size=11))
fig.update_xaxes(visible=False, range=[0, 1])
fig.update_yaxes(visible=False, range=[0, 1])
fig.show()
Needs pandas, numpy, plotly · reads mediation-path-demo.csv · app theme from the optional codesplash helper
Read the line as the cumulative sum of recursive residuals in time order.
A stable regression keeps it near zero, inside the bounds.
Touching a bound suggests the coefficients have moved.
1Callout 1: Reaches the bound: coefficients are unstable.
2Callout 2: The upper 5% bound.
3Callout 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
# Recursive residuals (CUSUM) — Codesplash Chart Lab (recipe "recursive-residual")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for b in (BL, BH):
if b:
fig.add_scatter(x=d[I], y=d[b], mode="lines", line=dict(color="#c13e2e", dash="dash"), name="5% bound")
fig.add_scatter(x=d[I], y=d[V], mode="lines", line=dict(color=REF, width=2), name=V)
fig.update_layout(xaxis_title=I, yaxis_title=V)
fig.show()
Needs pandas, numpy, plotly · reads recursive-residual-demo.csv · app theme from the optional codesplash helper
Compare the dashed prior with the solid posterior: the data moved belief from one to the other.
Compare heights at the test value: if the posterior is lower there, the data favour an effect.
Read the shaded credible interval: where the effect probably lies, given the prior.
1Callout 1: The prior's height at the test value.
2Callout 2: The posterior's height at the test value.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=prior[X], y=prior[D], mode="lines", line=dict(color=REF, dash="dash"), name="prior")
fig.add_scatter(x=post[X], y=post[D], mode="lines", line=dict(color=PALETTE[0], width=2.5), name="posterior")
fig.add_vline(x=POINT, line_dash="dot", line_color=REF)
fig.update_layout(xaxis_title=X, yaxis_title="density")
fig.show()
Needs pandas, numpy, plotly · reads prior-posterior-demo.csv · app theme from the optional codesplash helper
# Prior and posterior — Codesplash Chart Lab (recipe "prior-posterior")# controls: point=0, ci_low=0, ci_high=0, cred=0.95, bf10=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("prior-posterior-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["curve"]] <- factor(df[["curve"]], levels = c("Prior", "Posterior"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
X <- "δ (standardized effect)"
D <- "density"
K <- "curve"
POINT <- 0 # the test value
d <- data.frame(x = df[[X]], y = df[[D]], curve = ifelse(grepl("prior", as.character(df[[K]]), ignore.case = TRUE), "prior", "posterior"))
p <- ggplot(d, aes(x, y, colour = curve, linetype = curve)) +
geom_line(linewidth = 0.8) +
geom_vline(xintercept = POINT, colour = ref_col, linetype = "dotted") +
scale_colour_manual(values = c(posterior = cs_cat[[1]], prior = ref_col), name = NULL) +
scale_linetype_manual(values = c(posterior = "solid", prior = "dashed"), name = NULL) +
labs(x = X, y = "density") + theme_cs
print(p)
Needs ggplot2 · reads prior-posterior-demo.csv · app theme from the optional codesplashr helper
Read the curve as the Bayes factor at each prior width.
Find your chosen width on the curve.
If the curve stays in one evidence band across widths, the conclusion doesn't depend on the prior width.
1Callout 1: Your chosen prior width.
2Callout 2: Evidence band labels.
3Callout 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
# Bayes factor robustness — Codesplash Chart Lab (recipe "bf-robustness")# controls: chosen=0.707, logX=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=d[X], y=d[B], mode="lines", line=dict(color=PALETTE[0], width=2.5), name="BF₁₀")
for cut in CUTS:
fig.add_hline(y=cut, line_color=REF, line_width=1 if cut == 1 else 0.4, line_dash="dash" if cut == 1 else "dot")
fig.add_vline(x=0.707, line_color=REF)
fig.update_layout(xaxis_title="prior width r", yaxis_title="BF₁₀ (log scale)", yaxis_type="log")
fig.show()
Needs pandas, numpy, plotly · reads bf-robustness-demo.csv · app theme from the optional codesplash helper
A steady path is reassuring; big swings mean the result rests on a few rows.
1Callout 1: The final Bayes factor.
2Callout 2: BF = 1: no evidence either way.
3Callout 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
# Sequential Bayes factor — Codesplash Chart Lab (recipe "bf-sequential")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=d[X], y=d[B], mode="lines", line=dict(color=PALETTE[0], width=2.5), name="BF₁₀")
for cut in CUTS:
fig.add_hline(y=cut, line_color=REF, line_width=1 if cut == 1 else 0.4, line_dash="dash" if cut == 1 else "dot")
fig.update_layout(xaxis_title="observations so far", yaxis_title="BF₁₀ (log scale)", yaxis_type="log")
fig.show()
Needs pandas, numpy, plotly · reads bf-sequential-demo.csv · app theme from the optional codesplash helper
Read each bar as how much more the data support that model than the intercept-only model.
Longest bar: the best-supported model.
Read the posterior probability to weigh models against each other.
1Callout 1: The best-supported model.
2Callout 2: Its Bayes factor and posterior probability.
3Callout 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
# Model Bayes factors — Codesplash Chart Lab (recipe "bf-models")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Bar(x=d["bf"], y=d["model"], orientation="h", marker_color=PALETTE[0], text=[f"{v:.3g}" + (f" · {q:.0%}" if pd.notna(q) else "") for v, q in zip(d["bf"], d["posterior"])]))
fig.update_layout(xaxis_type="log", xaxis_title="Bayes factor against the intercept-only model (log scale)", yaxis_autorange="reversed")
fig.show()
Needs pandas, numpy, plotly · reads bf-models-demo.csv · app theme from the optional codesplash helper
Read x as time and y as the accumulated hazard, H(t) = −log S(t).
Read the slope as the failure rate at that time: steeper means failures are coming faster.
A straight line through the origin is a constant rate, as an exponential lifetime has.
1Callout 1: A shallow stretch: few failures for the time at risk.
2Callout 2: A steep stretch: the rate is higher.
3Callout 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
# Cumulative hazard — Codesplash Chart Lab (recipe "cumhaz")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, t, y) in enumerate(curves()):
fig.add_scatter(x=t, y=y, mode="lines", name=name, line=dict(color=PALETTE[i % len(PALETTE)], shape="hv"))
fig.update_layout(title="Cumulative hazard: a straight line means a constant hazard", xaxis_title=T, yaxis_title="H(t) = −log S(t)")
fig.show()
Needs pandas, numpy, plotly · reads cumhaz-demo.csv · app theme from the optional codesplash helper
# Cumulative hazard — Codesplash Chart Lab (recipe "cumhaz")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cumhaz-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("control", "treated"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "days"
y_col <- "survival"
g_col <- "arm"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & !is.na(df[[t_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
t <- d[[t_col]]
v <- d[[y_col]]
keep <- v > 0
data.frame(x = t[keep], y = (function(v) -log(v))(v[keep]), g = factor(g, levels = lv))
}))
p <- ggplot(pd, aes(x, y, colour = g)) + geom_step() + scale_colour_manual(values = cs_cat, name = NULL) +
labs(x = t_col, y = "H(t) = −log S(t)", title = "Cumulative hazard: a straight line means a constant hazard") + theme_cs
print(p)
Needs ggplot2 · reads cumhaz-demo.csv · app theme from the optional codesplashr helper
Read each curve as the share still event-free over time, and τ as the horizon marked by the dashed line.
Read the area under a curve up to τ as that group's restricted mean survival time, given in the legend.
Read the shaded gap between the curves as the difference in mean event-free time up to τ.
1Callout 1: τ: the area stops here.
2Callout 2: The shared area: time both groups have on average.
3Callout 3: The gap: extra event-free time for one group.
4Callout 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
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")# controls: tau=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
fig = go.Figure()
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]))
fig.add_scatter(x=tt, y=ss, mode="lines", name=f"{name}: RMST {rmst:.4g}", fill="tozeroy", line=dict(color=PALETTE[i % len(PALETTE)], shape="hv"))
fig.add_vline(x=tau, line_dash="dash", line_color=REF)
fig.update_layout(title=f"Restricted mean survival up to {tau:g}", xaxis_title=T, yaxis_title="Survival probability")
fig.show()
Needs pandas, numpy, plotly · reads rmst-area-demo.csv · app theme from the optional codesplash helper
# Restricted mean survival area — Codesplash Chart Lab (recipe "rmst-area")# controls: tau=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("rmst-area-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("control", "treated"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "days"
y_col <- "survival"
g_col <- "arm"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
TAU <- 0
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
tau <- if (TAU > 0) TAU else min(vapply(lv, function(g) max(df[[t_col]][grp == g], na.rm = TRUE), numeric(1))) # the shorter follow-up
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & df[[t_col]] <= tau, , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
tt <- c(d[[t_col]], tau)
ss <- c(d[[y_col]], d[[y_col]][nrow(d)])
rmst <- sum(diff(tt) * ss[-length(ss)]) # area under the step curve
data.frame(t = tt, s = ss, g = factor(sprintf("%s: RMST %.4g", g, rmst)))
}))
p <- ggplot(pd, aes(t, s, colour = g)) + geom_step() + geom_vline(xintercept = tau, colour = ref_col, linetype = "dashed") +
scale_colour_manual(values = cs_cat, name = NULL) +
labs(x = t_col, y = "Survival probability", title = sprintf("Restricted mean survival up to %g", tau)) + theme_cs
print(p)
Needs ggplot2 · reads rmst-area-demo.csv · app theme from the optional codesplashr helper
Machine learning
Model evaluation and explanation: PR and gain curves, thresholds, importance, SHAP, PDP/ALE, tuning and validation splits.
Read the x axis as how much of the list you act on, top-scored first.
Read the y axis as the share of all positives reached.
Compare with the diagonal: random targeting.
1Callout 1: Acting on the top 20% reaches this share of the positives.
2Callout 2: Diagonal: random targeting.
3Callout 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
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")# controls: mode=gain
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
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 = go.Figure()
if MODE == "gain":
fig.add_scatter(x=[0, 1], y=[0, 1], mode="lines", line=dict(color="grey", dash="dash", width=1), name="random")
else:
fig.add_hline(y=1, line=dict(color="grey", dash="dash", width=1))
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]
fig.add_scatter(x=d[F], y=y, mode="lines+markers", name=name or GAIN, line=dict(color=PALETTE[i % len(PALETTE)], width=2), marker=dict(size=5))
fig.update_layout(xaxis_title=F, yaxis_title=GAIN if MODE == "gain" else "lift (× random)")
fig.show()
Needs pandas, numpy, plotly · reads lift-gain-demo.csv · app theme from the optional codesplash helper
# Cumulative gain and lift — Codesplash Chart Lab (recipe "lift-gain")# controls: mode=gain
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("lift-gain-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]], levels = c("Gradient boosting", "Random forest"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
f_col <- "share of customers contacted"
gain_col <- "share of churners reached"
lift_col <- NULL
curve_col <- "model"
mode <- "gain" # "gain" or "lift"
d <- data.frame(f = df[[f_col]], gain = df[[gain_col]], g = if (is.null(curve_col)) "" else factor(as.character(df[[curve_col]]), levels = levels_of(df[[curve_col]])))
d$lift <- if (is.null(lift_col)) ifelse(d$f > 0, d$gain / d$f, NA) else df[[lift_col]]
d <- d[!is.na(d$f), ]
d$y <- if (mode == "gain") d$gain else d$lift
d <- d[!is.na(d$y), ]
p <- ggplot(d[order(d$g, d$f), ], aes(f, y, colour = g)) +
{ if (mode == "gain") geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "grey60") else geom_hline(yintercept = 1, linetype = "dashed", colour = "grey60") } +
geom_line(linewidth = 0.9) + geom_point(size = 1.2) +
scale_colour_manual(values = cs_cat, guide = if (is.null(curve_col)) "none" else "legend") +
labs(x = f_col, y = if (mode == "gain") gain_col else "lift (× random)", colour = NULL) + theme_cs
print(p)
Needs ggplot2 · reads lift-gain-demo.csv · app theme from the optional codesplashr helper
Read each curve as one metric as the threshold moves.
Find the marker: the threshold chosen now.
Pick the threshold from your error costs, not from where the lines cross.
1Callout 1: The chosen threshold.
2Callout 2: Each metric's value at it.
3Callout 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
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")# controls: marker=0.5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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
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 = go.Figure()
fig.add_vline(x=MARKER, line=dict(color=REF, dash="dash", width=1))
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
at = float(np.interp(MARKER, d[T], d[V]))
many = len(series) > 1 # several metrics: a dash and a marker shape each, as in the app
fig.add_scatter(x=d[T], y=d[V], mode="lines", name=f"{name or V} ({at:.2f})", line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if many else "solid"))
fig.add_scatter(x=[MARKER], y=[at], mode="markers", marker=dict(color=col, size=8, symbol=SERIES_MARKERS[i % 8] if many else "circle"), showlegend=False)
fig.update_layout(xaxis_title=T, yaxis_title=V)
fig.show()
Needs pandas, numpy, plotly · reads threshold-metrics-demo.csv · app theme from the optional codesplash helper
# Metrics across thresholds — Codesplash Chart Lab (recipe "threshold-metrics")# controls: marker=0.5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("threshold-metrics-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["metric"]] <- factor(df[["metric"]], levels = c("precision", "recall", "F1", "specificity"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "probability threshold"
v_col <- "value"
m_col <- "metric"
marker <- 0.5 # the chosen threshold
d <- data.frame(t = df[[t_col]], v = df[[v_col]], m = if (is.null(m_col)) v_col else factor(as.character(df[[m_col]]), levels = levels_of(df[[m_col]])))
d <- d[!is.na(d$t) & !is.na(d$v), ]
d <- d[order(d$m, d$t), ]
at <- do.call(rbind, lapply(split(d, d$m, drop = TRUE), function(s) data.frame(m = s$m[1], t = marker, v = stats::approx(s$t, s$v, xout = marker, rule = 2, ties = mean)$y)))
p <- ggplot(d, aes(t, v, colour = m)) + geom_vline(xintercept = marker, linetype = "dashed", colour = ref_col) +
geom_line(aes(linetype = m), linewidth = 0.9) + geom_point(data = at, aes(shape = m), size = 2.4) + # dash and marker per metric, as in the app
geom_text(data = at, aes(label = sprintf("%.2f", v)), hjust = -0.25, size = 3, show.legend = FALSE) +
scale_colour_manual(values = cs_cat) + scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = t_col, y = v_col, colour = NULL, linetype = NULL, shape = NULL) + theme_cs
print(p)
Needs ggplot2 · reads threshold-metrics-demo.csv · app theme from the optional codesplashr helper
Read bar length as how much the model relies on that feature.
Check the whiskers: overlapping features may not really differ.
Check which kind of importance is on the axis.
1Callout 1: The top feature.
2Callout 2: Whisker: how much it varies across repeats.
3Callout 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
# Feature importance — Codesplash Chart Lab (recipe "importance-bar")# controls: top=20
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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]
err = dict(type="data", symmetric=False, array=d[HI] - d[IMP], arrayminus=d[IMP] - d[LO]) if LO and HI else None
fig = go.Figure(go.Bar(x=d[IMP], y=d[FEAT].astype(str), orientation="h", marker_color=PALETTE[0], error_x=err))
fig.update_layout(xaxis_title=IMP, yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads importance-bar-demo.csv · app theme from the optional codesplash helper
Read each row as a feature, ranked by average impact.
Read a dot's position: to the right pushes the prediction up.
Read colour as the feature's value: red right and blue left means high values raise predictions.
1Callout 1: Top row: the feature with the largest average impact.
2Callout 2: Red on the right: high values push predictions up.
3Callout 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
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")# controls: top=20
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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()
ypos = {f: len(order) - 1 - i for i, f in enumerate(order)}
d = d[d[FEAT].isin(order)]
rng = np.random.default_rng(1)
y = d[FEAT].map(ypos) + rng.uniform(-0.32, 0.32, len(d))
marker = dict(size=4, opacity=0.8, color=d[V], colorscale=[[0, DIV[-1]], [1, DIV[0]]], colorbar=dict(title=V)) if V else dict(size=4, color=PALETTE[0])
fig = go.Figure(go.Scattergl(x=d[SHAP], y=y, mode="markers", marker=marker, text=d[FEAT]))
fig.add_vline(x=0, line=dict(color="grey", width=1))
fig.update_yaxes(tickvals=[ypos[f] for f in order], ticktext=order)
fig.update_layout(xaxis_title=SHAP)
fig.show()
Needs pandas, numpy, plotly · reads shap-beeswarm-demo.csv · app theme from the optional codesplash helper
# SHAP beeswarm — Codesplash Chart Lab (recipe "shap-beeswarm")# controls: top=20
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("shap-beeswarm-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feature"]] <- factor(df[["feature"]], levels = c("glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
feat_col <- "feature"
shap_col <- "SHAP value (log-odds)"
v_col <- "feature value (rank-scaled)"
top_n <- 20
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[shap_col]]), ]
d <- data.frame(f = as.character(d[[feat_col]]), s = d[[shap_col]], v = if (is.null(v_col)) NA_real_ else d[[v_col]])
rank <- sort(tapply(abs(d$s), d$f, mean), decreasing = TRUE) # by mean |SHAP|
keep <- head(names(rank), top_n)
d <- d[d$f %in% keep, ]
d$f <- factor(d$f, levels = rev(keep))
p <- ggplot(d, aes(s, f, colour = v)) + geom_vline(xintercept = 0, colour = "grey60") +
geom_point(position = position_jitter(width = 0, height = 0.3, seed = 1), size = 0.8, alpha = 0.8) + # jitter stands in for the beeswarm
scale_colour_gradient(low = div_ramp[length(div_ramp)], high = div_ramp[1], na.value = cs_cat[1]) +
labs(x = shap_col, y = NULL, colour = v_col) + theme_cs
print(p)
Needs ggplot2 · reads shap-beeswarm-demo.csv · app theme from the optional codesplashr helper
Read the shape: how a feature's value changes its contribution.
Read the vertical spread at one value: another feature is modifying it.
Read the colour to see which one.
1Callout 1: Crossing zero: the feature's effect flips sign here.
2Callout 2: Rising with age.
3Callout 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
# SHAP dependence — Codesplash Chart Lab (recipe "shap-dependence")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
marker = dict(size=6, opacity=0.8, color=d[COL], colorscale=[[0, DIV[-1]], [1, DIV[0]]], colorbar=dict(title=COL)) if COL else dict(size=6, color=PALETTE[0])
fig = go.Figure(go.Scatter(x=d[V], y=d[SHAP], mode="markers", marker=marker))
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.update_layout(xaxis_title=V, yaxis_title=SHAP)
fig.show()
Needs pandas, numpy, plotly · reads shap-dependence-demo.csv · app theme from the optional codesplash helper
# SHAP dependence — Codesplash Chart Lab (recipe "shap-dependence")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("shap-dependence-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
v_col <- "age (years)"
shap_col <- "SHAP value (log-odds)"
col_col <- "BMI"
d <- df[!is.na(df[[v_col]]) & !is.na(df[[shap_col]]), ]
d <- data.frame(x = d[[v_col]], s = d[[shap_col]], k = if (is.null(col_col)) NA_real_ else d[[col_col]])
p <- ggplot(d, aes(x, s, colour = k)) + geom_hline(yintercept = 0, colour = "grey60") + geom_point(alpha = 0.8, size = 1.4) +
scale_colour_gradient(low = div_ramp[length(div_ramp)], high = div_ramp[1], na.value = cs_cat[1], guide = if (is.null(col_col)) "none" else "colourbar") +
labs(x = v_col, y = shap_col, colour = col_col) + theme_cs
print(p)
Needs ggplot2 · reads shap-dependence-demo.csv · app theme from the optional codesplashr helper
Each bar pushes the prediction up or down, largest first.
End at the final value: this row's prediction.
1Callout 1: Baseline: the model's average output.
2Callout 2: This feature pushes the prediction up most.
3Callout 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
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")# controls: base=0, prediction=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[FEAT, CON]).reset_index(drop=True)
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))]
pred = PRED_SET if PRED_SET != 0 else float(BASE + d[CON].sum())
fig = go.Figure(go.Waterfall(orientation="h", y=labels[::-1], x=list(d[CON])[::-1], base=BASE, measure=["relative"] * len(d),
increasing=dict(marker=dict(color=DIV[0])), decreasing=dict(marker=dict(color=DIV[-1])), connector=dict(line=dict(color="grey", width=0.5))))
fig.add_vline(x=BASE, line=dict(color="grey", dash="dash", width=1))
fig.add_vline(x=pred, line=dict(color=REF, width=1.2))
fig.update_layout(xaxis_title=f"E[f(x)] = {BASE:.3g}, f(x) = {pred:.3g}")
fig.show()
Needs pandas, numpy, plotly · reads shap-waterfall-demo.csv · app theme from the optional codesplash helper
# SHAP waterfall — Codesplash Chart Lab (recipe "shap-waterfall")# controls: base=0, prediction=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("shap-waterfall-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["feature"]] <- factor(df[["feature"]], levels = c("glucose", "BMI", "age", "pedigree", "pregnancies", "blood pressure", "4 other features"))
df[["value"]] <- factor(df[["value"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
feat_col <- "feature"
con_col <- "SHAP value (log-odds)"
v_col <- "value"
base <- 0; pred_set <- 0 # E[f(x)]; f(x) when given (0 = base + sum of SHAP)
d <- df[!is.na(df[[feat_col]]) & !is.na(df[[con_col]]), ]
v <- if (is.null(v_col)) rep(NA, nrow(d)) else as.character(d[[v_col]])
d <- data.frame(lab = ifelse(is.na(v), as.character(d[[feat_col]]), paste(d[[feat_col]], "=", v)), con = d[[con_col]])
d$end <- base + cumsum(d$con); d$start <- d$end - d$con
d$row <- factor(seq_len(nrow(d)), levels = rev(seq_len(nrow(d)))) # first feature at the top
pred <- if (pred_set != 0) pred_set else d$end[nrow(d)]
p <- ggplot(d) + geom_rect(aes(xmin = start, xmax = end, ymin = as.numeric(row) - 0.3, ymax = as.numeric(row) + 0.3, fill = con > 0)) +
geom_text(aes(x = pmax(start, end), y = as.numeric(row), label = sprintf("%+.3g", con)), hjust = -0.15, size = 3) +
geom_vline(xintercept = base, linetype = "dashed", colour = "grey60") + geom_vline(xintercept = pred, colour = ref_col) +
scale_fill_manual(values = c("FALSE" = div_ramp[length(div_ramp)], "TRUE" = div_ramp[1]), guide = "none") +
scale_y_continuous(breaks = seq_len(nrow(d)), labels = rev(d$lab)) + scale_x_continuous(expand = expansion(mult = c(0.05, 0.14))) + # room for the value labels
labs(x = sprintf("E[f(x)] = %.3g, f(x) = %.3g", base, pred), y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads shap-waterfall-demo.csv · app theme from the optional codesplashr helper
Read the curve as the feature's effect, relative to the average prediction.
Read its slope: how predictions change locally.
Check the band for uncertainty, and the rug for where data exists.
1Callout 1: Crosses zero: predictions here equal the average.
2Callout 2: Higher values lift predictions.
3Callout 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
# Accumulated local effects — Codesplash Chart Lab (recipe "ale-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "linear"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape))
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads ale-plot-demo.csv · app theme from the optional codesplash helper
# Accumulated local effects — Codesplash Chart Lab (recipe "ale-plot")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ale-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "daylight (minutes)"
y_col <- "effect on daily rentals"
lo_col <- "lower"
hi_col <- "upper"
g_col <- NULL
d <- data.frame(x = df[[x_col]], y = df[[y_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d <- d[!is.na(d$x) & !is.na(d$y), ]
d <- d[order(d$g, d$x), ]
p <- ggplot(d, aes(x, y, colour = g, fill = g)) +
geom_hline(yintercept = 0, colour = "grey50") +
{ if (!all(is.na(d$lo))) geom_ribbon(aes(ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } + geom_line(linewidth = 0.9) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = x_col, y = y_col, colour = NULL) + theme_cs
print(p)
Needs ggplot2 · reads ale-plot-demo.csv · app theme from the optional codesplashr helper
Compare the training and validation lines as rows grow.
A persistent gap suggests overfitting; more data may help.
Both low and close together suggests a model too simple; more data won't help much.
1Callout 1: Training score.
2Callout 2: Validation score: rises with more rows.
3Callout 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
# Learning curve — Codesplash Chart Lab (recipe "learning-curve")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "linear"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads learning-curve-demo.csv · app theme from the optional codesplash helper
Read each row as one fold of the plan, rows binned in order.
Colours mark training, validation and test.
Check for leaks: no validation or test bin should come before training in a time-ordered plan.
1Callout 1: The final fit.
2Callout 2: One fold's training rows.
3Callout 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
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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 = go.Figure()
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:
h = (s[col].fillna(0) / total).fillna(0).to_numpy() * 0.8
pattern = dict(shape=SERIES_HATCHES[1] if label == "test" else "", fgcolor=HATCH_INK, fillmode="overlay") # the held-out test set is hatched
fig.add_bar(x=s[BIN], y=h, base=bottom, marker=dict(color=colour, line=dict(width=0), pattern=pattern), width=1.0, name=label, showlegend=r == 0, legendgroup=label)
bottom = bottom + h
fig.update_yaxes(tickvals=list(range(len(rows)))[::-1], ticktext=rows)
fig.update_layout(barmode="overlay", bargap=0, xaxis_title=BIN)
fig.show()
Needs pandas, numpy, plotly · reads split-strip-demo.csv · app theme from the optional codesplash helper
# Validation fold strip — Codesplash Chart Lab (recipe "split-strip")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("split-strip-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["fold"]] <- factor(df[["fold"]], levels = c("Final", "Fold 1", "Fold 2", "Fold 3", "Fold 4"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
row_col <- "fold"
bin_col <- "rows in time order (binned)"
tr_col <- "train"
va_col <- "validation"
te_col <- "test"
ex_col <- "excluded"
d <- df[!is.na(df[[row_col]]) & !is.na(df[[bin_col]]), ]
rows <- levels_of(d[[row_col]])
cols <- c(train = tr_col, validation = va_col, test = te_col, excluded = if (is.null(ex_col)) NA else ex_col)
cols <- cols[!is.na(cols)]
long <- do.call(rbind, lapply(names(cols), function(k) data.frame(row = as.character(d[[row_col]]), bin = d[[bin_col]], part = k, n = d[[cols[[k]]]])))
long$n[is.na(long$n)] <- 0
long$part <- factor(long$part, levels = rev(names(cols)))
long$row <- factor(long$row, levels = rows)
p <- ggplot(long, aes(bin, n, fill = part)) + geom_col(position = "fill", width = 1) + # each bin split by share
facet_grid(row ~ ., switch = "y") +
# the held-out test set is hatched (texture 2 of cs_textures), as in the app
scale_fill_manual(values = list(train = cs_cat[1], validation = cs_cat[2], test = cs_textures(list(cs_cat[3]), idx = 2)[[1]], excluded = grey_col), breaks = names(cols)) +
labs(x = bin_col, y = NULL, fill = NULL) + theme_cs +
theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), strip.text.y.left = element_text(angle = 0), panel.spacing = unit(2, "pt"), legend.position = "bottom")
print(p)
Needs ggplot2 · reads split-strip-demo.csv · app theme from the optional codesplashr helper
Read the top axis as mean rank across folds: lower is better.
A thick bar joins models the test could not separate.
Compare distances with the critical difference at the top.
1Callout 1: The critical difference.
2Callout 2: A thick bar: these models can't be separated.
3Callout 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
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")# controls: cd=1.93
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=ranks, y=[0] * len(ranks), mode="markers+text", text=names, textposition="top center", marker=dict(color=PALETTE[0], size=10), showlegend=False)
for k, (i, j) in enumerate(cliques):
fig.add_scatter(x=[ranks[i], ranks[j]], y=[-0.12 - 0.06 * k] * 2, mode="lines", line=dict(color="black", width=4), showlegend=False)
fig.update_layout(xaxis_title="Mean rank across folds (1 = best)", yaxis=dict(visible=False, range=[-0.5, 0.5]))
fig.show()
Needs pandas, numpy, plotly · reads cd-diagram-demo.csv · app theme from the optional codesplash helper
# Critical-difference diagram — Codesplash Chart Lab (recipe "cd-diagram")# controls: cd=1.93
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cd-diagram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["model"]] <- factor(df[["model"]])
L <- "model"
R <- "mean rank"
CD <- 1.93 # critical difference
d <- data.frame(label = as.character(df[[L]]), rank = df[[R]])
d <- d[is.finite(d$rank), ]
d <- d[order(d$rank, d$label), ]
cl <- list(); last <- 0 # Demšar: maximal runs of models within CD of each other
if (!is.null(CD)) for (i in seq_len(nrow(d))) {
j <- i
while (j < nrow(d) && d$rank[j + 1] - d$rank[i] <= CD + 1e-12) j <- j + 1
if (j > i && j > last) { cl[[length(cl) + 1]] <- data.frame(x = d$rank[i], xend = d$rank[j], y = -0.12 - 0.06 * length(cl)); last <- j }
}
bars <- if (length(cl)) do.call(rbind, cl) else data.frame(x = numeric(), xend = numeric(), y = numeric())
d$h <- 0.15 + 0.1 * (seq_len(nrow(d)) - 1)
p <- ggplot(d) +
geom_segment(aes(rank, 0, xend = rank, yend = h), colour = "grey60") +
geom_point(aes(rank, 0), colour = cs_cat[[1]], size = 2.4) +
geom_text(aes(rank, h, label = sprintf("%s (%.2f)", label, rank)), size = 2.8, vjust = -0.4) +
geom_segment(aes(x, y, xend = xend, yend = y), bars, linewidth = 1.4) +
scale_x_continuous(expand = expansion(mult = 0.2)) +
labs(x = "Mean rank across folds (1 = best)", y = NULL) + theme_cs + theme(axis.text.y = element_blank(), panel.grid.major.y = element_blank(), panel.grid.minor.y = element_blank())
print(p)
Needs ggplot2 · reads cd-diagram-demo.csv · app theme from the optional codesplashr helper
Compare training and validation scores across one hyperparameter.
Where validation peaks: the best trade-off.
Where the lines part: more complexity only fits noise.
1Callout 1: Validation peaks at this value.
2Callout 2: Training keeps climbing.
3Callout 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
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")# controls: logX=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
fig = go.Figure()
for i, k in enumerate(levels_of(df[K])):
g = df[df[K].astype(str) == str(k)].dropna(subset=[S])
if pd.api.types.is_numeric_dtype(g[X]):
g = g.sort_values(X)
col = PALETTE[i % len(PALETTE)]
err = dict(type="data", array=g[HI] - g[S], arrayminus=g[S] - g[LO]) if LO and HI else None
fig.add_scatter(x=g[X], y=g[S], mode="lines+markers", name=str(k), line=dict(color=col), error_y=err)
fig.update_layout(xaxis_title=X, yaxis_title=S)
fig.show()
Needs pandas, numpy, plotly · reads validation-curve-demo.csv · app theme from the optional codesplash helper
# Validation curve — Codesplash Chart Lab (recipe "validation-curve")# controls: logX=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("validation-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["set"]] <- factor(df[["set"]], levels = c("Training", "Validation"))
X <- "max depth"
S <- "ROC AUC"
K <- "set"
LO <- "lower"
HI <- "upper"
d <- data.frame(x = df[[X]], y = df[[S]], set = as.character(df[[K]]))
if (!is.null(LO) && !is.null(HI)) { d$lo <- df[[LO]]; d$hi <- df[[HI]] }
d <- d[is.finite(d$y), ]
p <- ggplot(d, aes(x, y, colour = set, group = set)) +
(if (!is.null(LO) && !is.null(HI)) geom_ribbon(aes(ymin = lo, ymax = hi, fill = set), colour = NA, alpha = 0.18)) +
geom_line() + geom_point() +
scale_colour_manual(values = cs_cat, name = NULL) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = X, y = S) + theme_cs
print(p)
Needs ggplot2 · reads validation-curve-demo.csv · app theme from the optional codesplashr helper
Read each point as one follow-up time: the chance that someone with the event by then was scored above someone still event-free.
Compare with the dashed line at 0.5, where the score ranks no better than a coin flip.
Follow the line across time: a falling line means the model ranks early events better than late ones.
1Callout 1: Early follow-up: how well the score ranks the first events.
2Callout 2: Dashed line: no skill.
3Callout 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
# Time-dependent AUC — Codesplash Chart Lab (recipe "td-auc-curve")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Scatter(x=d[T], y=d[A], mode="lines+markers", line_color=PALETTE[0], name=f"mean AUC {d[A].mean():.3f}"))
fig.add_hline(y=0.5, line_dash="dash", line_color=REF, annotation_text="no skill")
fig.update_layout(xaxis_title=T, yaxis_title=A, yaxis_range=[min(0.4, d[A].min()), 1], showlegend=True)
fig.show()
Needs pandas, numpy, plotly · reads td-auc-curve-demo.csv · app theme from the optional codesplash helper
# Time-dependent AUC — Codesplash Chart Lab (recipe "td-auc-curve")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("td-auc-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
T <- "Days since diagnosis"
A <- "Time-dependent AUC"
d <- data.frame(time = df[[T]], auc = df[[A]])
d <- d[is.finite(d$time) & is.finite(d$auc), ]
d <- d[order(d$time), ]
p <- ggplot(d, aes(time, auc)) +
geom_hline(yintercept = 0.5, linetype = "dashed", colour = ref_col) +
geom_line(colour = cs_cat[[1]], linewidth = 0.8) +
geom_point(colour = cs_cat[[1]], size = 1.5) +
coord_cartesian(ylim = c(min(0.4, d$auc), 1)) +
labs(x = T, y = A, subtitle = sprintf("mean AUC %.3f", mean(d$auc))) + theme_cs
print(p)
Needs ggplot2 · reads td-auc-curve-demo.csv · app theme from the optional codesplashr helper
Read each point as the squared error of the predicted survival probability at that time; lower is better.
Compare with the dashed line at 0.25: the score of a forecast that always says 50%.
Read the number at the top left, the integrated Brier score: the average of this curve across the times shown.
1Callout 1: Early on few events have happened, so errors are small for any model.
2Callout 2: Reference: a 50/50 forecast.
3Callout 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
# Survival Brier score — Codesplash Chart Lab (recipe "surv-brier-curve")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Scatter(x=d[T], y=d[B], mode="lines+markers", line_color=PALETTE[0], name=f"integrated {trapezoid_mean(d[T], d[B]):.3f}"))
fig.add_hline(y=0.25, line_dash="dash", line_color=REF, annotation_text="0.25: a 50/50 forecast")
fig.update_layout(xaxis_title=T, yaxis_title=B, yaxis_range=[0, max(0.3, d[B].max())], showlegend=True)
fig.show()
Needs pandas, numpy, plotly · reads surv-brier-curve-demo.csv · app theme from the optional codesplash helper
Read each line as the share of one predicted-risk group still event-free over time.
Check the order: the low-risk line should stay on top and the high-risk line at the bottom.
Read the gap between lines: wider means the score separates people more, and crossing lines mean it stops doing so.
1Callout 1: The group the model scored as lowest risk.
2Callout 2: The group it scored as highest risk.
3Callout 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
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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 = go.Figure()
for i, (name, d) in enumerate(series):
d = d.dropna(subset=[T, S]).sort_values(T)
x = [0.0] + d[T].tolist() + [end]
y = [1.0] + d[S].tolist() + [d[S].iloc[-1] if len(d) else 1.0]
fig.add_trace(go.Scatter(x=x, y=y, mode="lines", line_shape="hv", line_color=PALETTE[i % len(PALETTE)], line_dash=SERIES_DASHES[i % 8], name=name or S)) # dash per group
fig.update_layout(xaxis_title=T, yaxis_title=S, yaxis_range=[0, 1], yaxis_tickformat=".0%")
fig.show()
Needs pandas, numpy, plotly · reads risk-group-km-demo.csv · app theme from the optional codesplash helper
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("risk-group-km-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["Risk group"]] <- factor(df[["Risk group"]], levels = c("Low risk (n = 76)", "Middle risk (n = 76)", "High risk (n = 76)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
T <- "Days"
S <- "Survival"
G <- "Risk group"
g <- if (is.null(G)) factor(rep("", nrow(df))) else factor(as.character(df[[G]]), levels = levels_of(df[[G]]))
end <- max(df[[T]], na.rm = TRUE)
curves <- do.call(rbind, lapply(levels(g), function(name) {
d <- data.frame(time = df[[T]][g == name], survival = df[[S]][g == name])
d <- d[is.finite(d$time) & is.finite(d$survival), ]
d <- d[order(d$time), ]
last <- if (nrow(d)) d$survival[nrow(d)] else 1
data.frame(group = name, time = c(0, d$time, end), survival = c(1, d$survival, last))
}))
curves$group <- factor(curves$group, levels = levels(g))
p <- ggplot(curves, aes(time, survival, colour = group, linetype = group)) +
geom_step(linewidth = 0.8) + # dash per group, as in the app
scale_colour_manual(values = unname(cs_cat), name = NULL) + scale_linetype_manual(values = cs_linetypes, name = NULL) +
scale_y_continuous(labels = function(v) paste0(round(100 * v), "%"), limits = c(0, 1)) +
labs(x = T, y = S) + theme_cs
print(p)
Needs ggplot2 · reads risk-group-km-demo.csv · app theme from the optional codesplashr helper
Read each panel as one feature: how far it moves the prediction above or below average as its value changes.
Check the shaded band, about two standard errors: where it covers the dashed zero line, the data can't tell the effect from none.
Compare heights across panels. They share one y axis, so a taller curve is a larger effect.
1Callout 1: A steep stretch: the feature matters most here.
2Callout 2: Dashed line: the average prediction.
3Callout 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
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])
from plotly.subplots import make_subplots
_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 = make_subplots(rows=rows, cols=cols, shared_yaxes=True, subplot_titles=[name for name, _ in series])
for k, (name, d) in enumerate(series):
d = d.dropna(subset=[X, E]).sort_values(X)
r, s = k // cols + 1, k % cols + 1
if L and U:
fig.add_trace(go.Scatter(x=d[X], y=d[U], mode="lines", line_width=0, showlegend=False), row=r, col=s)
fig.add_trace(go.Scatter(x=d[X], y=d[L], mode="lines", line_width=0, fill="tonexty", fillcolor="rgba(113,157,239,0.16)", showlegend=False), row=r, col=s)
fig.add_trace(go.Scatter(x=d[X], y=d[E], mode="lines", line_color=PALETTE[0], showlegend=False), row=r, col=s)
fig.add_hline(y=0, line_dash="dash", line_color=REF, row=r, col=s)
fig.update_layout(height=280 * rows)
fig.show()
Needs pandas, numpy, plotly · reads gam-partial-demo.csv · app theme from the optional codesplash helper
# GAM partial effects — Codesplash Chart Lab (recipe "gam-partial")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("gam-partial-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["Feature"]] <- factor(df[["Feature"]], levels = c("Temperature", "Wind", "Solar radiation"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
F <- "Feature"
X <- "Value"
E <- "Effect"
L <- "Lower"
U <- "Upper"
d <- data.frame(feature = factor(as.character(df[[F]]), levels = levels_of(df[[F]])), x = df[[X]], effect = df[[E]])
if (!is.null(L) && !is.null(U)) {
d$lower <- df[[L]]
d$upper <- df[[U]]
}
d <- d[is.finite(d$x) & is.finite(d$effect), ]
p <- ggplot(d, aes(x, effect)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = ref_col)
if ("lower" %in% names(d)) p <- p + geom_ribbon(aes(ymin = lower, ymax = upper), fill = cs_cat[[1]], alpha = 0.16)
p <- p + geom_line(colour = cs_cat[[1]], linewidth = 0.8) +
facet_wrap(~feature, scales = "free_x") +
labs(x = NULL, y = E) + theme_cs
print(p)
Needs ggplot2 · reads gam-partial-demo.csv · app theme from the optional codesplashr helper
Read each solid line as one network's training loss, epoch by epoch (or NGBoost's training score, round by round).
Read the dashed line in the same colour as its loss on the held-back validation rows.
Find the ring: the epoch with the lowest validation loss, whose weights early stopping keeps.
1Callout 1: Steep early fall: the network is learning the main pattern.
2Callout 2: Ring: the kept epoch.
3Callout 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
# Training curves — Codesplash Chart Lab (recipe "training-curves")# controls: scale=linear, valid=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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)]
name = s if s is not None else Y
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))
sizes = [7 if k % every == (i * every) // len(series) else 0 for k in range(len(d))] # about 8 markers per member, staggered
fig.add_trace(go.Scatter(x=d[X], y=d[Y], mode="lines+markers" if many else "lines", name=name, line=dict(color=colour, width=2), marker=dict(symbol=SERIES_MARKERS[i % 8], size=sizes, color=colour)))
if V and SHOW_VALID:
dv = d.dropna(subset=[V])
if len(dv):
fig.add_trace(go.Scatter(x=dv[X], y=dv[V], mode="lines", name=f"{name} (validation)", line=dict(color=colour, width=1.5, dash="dash"), showlegend=False))
best = dv.loc[dv[V].idxmin()]
fig.add_trace(go.Scatter(x=[best[X]], y=[best[V]], mode="markers", marker=dict(color="white", symbol=SERIES_MARKERS[i % 8] if many else "circle", line=dict(color=colour, width=2), size=9), showlegend=False, hovertext="best validation"))
fig.update_layout(title="Training curves (dashed: validation)", xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads training-curves-demo.csv · app theme from the optional codesplash helper
# Training curves — Codesplash Chart Lab (recipe "training-curves")# controls: scale=linear, valid=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("training-curves-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["network"]] <- factor(df[["network"]], levels = c("member 1", "member 2", "member 3"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "epoch"
Y <- "training log loss"
S <- "network"
V <- "validation log loss"
show_valid <- TRUE
d <- data.frame(x = df[[X]], y = df[[Y]], s = if (is.null(S)) factor(Y) else factor(df[[S]], levels = levels_of(df[[S]])))
if (!is.null(V)) d$v <- df[[V]]
d <- d[order(d$s, d$x), ]
p <- ggplot(d, aes(x, y, colour = s)) + geom_line(linewidth = 0.6)
if (nlevels(d$s) > 1) { # members share solid/dashed for train/validation, so a marker shape names each (as in the app)
marks <- do.call(rbind, lapply(split(d, d$s, drop = TRUE), function(g) {
k <- max(1, round(nrow(g) / 8)); off <- ((as.integer(g$s[1]) - 1) * k) %/% nlevels(d$s)
g[(seq_len(nrow(g)) - 1) %% k == off, ] # about 8 markers per member, staggered
}))
p <- p + geom_point(data = marks, aes(shape = s), size = 1.8) + scale_shape_manual(values = cs_shapes, name = NULL)
}
if (!is.null(V) && show_valid) {
dv <- d[!is.na(d$v), ]
best <- do.call(rbind, lapply(split(dv, dv$s, drop = TRUE), function(g) g[which.min(g$v), ])) # the kept epoch
p <- p + geom_line(data = dv, aes(y = v), linetype = "dashed", linewidth = 0.45) +
geom_point(data = best, aes(y = v), shape = 21, fill = "white", size = 2.2, show.legend = FALSE) # the legend keeps each member's marker
}
p <- p + scale_colour_manual(values = rep(cs_cat, length.out = nlevels(d$s))) +
labs(x = X, y = Y, colour = NULL, title = "Training curves (dashed: validation)")
print(p)
Needs ggplot2 · reads training-curves-demo.csv · app theme from the optional codesplashr helper
Read the x axis as rows ordered by the ensemble's prediction, lowest on the left.
Read the grey dots at one position as the members' predictions for that row; a tall column means they disagree.
Compare the ticks (actual values) with the shaded band: the legend says what share of them it holds.
1Callout 1: Members agree: the dots sit on the line.
2Callout 2: Members spread out: the model is unsure here.
3Callout 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
# Ensemble spread — Codesplash Chart Lab (recipe "ensemble-spread")# controls: members=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
fig = go.Figure()
if LO and HI:
fig.add_trace(go.Scatter(x=list(rows[X]) + list(rows[X])[::-1], y=list(rows[HI]) + list(rows[LO])[::-1], fill="toself", fillcolor="rgba(70,110,200,0.18)", line=dict(width=0), name="band", hoverinfo="skip"))
if SHOW_MEMBERS:
fig.add_trace(go.Scatter(x=df[X], y=df[Y], mode="markers", marker=dict(color=GREY, size=4), name="members"))
fig.add_trace(go.Scatter(x=rows[X], y=rows[C], mode="lines", line=dict(color=PALETTE[0], width=2), name=C))
if A:
fig.add_trace(go.Scatter(x=rows[X], y=rows[A], mode="markers", marker=dict(symbol="line-ew", color=REF, size=10, line=dict(width=2, color=REF)), name=A))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads ensemble-spread-demo.csv · app theme from the optional codesplash helper
# Ensemble spread — Codesplash Chart Lab (recipe "ensemble-spread")# controls: members=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ensemble-spread-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["member"]] <- factor(df[["member"]], levels = c("member 1", "member 2", "member 3", "member 4", "member 5"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
X <- "row (ordered by prediction)"
Y <- "member prediction"
C <- "ensemble"
LO <- "90% low"
HI <- "90% high"
A <- "actual"
show_members <- TRUE
rows <- df[!duplicated(df[[X]]), , drop = FALSE]
rows <- rows[order(rows[[X]]), , drop = FALSE]
r <- data.frame(x = rows[[X]], centre = rows[[C]])
p <- ggplot()
if (!is.null(LO) && !is.null(HI)) {
r$lo <- rows[[LO]]; r$hi <- rows[[HI]]
p <- p + geom_ribbon(data = r, aes(x, ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.18)
}
if (show_members) p <- p + geom_point(data = data.frame(x = df[[X]], y = df[[Y]]), aes(x, y), colour = grey_col, size = 0.8)
p <- p + geom_line(data = r, aes(x, centre), colour = cs_cat[1], linewidth = 0.7)
if (!is.null(A)) p <- p + geom_point(data = data.frame(x = rows[[X]], a = rows[[A]]), aes(x, a), shape = 95, size = 5, colour = ref_col)
p <- p + labs(x = X, y = Y)
print(p)
Needs ggplot2 · reads ensemble-spread-demo.csv · app theme from the optional codesplashr helper
Read each curve as the full distribution the model predicts for one row; its peak is the most likely value.
Read a curve's width as the model's uncertainty for that row: narrow is confident.
Follow the dashed line up from the actual value: its height is the likelihood the model gave to what happened.
1Callout 1: A narrow, tall curve: a confident prediction.
2Callout 2: A wide, low curve: an uncertain one.
3Callout 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
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")# controls: discrete=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
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 = go.Figure()
for i, s in enumerate(series):
d = df[df[S].astype(str) == s].sort_values(X)
colour = PALETTE[i % len(PALETTE)]
if DISCRETE:
fig.add_trace(go.Bar(x=d[X], y=d[D], name=s, marker=dict(color=colour, pattern=dict(shape=SERIES_HATCHES[i % 8], fgcolor=HATCH_INK, fillmode="overlay")))) # texture per row
else:
fig.add_trace(go.Scatter(x=d[X], y=d[D], mode="lines", name=s, line=dict(color=colour, width=2, dash=SERIES_DASHES[i % 8]))) # 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
fig.add_trace(go.Scatter(x=[a, a], y=[0, top], mode="lines", line=dict(color=colour, dash="dash", width=1.5), showlegend=False, hovertext=f"actual {a:g}"))
if not DISCRETE:
fig.add_trace(go.Scatter(x=[a], y=[top], mode="markers", marker=dict(symbol=SERIES_MARKERS[i % 8], color="white", size=8, line=dict(color=colour, width=1.6)), showlegend=False))
fig.update_layout(xaxis_title=X, yaxis_title=D, barmode="group")
fig.show()
Needs pandas, numpy, plotly · reads predicted-distributions-demo.csv · app theme from the optional codesplash helper
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")# controls: discrete=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("predicted-distributions-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["row"]] <- factor(df[["row"]], levels = c("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)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "ozone (ppb)"
D <- "density"
S <- "row"
A <- "actual"
discrete <- FALSE
d <- data.frame(x = df[[X]], dens = df[[D]], s = factor(df[[S]], levels = levels_of(df[[S]])))
if (!is.null(A)) d$a <- df[[A]]
d <- d[order(d$s, d$x), ]
p <- ggplot(d, aes(x, dens, colour = s))
if (discrete) {
p <- p + geom_linerange(aes(ymin = 0, ymax = dens), position = position_dodge(width = 0.5)) +
geom_point(aes(shape = s), position = position_dodge(width = 0.5), size = 1.4) # marker shape per row, as in the app
} else {
p <- p + geom_area(aes(fill = s), position = "identity", alpha = 0.08, colour = NA, show.legend = FALSE) + geom_line(aes(linetype = s), linewidth = 0.6) # dash per row
}
if (!is.null(A)) {
act <- do.call(rbind, lapply(split(d, d$s, drop = TRUE), function(g) {
a <- g$a[!is.na(g$a)][1]
data.frame(s = g$s[1], a = a, top = if (discrete) max(g$dens) * 0.08 else stats::approx(g$x, g$dens, a, rule = 2)$y)
}))
p <- p + geom_segment(data = act, aes(x = a, xend = a, y = 0, yend = top, colour = s), linetype = "dashed", linewidth = 0.45)
if (!discrete) p <- p + geom_point(data = act, aes(x = a, y = top, colour = s, shape = s), size = 2, show.legend = FALSE) # the row's marker at the actual
}
p <- p + scale_colour_manual(values = rep(cs_cat, length.out = nlevels(d$s))) +
scale_fill_manual(values = rep(cs_cat, length.out = nlevels(d$s))) + scale_linetype_manual(values = cs_linetypes) +
scale_shape_manual(values = cs_shapes) + labs(x = X, y = D, colour = NULL, linetype = NULL, shape = NULL)
print(p)
Needs ggplot2 · reads predicted-distributions-demo.csv · app theme from the optional codesplashr helper
Read each line as one part of the network's loss, averaged over an epoch's rows.
Falling lines that level off mean training has settled; a line still falling at the right edge means more epochs could help.
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.
1Callout 1: Early epochs: the loss drops fast.
2Callout 2: Late epochs: the lines level off.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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]
fig.add_trace(go.Scatter(x=s[X], y=y, mode="lines+markers" if len(s) <= 60 else "lines", name=name,
line_dash=SERIES_DASHES[i % 8] if many else "solid", marker_symbol=SERIES_MARKERS[i % 8] if many else "circle"))
fig.update_layout(xaxis_title=X, yaxis_title=V, template="plotly_white")
if LOG and (d[V] > 0).all():
fig.update_yaxes(type="log")
fig.show()
Needs pandas, numpy, plotly · reads training-components-demo.csv · app theme from the optional codesplash helper
# Training loss and its parts — Codesplash Chart Lab (recipe "training-components")# controls: scale=linear, smooth=1
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("training-components-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["part"]] <- factor(df[["part"]], levels = c("total", "reconstruction", "KL"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "epoch"
V <- "loss per row"
C <- "part"
SMOOTH <- 1; LOG <- FALSE # centered moving average (1 = none); log y axis
d <- df[!is.na(df[[X]]) & !is.na(df[[V]]), ]
d$part <- factor(as.character(d[[C]]), levels = levels_of(d[[C]]))
d <- d[order(d$part, d[[X]]), ]
ma <- function(y, w) { h <- w %/% 2; vapply(seq_along(y), function(i) mean(y[max(1, i - h):min(length(y), i + h)]), numeric(1)) }
d$y <- if (SMOOTH > 1) ave(d[[V]], d$part, FUN = function(y) ma(y, SMOOTH)) else d[[V]]
# several components: a dash each (and a marker shape when the points are few), as in the app
p <- ggplot(d, aes(x = .data[[X]], y = y, colour = part, linetype = part)) + geom_line(linewidth = 0.7) +
{ if (any(table(d$part) <= 60)) geom_point(data = d[ave(d$y, d$part, FUN = length) <= 60, ], aes(shape = part), size = 1.4) } +
scale_linetype_manual(values = cs_linetypes) + scale_shape_manual(values = cs_shapes) +
labs(x = X, y = V, colour = NULL, linetype = NULL, shape = NULL) + theme_minimal()
if (LOG && all(d[[V]] > 0)) p <- p + scale_y_log10() else if (min(d[[V]]) < 0 && max(d[[V]]) > 0) p <- p + geom_hline(yintercept = 0, linetype = "dotted", colour = "grey50")
print(p)
Needs ggplot2 · reads training-components-demo.csv · app theme from the optional codesplashr helper
Read each dot as one level of a categorical feature, placed by the vector the network learned for it.
Levels close together act alike on the target; a level far from the rest gets treated differently.
Compare levels within one colour (one feature): distances between features' levels are not comparable.
1Callout 1: Two levels the model treats alike: close together.
2Callout 2: A level set apart from the rest.
3Callout 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
# Category embedding map — Codesplash Chart Lab (recipe "embedding-map")# controls: labels=true, equal=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, k in enumerate(groups):
m = (d[G].astype(str) == str(k)).to_numpy() if G else np.ones(len(d), bool)
text = d.loc[m, LABEL].astype(str) if LABEL else None
fig.add_scatter(
x=d.loc[m, X], y=d.loc[m, Y], mode="markers+text" if (LABELS and LABEL) else "markers", text=text,
textposition="middle right", name=str(k) if k is not None else "levels",
marker=dict(size=2 * r[m], color=PALETTE[i % len(PALETTE)], opacity=0.72, line=dict(color="white", width=1)),
)
fig.add_hline(y=0, line_dash="dash", line_color=REF, opacity=0.35)
fig.add_vline(x=0, line_dash="dash", line_color=REF, opacity=0.35)
fig.update_layout(xaxis_title=X, yaxis_title=Y, legend_title_text=G or "", title="Learned category embeddings")
if EQUAL:
fig.update_yaxes(scaleanchor="x", scaleratio=1) # equal units
fig.show()
Needs pandas, numpy, plotly · reads embedding-map-demo.csv · app theme from the optional codesplash helper
Read each small square as one kernel the first layer learned; the network slides it over every position of the image.
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.
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.
1Callout 1: One kernel: k × k weights.
2Callout 2: Opposite signs side by side: an edge detector.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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))
scale = [[0, DIV[0]], [0.5, DIV[1]], [1, DIV[2]]]
titles = [str(p) for p in panels]
fig = make_subplots(rows=lines, cols=per_row, subplot_titles=titles, horizontal_spacing=0.03, vertical_spacing=0.1)
for i, name in enumerate(panels):
g = grids[name]
lo, hi = limits(name)
show = VALUES and g.size <= 49
fig.add_heatmap(z=g, zmin=lo, zmax=hi, colorscale=scale, showscale=i == 0, colorbar=dict(title=VALUE),
text=np.round(g, 2) if show else None, texttemplate="%{text}" if show else None,
row=i // per_row + 1, col=i % per_row + 1)
fig.update_yaxes(autorange="reversed", showticklabels=False, scaleanchor="x")
fig.update_xaxes(showticklabels=False)
fig.show()
Needs pandas, numpy, plotly · reads cnn-filters-demo.csv · app theme from the optional codesplash helper
# CNN filters (first-layer kernels) — Codesplash Chart Lab (recipe "cnn-filters")# controls: scale=shared, values=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cnn-filters-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["panel"]] <- factor(df[["panel"]], levels = c("filter 1", "filter 2", "filter 3", "filter 4", "filter 5", "filter 6", "filter 7", "filter 8"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
panel_col <- "panel"
row_col <- "row"
col_col <- "col"
value_col <- "weight"
shared <- TRUE; show_values <- TRUE # one colour scale for all panels; values in small grids
d <- data.frame(panel = factor(as.character(df[[panel_col]]), levels = levels_of(df[[panel_col]])),
r = df[[row_col]], c = df[[col_col]], v = df[[value_col]])
top <- max(abs(d$v), na.rm = TRUE) # ± the largest weight of any filter
d$fill <- if (shared) d$v / top else ave(d$v, d$panel, FUN = function(x) x / max(abs(x), na.rm = TRUE))
p <- ggplot(d, aes(c, r, fill = fill)) + geom_tile(colour = "white", linewidth = 0.2) +
scale_fill_gradient2(low = div_ramp[1], mid = div_ramp[2], high = div_ramp[3], midpoint = 0, limits = c(-1, 1), name = paste(value_col, "(÷ max)")) +
scale_y_reverse() + coord_equal() + facet_wrap(~panel) +
labs(x = NULL, y = NULL) + theme_cs + theme(axis.text = element_blank(), panel.grid = element_blank())
if (show_values && max(d$r) * max(d$c) <= 49) p <- p + geom_text(aes(label = sprintf("%.2f", v), colour = abs(fill) > 0.55), size = 2) + scale_colour_manual(values = c(`FALSE` = "black", `TRUE` = "white"), guide = "none")
print(p)
Needs ggplot2 · reads cnn-filters-demo.csv · app theme from the optional codesplashr helper
Start with the outlined panel: the input image as the network sees it.
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.
Compare the maps: different kernels pick out different strokes of the same image, which is what the next layer combines.
1Callout 1: The input image.
2Callout 2: A map: bright where the kernel's pattern is.
3Callout 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
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")# controls: scale=each, values=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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))
scale = [[0, SEQ[0]], [1, SEQ[-1]]]
titles = ["<b>input</b>" if str(p).lower() == "input" else f"{p} · max {np.nanmax(grids[p]):.2f}" for p in panels]
fig = make_subplots(rows=lines, cols=per_row, subplot_titles=titles, horizontal_spacing=0.03, vertical_spacing=0.1)
for i, name in enumerate(panels):
g = grids[name]
lo, hi = limits(name)
show = VALUES and g.size <= 49
fig.add_heatmap(z=g, zmin=lo, zmax=hi, colorscale=scale, showscale=i == 0, colorbar=dict(title=VALUE),
text=np.round(g, 2) if show else None, texttemplate="%{text}" if show else None,
row=i // per_row + 1, col=i % per_row + 1)
fig.update_yaxes(autorange="reversed", showticklabels=False, scaleanchor="x")
fig.update_xaxes(showticklabels=False)
fig.show()
Needs pandas, numpy, plotly · reads cnn-feature-maps-demo.csv · app theme from the optional codesplash helper
# CNN feature maps — Codesplash Chart Lab (recipe "cnn-feature-maps")# controls: scale=each, values=false
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cnn-feature-maps-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["panel"]] <- factor(df[["panel"]], levels = c("input", "map 1", "map 2", "map 3", "map 4", "map 5", "map 6", "map 7", "map 8"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
panel_col <- "panel"
row_col <- "row"
col_col <- "col"
value_col <- "activation"
shared <- FALSE; show_values <- FALSE # one colour scale for all panels; values in small grids
d <- data.frame(panel = factor(as.character(df[[panel_col]]), levels = levels_of(df[[panel_col]])),
r = df[[row_col]], c = df[[col_col]], v = df[[value_col]])
is_input <- tolower(as.character(d$panel)) == "input"
top <- max(d$v[!is_input], na.rm = TRUE)
d$fill <- ave(d$v, d$panel, FUN = function(x) (x - min(0, x, na.rm = TRUE)) / max(x, na.rm = TRUE)) # each panel 0 → its peak
if (shared) d$fill[!is_input] <- d$v[!is_input] / top
p <- ggplot(d, aes(c, r, fill = fill)) + geom_tile(colour = "white", linewidth = 0.2) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), name = paste(value_col, "(÷ max)")) +
scale_y_reverse() + coord_equal() + facet_wrap(~panel) +
labs(x = NULL, y = NULL) + theme_cs + theme(axis.text = element_blank(), panel.grid = element_blank())
if (show_values && max(d$r) * max(d$c) <= 49) p <- p + geom_text(aes(label = sprintf("%.2f", v), colour = abs(fill) > 0.55), size = 2) + scale_colour_manual(values = c(`FALSE` = "black", `TRUE` = "white"), guide = "none")
p <- p + geom_rect(data = unique(d[is_input, "panel", drop = FALSE]), aes(xmin = 0.5, xmax = max(d$c) + 0.5, ymin = 0.5, ymax = max(d$r) + 0.5), inherit.aes = FALSE, fill = NA, colour = ref_col, linewidth = 0.8) # the input image
print(p)
Needs ggplot2 · reads cnn-feature-maps-demo.csv · app theme from the optional codesplashr helper
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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)"
text = [[f"{v:g}" if (VALUES and (v > 0 or i == j)) else "" for j, v in enumerate(row)] for i, row in enumerate(M)]
fig = go.Figure(go.Heatmap(z=Z, x=classes, y=ylabels, zmin=0, zmax=1, colorscale=[[0, SEQ[0]], [1, SEQ[-1]]],
text=text, texttemplate="%{text}", customdata=M, hovertemplate="actual %{y}<br>predicted %{x}<br>%{customdata:g} rows<extra></extra>",
colorbar=dict(title="row share" if BY_ROW else "rows ÷ max")))
for i in range(k): # outline the diagonal (correct predictions)
fig.add_shape(type="rect", x0=i - 0.45, x1=i + 0.45, y0=i - 0.45, y1=i + 0.45, line=dict(color=REF, width=1.5))
fig.update_yaxes(autorange="reversed", title="actual (recall)", type="category")
fig.update_xaxes(side="top", title="predicted", type="category")
fig.update_layout(title=title)
fig.show()
Needs pandas, numpy, plotly · reads cnn-confusion-demo.csv · app theme from the optional codesplash helper
# Confusion matrix (out of fold) — Codesplash Chart Lab (recipe "cnn-confusion")# controls: normalize=row, values=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("cnn-confusion-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["actual"]] <- factor(df[["actual"]], levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))
df[["predicted"]] <- factor(df[["predicted"]], levels = c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
actual_col <- "actual"
predicted_col <- "predicted"
count_col <- "rows"
by_row <- TRUE; show_values <- TRUE # shade by the share of each actual class; print counts
classes <- unique(c(levels_of(df[[actual_col]]), levels_of(df[[predicted_col]])))
n <- if (is.null(count_col)) rep(1, nrow(df)) else df[[count_col]]
M <- matrix(0, length(classes), length(classes), dimnames = list(classes, classes)) # rows actual, columns predicted
for (i in seq_len(nrow(df))) {
a <- as.character(df[[actual_col]][i]); p <- as.character(df[[predicted_col]][i])
if (!is.na(a) && !is.na(p) && !is.na(n[i])) M[a, p] <- M[a, p] + n[i]
}
totals <- rowSums(M)
recall <- ifelse(totals > 0, diag(M) / totals, NA)
ylab <- ifelse(is.na(recall), classes, sprintf("%s (%.0f%%)", classes, 100 * recall))
d <- expand.grid(i = seq_along(classes), j = seq_along(classes))
d$count <- M[cbind(d$i, d$j)]
d$fill <- if (by_row) ifelse(totals[d$i] > 0, d$count / totals[d$i], 0) else d$count / max(M, 1)
d$actual <- factor(ylab[d$i], levels = rev(ylab))
d$predicted <- factor(classes[d$j], levels = classes)
p <- ggplot(d, aes(predicted, actual, fill = fill)) + geom_tile(colour = "white", linewidth = 0.3) +
geom_tile(data = d[d$i == d$j, ], fill = NA, colour = ref_col, linewidth = 0.7, width = 0.9, height = 0.9) + # correct predictions
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), name = if (by_row) "row share" else "rows ÷ max") +
scale_x_discrete(position = "top") + coord_equal() +
labs(x = "predicted", y = "actual (recall)", title = sprintf("accuracy %.1f%% of %g (diagonal outlined)", 100 * sum(diag(M)) / max(sum(M), 1), sum(M))) +
theme_cs + theme(panel.grid = element_blank())
if (show_values) p <- p + geom_text(data = d[d$count > 0 | d$i == d$j, ], aes(label = format(count), colour = fill > 0.55), size = 2.8) +
scale_colour_manual(values = c(`FALSE` = "black", `TRUE` = "white"), guide = "none") # readable on dark cells
print(p)
Needs ggplot2 · reads cnn-confusion-demo.csv · app theme from the optional codesplashr helper
Discover & forecasting
Clusters, dendrograms, embeddings, association rules, topics, anomalies and forecasts with backtests.
Read from the leaves up: branches join where groups merge.
Read join height as how different the merged groups are.
Cut across a long vertical gap to get a natural number of clusters.
1Callout 1: A high join: very different groups.
2Callout 2: Low joins: very similar rows.
3Callout 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
# Dendrogram — Codesplash Chart Lab (recipe "dendrogram")# controls: k=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
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 = go.Figure()
for i, (left, right, h) in enumerate(merges):
col = PALETTE[cluster[lv(left)[0]] % len(PALETTE)] if cluster and i < below else REF
fig.add_scatter(x=[xo(left), xo(left), xo(right), xo(right)], y=[ho(left), h, h, ho(right)], mode="lines", line=dict(color=col, width=1.3), showlegend=False, hoverinfo="skip")
if cut is not None:
fig.add_hline(y=cut, line=dict(color="#ce5342", dash="dash", width=1))
fig.update_xaxes(tickvals=list(range(len(order))), ticktext=[labels[x - 1] if x - 1 < len(labels) else str(x) for x in order], tickangle=-90)
fig.update_yaxes(title=H)
fig.show()
Needs pandas, numpy, plotly · reads dendrogram-demo.csv · app theme from the optional codesplash helper
# Dendrogram — Codesplash Chart Lab (recipe "dendrogram")# controls: k=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("dendrogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
ml_col <- "merge left"
mr_col <- "merge right"
h_col <- "height (Ward)"
lab_col <- "state"
k <- 0 # cut into k clusters (0 = no cut)
ok <- !is.na(df[[ml_col]]) & !is.na(df[[mr_col]]) & !is.na(df[[h_col]])
mg <- cbind(as.integer(df[[ml_col]][ok]), as.integer(df[[mr_col]][ok])); hh <- df[[h_col]][ok]
m <- nrow(mg); n <- m + 1
ord <- integer(0); stack <- m # hclust order: depth first, left subtree first
while (length(stack)) { v <- stack[length(stack)]; stack <- stack[-length(stack)]; if (v < 0) ord <- c(ord, -v) else stack <- c(stack, mg[v, 2], mg[v, 1]) }
pos <- integer(n); pos[ord] <- seq_along(ord) - 1
mx <- numeric(m); leaves <- vector("list", m)
xo <- function(v) if (v < 0) pos[-v] else mx[v]
lv <- function(v) if (v < 0) -v else leaves[[v]]
ho <- function(v) if (v < 0) 0 else hh[v]
for (i in seq_len(m)) { mx[i] <- (xo(mg[i, 1]) + xo(mg[i, 2])) / 2; leaves[[i]] <- c(lv(mg[i, 1]), lv(mg[i, 2])) }
below <- if (k >= 2) m - (k - 1) else m # merges below the cut
clus <- rep(NA_integer_, n); cut_h <- NA
if (k >= 2) {
roots <- unlist(lapply(seq.int(below + 1, m), function(i) Filter(function(ch) ch < 0 || ch <= below, mg[i, ])))
roots <- roots[order(vapply(roots, function(v) min(pos[lv(v)]), numeric(1)))]
for (ci in seq_along(roots)) clus[lv(roots[ci])] <- ci
cut_h <- ((if (below >= 1) hh[below] else 0) + hh[below + 1]) / 2
}
seg <- do.call(rbind, lapply(seq_len(m), function(i) { l <- mg[i, 1]; r <- mg[i, 2]
col <- if (k >= 2 && i <= below) as.character(clus[lv(l)[1]]) else "above"
data.frame(x = c(xo(l), xo(l), xo(r)), xend = c(xo(l), xo(r), xo(r)), y = c(ho(l), hh[i], hh[i]), yend = c(hh[i], hh[i], ho(r)), col = col) }))
labs_leaf <- if (is.null(lab_col)) as.character(seq_len(n)) else as.character(df[[lab_col]])
p <- ggplot(seg) + geom_segment(aes(x = x, xend = xend, y = y, yend = yend, colour = col), linewidth = 0.6) +
{ if (!is.na(cut_h)) geom_hline(yintercept = cut_h, linetype = "dashed", colour = "#ce5342") } +
scale_colour_manual(values = c(above = ref_col, setNames(rep_len(cs_cat, max(1, n)), as.character(seq_len(max(1, n))))), guide = "none") +
scale_x_continuous(breaks = seq_len(n) - 1, labels = labs_leaf[ord], expand = expansion(add = 0.5)) +
labs(x = NULL, y = h_col) + theme_cs + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5, size = 7))
print(p)
Needs ggplot2 · reads dendrogram-demo.csv · app theme from the optional codesplashr helper
Read each thin bar as one row's fit: near 1 is well inside its cluster.
Compare clusters with the dashed average.
Bars below zero: rows closer to another cluster.
1Callout 1: Wide bars: rows well inside this cluster.
2Callout 2: Dashed line: the average silhouette.
3Callout 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
# Silhouette plot — Codesplash Chart Lab (recipe "silhouette-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
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()
fig.add_bar(x=w, y=np.arange(y0, y0 + len(w)), orientation="h", marker=dict(color=PALETTE[i % len(PALETTE)], line=dict(width=0)), name=str(k), width=1.0)
ticks.append(y0 + len(w) / 2)
y0 += len(w) + 3
avg = float(d[W].mean())
fig.add_vline(x=avg, line=dict(color=REF, dash="dash", width=1), annotation_text=f"average {avg:.2f}")
fig.update_yaxes(tickvals=ticks, ticktext=[str(k) for k in clusters], autorange="reversed", title=CL)
fig.update_layout(xaxis_title=W, bargap=0, showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads silhouette-plot-demo.csv · app theme from the optional codesplash helper
Read one panel per criterion against the number of clusters.
Look for a bend or peak: the ringed point is the suggested k.
Prefer a k that several criteria agree on, and that makes sense for your data.
1Callout 1: The elbow: extra clusters stop helping much.
2Callout 2: A peak: the best silhouette.
3Callout 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
# Choosing k — Codesplash Chart Lab (recipe "elbow-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = make_subplots(rows=1, cols=len(crits), subplot_titles=[str(cr) if cr is not None else S for cr in crits])
for i, cr in enumerate(crits, start=1):
g = d if cr is None else d[d[CRIT].astype(str) == str(cr)]
fig.add_scatter(x=g[K], y=g[S], mode="lines+markers", line=dict(color=PALETTE[(i - 1) % len(PALETTE)], width=2), showlegend=False, row=1, col=i)
if CH:
pick = g[truthy(g[CH])]
fig.add_scatter(x=pick[K], y=pick[S], mode="markers", marker=dict(size=16, color="rgba(0,0,0,0)", line=dict(color=REF, width=2)), showlegend=False, row=1, col=i)
fig.update_xaxes(title_text=K, row=1, col=i)
fig.show()
Needs pandas, numpy, plotly · reads elbow-plot-demo.csv · app theme from the optional codesplash helper
Read arrows as variables: long arrows contribute more.
Rows far along an arrow have high values for that variable.
1Callout 1: An arrow: this variable's direction.
2Callout 2: A row far along this direction.
3Callout 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.
Read x as how common the rule is and y as how often it holds.
Read colour as lift: how much more often than chance.
Prefer rules that are high on all three.
1Callout 1: High confidence, but rare.
2Callout 2: Common but less reliable.
3Callout 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
# Association rules — Codesplash Chart Lab (recipe "rules-scatter")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
top = set(d.nlargest(5, LIFT).index)
fig = go.Figure(go.Scatter(x=d[SUP], y=d[CONF], mode="markers+text", text=[str(v) if i in top else "" for i, v in zip(d.index, d[LAB])],
textposition="top right", textfont=dict(size=9), hovertext=d[LAB].astype(str),
marker=dict(size=9, color=d[LIFT], colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], colorbar=dict(title=LIFT), line=dict(color=GREY, width=0.5))))
fig.update_layout(xaxis_title=SUP, yaxis_title=CONF)
fig.show()
Needs pandas, numpy, plotly · reads rules-scatter-demo.csv · app theme from the optional codesplash helper
Find the dashed threshold: rows beyond it are flagged in red.
A clear gap before the threshold is reassuring; a smooth tail means the cut is arbitrary.
1Callout 1: Most rows: low scores.
2Callout 2: Threshold: the flagging cut.
3Callout 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
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")# controls: threshold=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
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))))))
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)
mid, w = (edges[:-1] + edges[1:]) / 2, np.diff(edges)
thr = THRESHOLD if THRESHOLD != 0 else (float(d.loc[flag, S].min()) if flag.any() else None)
fig = go.Figure()
fig.add_bar(x=mid, y=normal, width=w, name="normal", marker_color=PALETTE[0])
fig.add_bar(x=mid, y=flagged, width=w, name="flagged", marker_color="#ce5342")
if thr is not None:
fig.add_vline(x=thr, line=dict(color=REF, dash="dash", width=1.2), annotation_text=f"threshold {thr:.3g}")
fig.update_layout(barmode="stack", bargap=0, xaxis_title=S, yaxis_title="rows")
fig.show()
Needs pandas, numpy, plotly · reads anomaly-scores-demo.csv · app theme from the optional codesplash helper
# Anomaly score distribution — Codesplash Chart Lab (recipe "anomaly-scores")# controls: threshold=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("anomaly-scores-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["flagged"]] <- as.logical(df[["flagged"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
truthy <- function(v) tolower(trimws(as.character(v))) %in% c("true", "1", "yes", "t")
s_col <- "anomaly score"
flag_col <- "flagged"
threshold <- 0 # 0 = the smallest flagged score
d <- data.frame(s = df[[s_col]], flag = if (is.null(flag_col)) FALSE else truthy(df[[flag_col]]))
d <- d[!is.na(d$s), ]
k <- min(60, max(10, round(1.5 * sqrt(nrow(d))))) # about 1.5 sqrt(n) bins
edges <- seq(min(d$s), max(d$s), length.out = k + 1)
d$group <- factor(ifelse(d$flag, "flagged", "normal"), levels = c("flagged", "normal"))
thr <- if (threshold != 0) threshold else if (any(d$flag)) min(d$s[d$flag]) else NA
p <- ggplot(d, aes(s, fill = group)) + geom_histogram(breaks = edges, position = "stack", colour = NA) +
{ if (!is.na(thr)) geom_vline(xintercept = thr, linetype = "dashed", colour = ref_col) } +
scale_fill_manual(values = c(normal = cs_cat[1], flagged = "#ce5342")) + labs(x = s_col, y = "rows", fill = NULL) + theme_cs
print(p)
Needs ggplot2 · reads anomaly-scores-demo.csv · app theme from the optional codesplashr helper
Read the line for history and where the forecast continues from.
Read the bands: the darker is 80%, the lighter 95%.
Bands that widen quickly mean the forecast is soon uncertain.
1Callout 1: The forecast's centre line.
2Callout 2: The lighter band: 95% prediction interval.
3Callout 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
# Forecast fan chart — Codesplash Chart Lab (recipe "forecast-fan")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = make_subplots(rows=len(names), cols=1, subplot_titles=[str(n) if n is not None else "" for n in names])
for r, name in enumerate(names, start=1):
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, label in ((L95, H95, 0.15, "95%"), (L80, H80, 0.3, "80%")):
if lo and hi and len(fc):
fig.add_scatter(x=fc[T], y=fc[lo], mode="lines", line=dict(width=0), showlegend=False, hoverinfo="skip", row=r, col=1)
fig.add_scatter(x=fc[T], y=fc[hi], mode="lines", line=dict(width=0), fill="tonexty", fillcolor=rgba(PALETTE[0], a), name=label, showlegend=r == 1, row=r, col=1)
fig.add_scatter(x=act[T], y=act[V], mode="lines", line=dict(color=REF, width=1.5), name="actual", showlegend=r == 1, row=r, col=1)
if len(fit):
fig.add_scatter(x=fit[T], y=fit[V], mode="lines", line=dict(color=PALETTE[1], dash="dash", width=1), name="fitted", showlegend=r == 1, row=r, col=1)
if len(fc):
joined = pd.concat([act.tail(1), fc])
fig.add_scatter(x=joined[T], y=joined[V], mode="lines", line=dict(color=PALETTE[0], width=2), name="forecast", showlegend=r == 1, row=r, col=1)
fig.update_yaxes(title_text=V, row=r, col=1)
fig.show()
Needs pandas, numpy, plotly · reads forecast-fan-demo.csv · app theme from the optional codesplash helper
Read thin lines as individual backtest windows, the thick line as the mean.
Rising with horizon is normal; compare how fast.
Thin lines far apart mean accuracy depends on when you start.
1Callout 1: Mean error at short horizons.
2Callout 2: Thin line: one forecast origin.
3Callout 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
# Backtest errors by horizon — Codesplash Chart Lab (recipe "backtest-errors")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = make_subplots(rows=1, cols=len(metrics), subplot_titles=[str(m) if m is not None else E for m in metrics])
for i, met in enumerate(metrics, start=1):
g = d if met is None else d[d[MET].astype(str) == str(met)]
if ORIG:
for name, s in g.groupby(ORIG, observed=True):
fig.add_scatter(x=s[H], y=s[E], mode="lines", line=dict(color=GREY, width=1), name=str(name), showlegend=False, row=1, col=i)
mean = g.groupby(H)[E].mean()
fig.add_scatter(x=mean.index, y=mean.values, mode="lines+markers", line=dict(color=PALETTE[(i - 1) % len(PALETTE)], width=3), name="mean", showlegend=i == 1, row=1, col=i)
fig.update_xaxes(title_text=H, row=1, col=i)
fig.update_yaxes(title_text=E, row=1, col=1)
fig.show()
Needs pandas, numpy, plotly · reads backtest-errors-demo.csv · app theme from the optional codesplash helper
Read bars outside the band as autocorrelation beyond noise.
For model residuals, you want nothing outside.
A spike at the seasonal lag means the season is not fully modelled.
1Callout 1: A bar beyond the band, at the seasonal lag.
2Callout 2: The band: the range for white noise.
3Callout 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
# ACF / PACF (precomputed) — Codesplash Chart Lab (recipe "acf-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = make_subplots(rows=1, cols=len(kinds), shared_yaxes=True, subplot_titles=[str(k).upper() if k is not None else ACF for k in kinds])
for i, k in enumerate(kinds, start=1):
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:
fig.add_hrect(y0=-bound, y1=bound, fillcolor=GREY, opacity=0.4, line_width=0, row=1, col=i)
out = (g[ACF].abs() > bound) if bound is not None else pd.Series(False, index=g.index)
fig.add_bar(x=g[LAG], y=g[ACF], width=0.25, marker_color=np.where(out, "#ce5342", PALETTE[0]), showlegend=False, row=1, col=i)
fig.update_xaxes(title_text=LAG, row=1, col=i)
fig.update_yaxes(title_text=ACF, row=1, col=1)
fig.show()
Needs pandas, numpy, plotly · reads acf-plot-demo.csv · app theme from the optional codesplash helper
Read rows sorted by distance to their k-th neighbour.
The ringed knee is where distances begin to climb.
Use the distance at the knee for eps: rows above it become noise.
1Callout 1: The knee: a candidate for eps.
2Callout 2: Flat region: rows in dense areas.
3Callout 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
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")# controls: eps=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=d[X], y=d[D], mode="lines", line=dict(color=PALETTE[0]), name="sorted k-distance")
if eps:
fig.add_hline(y=eps, line_dash="dash", line_color=REF, annotation_text=f"eps = {eps:.3g}")
fig.update_layout(xaxis_title="rows (sorted)", yaxis_title=D)
fig.show()
Needs pandas, numpy, plotly · reads k-distance-demo.csv · app theme from the optional codesplash helper
# k-distance curve — Codesplash Chart Lab (recipe "k-distance")# controls: eps=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("k-distance-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["chosen eps"]] <- as.logical(df[["chosen eps"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
X <- "rows (sorted)"
D <- "distance to the 5th neighbour"
CH <- "chosen eps"
d <- data.frame(x = df[[X]], y = df[[D]], chosen = if (is.null(CH)) FALSE else as.logical(df[[CH]]))
d <- d[is.finite(d$x) & is.finite(d$y), ]
d <- d[order(d$x), ]
eps <- 0
if (!eps && any(d$chosen, na.rm = TRUE)) eps <- d$y[which(d$chosen)[1]]
p <- ggplot(d, aes(x, y)) +
geom_line(colour = cs_cat[[1]]) +
(if (eps) geom_hline(yintercept = eps, colour = ref_col, linetype = "dashed")) +
geom_point(data = d[which(d$chosen), ], shape = 1, size = 3, colour = ref_col) +
labs(x = "rows (sorted)", y = D) + theme_cs
print(p)
Needs ggplot2 · reads k-distance-demo.csv · app theme from the optional codesplashr helper
Read each valley as a cluster; deeper valleys are denser.
Read the peaks between valleys as the boundaries.
1Callout 1: A valley: one cluster.
2Callout 2: A peak: a boundary between clusters.
3Callout 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
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")# controls: cut=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
no_reach = d[R].isna() | (d[U].astype(str).str.lower() == "true" if U else False)
fig = go.Figure()
fig.add_bar(x=d.loc[no_reach, X], y=[d[R].max() * 1.05] * int(no_reach.sum()), name="no reachability", marker_color=GREY)
for i, k in enumerate(levels_of(d[K]) if K else ["rows"]):
g = d[d[K].astype(str) == str(k)] if K else d
fig.add_bar(x=g[X], y=g[R], name=str(k), marker_color=GREY if str(k).lower() in ("noise", "-1") else PALETTE[i % len(PALETTE)])
fig.update_layout(barmode="overlay", bargap=0, xaxis_title="OPTICS order", yaxis_title="reachability distance")
fig.show()
Needs pandas, numpy, plotly · reads reachability-plot-demo.csv · app theme from the optional codesplash helper
# Reachability plot (OPTICS) — Codesplash Chart Lab (recipe "reachability-plot")# controls: cut=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("reachability-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["no reachability"]] <- as.logical(df[["no reachability"]])
df[["cluster"]] <- factor(df[["cluster"]], levels = c("1", "2", "3", "-1"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
X <- "OPTICS order"
R <- "reachability distance"
K <- "cluster"
U <- "no reachability"
d <- data.frame(x = df[[X]], y = df[[R]], k = if (is.null(K)) "rows" else as.character(df[[K]]))
if (!is.null(U)) d$y[as.logical(df[[U]])] <- NA # the start of a region has no reachability
d$k[is.na(d$k)] <- "noise"
lv <- unique(d$k)
cols <- setNames(rep_len(cs_cat, length(lv)), lv)
cols[lv %in% c("noise", "-1")] <- grey_col
top <- max(d$y, na.rm = TRUE) * 1.05
d$y[!is.finite(d$y)] <- top
p <- ggplot(d, aes(x, y, fill = k)) +
geom_col(width = 1) +
scale_fill_manual(values = cols, name = NULL) +
labs(x = "OPTICS order", y = "reachability distance") + theme_cs
print(p)
Needs ggplot2 · reads reachability-plot-demo.csv · app theme from the optional codesplashr helper
Read a cell as how often two rows cluster together across resamples.
Solid dark blocks: stable clusters.
Mottled cells between blocks: rows that move between clusters.
1Callout 1: A solid block: a stable cluster.
2Callout 2: Another block.
3Callout 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
# Consensus matrix — Codesplash Chart Lab (recipe "consensus-heatmap")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Heatmap(z=m.to_numpy(), x=m.columns, y=m.index, colorscale="Blues", reversescale=False, colorbar=dict(title=V)))
fig.update_layout(xaxis_title="row (by cluster)", yaxis_title="row (by cluster)", yaxis_autorange="reversed", yaxis_scaleanchor="x")
fig.show()
Needs pandas, numpy, plotly · reads consensus-heatmap-demo.csv · app theme from the optional codesplash helper
# Consensus matrix — Codesplash Chart Lab (recipe "consensus-heatmap")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("consensus-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
R <- "row (by cluster)"
C <- "column (by cluster)"
V <- "share of resamples together"
d <- data.frame(r = df[[R]], c = df[[C]], v = df[[V]])
p <- ggplot(d, aes(c, r, fill = v)) +
geom_raster() +
scale_fill_gradient(low = seq_ramp[[1]], high = seq_ramp[[length(seq_ramp)]], name = V) +
scale_y_reverse() + coord_equal() +
labs(x = "row (by cluster)", y = "row (by cluster)") + theme_cs
print(p)
Needs ggplot2 · reads consensus-heatmap-demo.csv · app theme from the optional codesplashr helper
Read ribbon width as how many journeys take that move.
Look for the widest paths and for the (end) nodes, where journeys stop.
1Callout 1: The first step: where journeys start.
2Callout 2: A wide ribbon: a common move.
3Callout 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
# Journey flow — Codesplash Chart Lab (recipe "sequence-sankey")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
fig = go.Figure(go.Sankey(node=dict(label=nodes, pad=12), link=dict(source=[index[str(v)] for v in d[SRC]], target=[index[str(v)] for v in d[DST]], value=d[N])))
fig.show()
Needs pandas, numpy, plotly · reads sequence-sankey-demo.csv · app theme from the optional codesplash helper
Read a band's thickness as that topic's share or count in that period.
A widening band is a rising topic; the bottom band is the easiest to read.
Switch between share and counts: a share can fall while the count rises.
1Callout 1: The largest topic, at the bottom.
2Callout 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
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")# controls: mode=share, top=6
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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 = go.Figure()
for i, k in enumerate(wide.columns):
fig.add_scatter(x=wide.index, y=wide[k], mode="lines", stackgroup="one", name=str(k), line=dict(color=PALETTE[i % len(PALETTE)], width=0.5),
fillpattern=dict(shape=SERIES_HATCHES[i % 8], fgcolor=HATCH_INK, fillmode="overlay")) # texture per topic, as in the app
fig.update_layout(xaxis_title=T, yaxis_title="share" if SHARE else "count")
fig.show()
Needs pandas, numpy, plotly · reads topics-over-time-demo.csv · app theme from the optional codesplash helper
# Topics over time — Codesplash Chart Lab (recipe "topics-over-time")# controls: mode=share, top=6
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("topics-over-time-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["topic"]] <- factor(df[["topic"]])
T <- "month"
K <- "topic"
W <- "tickets"
TOP <- 6; SHARE <- TRUE
d <- data.frame(t = df[[T]], k = as.character(df[[K]]), w = if (is.null(W)) 1 else df[[W]])
d <- d[!is.na(d$t) & !is.na(d$k), ]
totals <- sort(tapply(d$w, d$k, sum), decreasing = TRUE)
keep <- names(totals)[seq_len(min(TOP, length(totals)))]
d$k[!d$k %in% keep] <- "Other"
a <- aggregate(w ~ t + k, d, sum)
lv <- c(keep, if ("Other" %in% a$k) "Other")
a$k <- factor(a$k, levels = rev(lv)) # largest topic at the bottom
full <- merge(expand.grid(t = unique(a$t), k = levels(a$k)), a, all.x = TRUE)
full$w[is.na(full$w)] <- 0
full$k <- factor(full$k, levels = rev(lv))
p <- ggplot(full, aes(t, w, fill = k)) +
geom_area(position = if (SHARE) "fill" else "stack", alpha = 0.85) +
scale_fill_manual(values = setNames(cs_textures(rep_len(cs_cat, length(lv))), lv), name = NULL) + # texture per topic, as in the app
labs(x = T, y = if (SHARE) "share" else "count") + theme_cs
print(p)
Needs ggplot2 · reads topics-over-time-demo.csv · app theme from the optional codesplashr helper
Read each point as one row's position in the latent space (its posterior mean μ).
The dashed rings are the prior's 1σ and 2σ circles; rows should spread across them without big empty regions.
Clusters of colour show what the model separates; points far outside 2σ decode from places the prior rarely samples.
1Callout 1: The prior's centre.
2Callout 2: The 2σ ring.
3Callout 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
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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]
fig.add_trace(go.Scatter(x=s[X], y=s[Y], mode="markers", marker=dict(size=5, opacity=0.75, symbol=SERIES_MARKERS[i % 8]), name=name or "rows")) # marker shape per group
for r in (1, 2): # the N(0, I) prior's 1σ and 2σ rings
fig.add_shape(type="circle", x0=-r, y0=-r, x1=r, y1=r, line=dict(color="grey", dash="dash", width=1))
m = max(2.2, 1.05 * float(np.abs(d[[X, Y]].to_numpy()).max()))
fig.update_xaxes(range=[-m, m], title=X)
fig.update_yaxes(range=[-m, m], title=Y, scaleanchor="x", scaleratio=1)
fig.update_layout(template="plotly_white")
fig.show()
Needs pandas, numpy, plotly · reads latent-prior-demo.csv · app theme from the optional codesplash helper
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("latent-prior-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "latent 1 (μ)"
Y <- "latent 2 (μ)"
G <- "species"
d <- df[!is.na(df[[X]]) & !is.na(df[[Y]]), ]
d$grp <- if (is.null(G)) "rows" else factor(as.character(d[[G]]), levels = levels_of(d[[G]]))
theta <- seq(0, 2 * pi, length.out = 200)
rings <- do.call(rbind, lapply(1:2, function(r) data.frame(r = r, x = r * cos(theta), y = r * sin(theta))))
r2 <- d[[X]]^2 + d[[Y]]^2
labs_df <- data.frame(x = c(1, 2) * 0.707, y = c(1, 2) * 0.707,
label = sprintf("%dσ: %.0f%% inside (prior %.0f%%)", 1:2, 100 * sapply(1:2, function(r) mean(r2 <= r^2)), 100 * (1 - exp(-(1:2)^2 / 2))))
m <- max(2.2, 1.05 * max(abs(c(d[[X]], d[[Y]]))))
p <- ggplot(d, aes(x = .data[[X]], y = .data[[Y]])) +
geom_path(data = rings, aes(x = x, y = y, group = r), linetype = "dashed", colour = "grey50", inherit.aes = FALSE) +
geom_point(aes(colour = grp, shape = grp), size = 1.2, alpha = 0.75) + scale_shape_manual(values = cs_shapes) + # marker shape per group, as in the app
geom_text(data = labs_df, aes(x = x, y = y, label = label), size = 2.8, colour = "grey40", hjust = 0, inherit.aes = FALSE) +
coord_equal(xlim = c(-m, m), ylim = c(-m, m)) + labs(x = X, y = Y, colour = NULL, shape = NULL) + theme_minimal()
print(p)
Needs ggplot2 · reads latent-prior-demo.csv · app theme from the optional codesplashr helper
KPI & dashboard widgets
Headline numbers with change and targets: KPI tiles, sparklines, bullet charts, gauges, progress and variance to target.
Read the change below it, against the previous period.
Read the sparkline for context and the bar for progress to target.
1Callout 1: The latest value.
2Callout 2: Change against the previous period.
3Callout 3: Recent shape.
4Callout 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 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
s = k["series"]
if s is not None and len(s) >= 2: # sparkline: equal spacing per period, filled down to its minimum
xs, lo, hi = list(range(len(s))), s["v"].min(), s["v"].max()
fig.add_scatter(x=xs, y=[lo] * len(s), mode="lines", line=dict(width=0), hoverinfo="skip")
fig.add_scatter(x=xs, y=s["v"], mode="lines", line=dict(color=COL, width=2), fill="tonexty", fillcolor="rgba(41,113,198,0.15)",
hovertext=[period_name(t, GRAIN) for t in s["t"]], hoverinfo="text+y")
fig.add_scatter(x=[xs[-1]], y=[s["v"].iloc[-1]], mode="markers", marker=dict(color=COL, size=8), hoverinfo="skip")
fig.update_yaxes(range=[lo - (hi - lo) * 0.02, hi + (hi - lo) * 0.05])
fig.update_layout(width=640, height=360, showlegend=False, margin=dict(l=24, r=24, t=24, b=24),
xaxis=dict(visible=False, domain=[0, 1]), yaxis=dict(visible=False, domain=[0.18 if target else 0.04, 0.55]))
notes = [(label, 0.98, 12, MUTED, "left"), (fmt_kpi(k["value"], STYLE), 0.86, 40, FG, "left"),
(fmt_delta(k['delta'], k['pct'], STYLE), 0.66, 12, delta_colour, "left"), (caption, 0.66, 12, MUTED, "right")]
for text, y, size, colour, align in notes:
fig.add_annotation(text=text, x=0 if align == "left" else 1, y=y, xref="paper", yref="paper", showarrow=False,
xanchor=align, yanchor="top", font=dict(size=size, color=colour))
if target: # progress to target
fig.add_annotation(text=target_text, x=0, y=0.12, xref="paper", yref="paper", showarrow=False, xanchor="left", font=dict(size=11, color=MUTED))
fig.add_shape(type="rect", x0=0, x1=1, y0=0.0, y1=0.03, xref="paper", yref="paper", fillcolor=TRACK, line_width=0)
fig.add_shape(type="rect", x0=0, x1=min(max(progress, 0), 1), y0=0.0, y1=0.03, xref="paper", yref="paper",
fillcolor=PASS if progress >= 1 else COL, line_width=0)
fig.show()
Needs pandas, numpy, plotly · reads kpi-tile-demo.csv · app theme from the optional codesplash helper
# KPI tile — Codesplash Chart Lab (recipe "kpi-tile")# controls: agg=sum, grain=month, compare=true, points=12, good=up, format=compact, target=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("kpi-tile-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
AGG <- "sum"; GRAIN <- "month"; POINTS <- 12; COMPARE <- TRUE; GOOD <- "up"; STYLE <- "compact"
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
k <- kpi(df, "date", "revenue", "target", GRAIN, AGG, POINTS, COMPARE)
target <- if (!is.null(k$target) && is.finite(k$target)) k$target else FIXED_TARGET
progress <- if (is.null(target)) NULL else k$value / target
caption <- if (is.null(k$period)) sprintf("all rows (n = %s)", format(k$n, big.mark = ",")) else if (!is.null(k$previous)) paste(period_name(k$period, GRAIN), "vs", period_name(k$prev_period, GRAIN)) else period_name(k$period, GRAIN)
delta_colour <- c("1" = pass, "-1" = fail, "0" = muted)[[as.character(tone_of(k$delta, GOOD))]]
foot <- trimws(paste(fmt_delta(k$delta, k$pct, STYLE), " ", caption)) # signed change (no arrow glyphs: not in every font)
if (!is.null(target)) foot <- paste0(foot, "\n", fmt_kpi(progress, "percent", 0), " of target ", fmt_kpi(target, STYLE))
s <- if (is.null(k$series)) data.frame(i = numeric(), v = numeric()) else data.frame(i = seq_len(nrow(k$series)) - 1, v = k$series$v)
spark <- if (nrow(s) < 2) list() else list( # equal spacing per period, filled down to its minimum
geom_ribbon(aes(ymin = min(v, na.rm = TRUE), ymax = v), fill = col, alpha = 0.15),
geom_line(colour = col, linewidth = 1),
geom_point(data = utils::tail(s, 1), colour = col, size = 2.5))
p <- ggplot(s, aes(i, v)) +
spark +
labs(title = "revenue · sum", subtitle = fmt_kpi(k$value, STYLE), caption = foot, x = NULL, y = NULL) +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(plot.title = element_text(size = 12, colour = muted), plot.subtitle = element_text(size = 32, face = "bold", colour = fg),
plot.caption = element_text(hjust = 0, size = 11, colour = delta_colour), plot.caption.position = "plot", plot.title.position = "plot")
print(p)
Needs ggplot2 · reads kpi-tile-demo.csv · app theme from the optional codesplashr helper
-- KPI tile — Codesplash Chart Lab (recipe "kpi-tile")-- controls: agg=sum, grain=month, compare=true, points=12, good=up, format=compact, target=0-- KPI per month (UTC; DuckDB weeks start on Monday): value, previous period, change, target
WITH p AS (
SELECT date_trunc('month', "date") AS period, sum("revenue") AS value, sum("target") AS target, count(*) AS n
FROM read_csv('kpi-tile-demo.csv')
WHERE "date" IS NOT NULL
GROUP BY 1
)
SELECT cur.period, cur.value, prev.value AS previous, cur.value - prev.value AS change,
(cur.value - prev.value) / nullif(abs(prev.value), 0) AS pct_change, cur.target, cur.value / nullif(cur.target, 0) AS progress, cur.n
FROM p AS cur
LEFT JOIN p AS prev ON prev.period = cur.period - INTERVAL 1 MONTH
ORDER BY cur.period DESC
LIMIT 12 -- the first row is the KPI; all rows are the sparkline
Read the labelled minimum, maximum and last value.
The shaded band marks the middle half.
1Callout 1: The maximum.
2Callout 2: The minimum.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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()
xs = list(range(len(s)))
fig = go.Figure()
if BAND == "iqr":
fig.add_hrect(y0=q1, y1=q3, fillcolor=MUTED, opacity=0.14, line_width=0)
fig.add_scatter(x=xs, y=s["v"], mode="lines", line=dict(color=COL, width=2), hovertext=[period_name(t, GRAIN) for t in s["t"]], hoverinfo="text+y")
if MARKERS:
fig.add_scatter(x=[imin, imax], y=[s["v"][imin], s["v"][imax]], mode="markers+text", marker=dict(color=[FAIL, PASS], size=8),
text=[fmt_kpi(s["v"][imin], STYLE), fmt_kpi(s["v"][imax], STYLE)], textposition=["bottom center", "top center"], hoverinfo="skip")
fig.add_scatter(x=[xs[-1]], y=[s["v"].iloc[-1]], mode="markers", marker=dict(color=COL, size=8), hoverinfo="skip")
fig.update_layout(width=640, height=160, showlegend=False, margin=dict(l=150, r=110, t=20, b=20),
xaxis=dict(visible=False), yaxis=dict(visible=False))
name = "revenue"
fig.add_annotation(text=f"<b>{name}</b><br><span style='color:{MUTED}'>{AGG} per {GRAIN}</span>", x=-0.02, y=0.5, xref="paper", yref="paper",
showarrow=False, xanchor="right", align="left")
fig.add_annotation(text=f"<b>{fmt_kpi(s['v'].iloc[-1], STYLE)}</b><br><span style='color:{MUTED}'>{period_name(s['t'].iloc[-1], GRAIN)}</span>",
x=1.02, y=0.5, xref="paper", yref="paper", showarrow=False, xanchor="left", align="right")
fig.show()
Needs pandas, numpy, plotly · reads sparkline-demo.csv · app theme from the optional codesplash helper
# Sparkline — Codesplash Chart Lab (recipe "sparkline")# controls: agg=sum, grain=month, points=24, band=iqr, markers=true, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("sparkline-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
AGG <- "sum"; GRAIN <- "month"; POINTS <- 24; STYLE <- "compact"
BAND <- "iqr"; MARKERS <- TRUE
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
s <- utils::tail(period_series(df, "date", "revenue", GRAIN, AGG), POINTS)
s <- s[is.finite(s$v), , drop = FALSE]
s$i <- seq_len(nrow(s)) - 1
q <- unname(stats::quantile(s$v, c(0.25, 0.75), type = 7)) # the "normal range" band
ext <- s[c(which.min(s$v), which.max(s$v)), ]
ext$colour <- c(fail, pass)
p <- ggplot(s, aes(i, v)) +
(if (BAND == "iqr") annotate("rect", xmin = -Inf, xmax = Inf, ymin = q[1], ymax = q[2], fill = muted, alpha = 0.14) else NULL) +
geom_line(colour = col, linewidth = 0.9) +
(if (MARKERS) geom_point(data = ext, aes(colour = I(colour)), size = 2.2) else NULL) +
(if (MARKERS) geom_text(data = ext, aes(label = vapply(v, fmt_kpi, character(1), style = STYLE)), vjust = c(1.8, -1), size = 3, colour = muted) else NULL) +
geom_point(data = utils::tail(s, 1), colour = col, size = 2.2) +
labs(title = "revenue", subtitle = paste(AGG, "per", GRAIN), tag = paste0(fmt_kpi(utils::tail(s$v, 1), STYLE), "\n", period_name(utils::tail(s$t, 1), GRAIN)), x = NULL, y = NULL) +
scale_y_continuous(expand = expansion(mult = 0.25)) +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
theme(plot.tag.position = "right", plot.tag = element_text(size = 12, face = "bold", hjust = 1), plot.subtitle = element_text(colour = muted))
print(p)
Needs ggplot2 · reads sparkline-demo.csv · app theme from the optional codesplashr helper
-- Sparkline — Codesplash Chart Lab (recipe "sparkline")-- controls: agg=sum, grain=month, points=24, band=iqr, markers=true, format=compact-- sum per month (UTC), latest 24 periods
SELECT date_trunc('month', "date") AS period, sum("revenue") AS value, count(*) AS n
FROM read_csv('sparkline-demo.csv')
WHERE "date" IS NOT NULL
GROUP BY 1
ORDER BY 1 DESC
LIMIT 24
Read the grey bands as poor, satisfactory and good ranges.
1Callout 1: Actual reaches past the target.
2Callout 2: The tick: the target.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = float(np.nanmax(np.r_[rows["value"], rows["target"] * 1.15, 0]))
fig = go.Figure()
n = len(rows)
for i, r in rows.reset_index(drop=True).iterrows(): # one bullet gauge per group (Stephen Few)
t = r["target"]
steps = []
if SHOW_BANDS and np.isfinite(t) and t > 0:
edges = [0] + [b * t for b in BANDS]
steps = [dict(range=[lo, hi], color=f"rgba(98,106,117,{a})") for lo, hi, a in zip(edges[:-1], edges[1:], [0.32, 0.2, 0.1])]
fig.add_trace(go.Indicator(
mode="number+gauge", value=r["value"], title=dict(text=r["group"], font=dict(size=12)),
number=dict(valueformat=",.0f", font=dict(size=14)),
domain=dict(x=[0.18, 0.88], y=[1 - (i + 1) / n + 0.02, 1 - i / n - 0.02]),
gauge=dict(shape="bullet", axis=dict(range=[0, top]), bar=dict(color=COL, thickness=0.35), steps=steps,
**({"threshold": dict(value=t, line=dict(color=FG, width=3), thickness=0.8)} if np.isfinite(t) else {}))))
fig.update_layout(width=720, height=80 + 70 * n, margin=dict(l=20, r=20, t=20, b=20))
fig.show()
Needs pandas, numpy, plotly · reads bullet-chart-demo.csv · app theme from the optional codesplash helper
# Bullet chart — Codesplash Chart Lab (recipe "bullet-chart")# controls: agg=sum, target=0, bands=true, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("bullet-chart-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
target_rows <- function(d, group, value, target, how, fixed, levels) {
# per group: the aggregate of the values and of the targets (or the fixed target)
out <- do.call(rbind, lapply(levels, function(lv) {
g <- d[as.character(d[[group]]) %in% lv, , drop = FALSE]
t <- if (is.null(target)) (if (is.null(fixed)) NA_real_ else fixed) else agg(g[[target]], how)
data.frame(group = lv, value = agg(g[[value]], how), target = t, n = nrow(g))
}))
out$variance <- out$value - out$target
out$variance_pct <- ifelse(is.finite(out$target) & out$target != 0, out$variance / abs(out$target), NA_real_)
out$progress <- ifelse(is.finite(out$target) & out$target != 0, out$value / out$target, NA_real_)
out
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; STYLE <- "compact"; GOOD <- "up"
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
rows <- target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df[["region"]], 12))
SHOW_BANDS <- TRUE
rows$group <- factor(rows$group, levels = rev(rows$group))
top <- max(c(rows$value, rows$target * 1.15, 0), na.rm = TRUE)
bands <- do.call(rbind, lapply(seq_len(nrow(rows)), function(i) {
t <- rows$target[i]
if (!SHOW_BANDS || !is.finite(t) || t <= 0) return(NULL)
e <- c(0, 0.6, 0.8, 1) * t # poor / satisfactory / good
data.frame(group = rows$group[i], lo = e[-4], hi = e[-1], alpha = c(0.32, 0.2, 0.1))
}))
y_of <- function(g) as.numeric(g)
p <- ggplot(rows) +
(if (!is.null(bands)) geom_rect(data = bands, aes(xmin = lo, xmax = hi, ymin = y_of(group) - 0.4, ymax = y_of(group) + 0.4, alpha = I(alpha)), fill = muted) else NULL) +
geom_rect(aes(xmin = 0, xmax = value, ymin = y_of(group) - 0.16, ymax = y_of(group) + 0.16), fill = col) +
geom_segment(data = rows[is.finite(rows$target), ], aes(x = target, xend = target, y = y_of(group) - 0.3, yend = y_of(group) + 0.3), colour = fg, linewidth = 1.2) +
geom_text(aes(x = top * 1.04, y = y_of(group), label = vapply(value, fmt_kpi, character(1), style = STYLE)), hjust = 0, size = 3.2, colour = fg) +
scale_y_continuous(breaks = seq_len(nrow(rows)), labels = levels(rows$group)) +
scale_x_continuous(limits = c(0, top * 1.15), expand = c(0, 0), labels = function(v) vapply(v, fmt_kpi, character(1), style = "compact", decimals = 0)) +
labs(x = paste0("revenue", " (", AGG, ")"), y = NULL) +
theme_cs + theme(panel.grid.major.y = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads bullet-chart-demo.csv · app theme from the optional codesplashr helper
-- Bullet chart — Codesplash Chart Lab (recipe "bullet-chart")-- controls: agg=sum, target=0, bands=true, format=compact-- per group: sum of the value and the target
WITH g AS (
SELECT "region" AS "group", sum("revenue") AS actual, sum("target") AS target, count(*) AS n
FROM read_csv('bullet-chart-demo.csv')
WHERE "region" IS NOT NULL
GROUP BY 1
)
SELECT "group", actual, target, actual / nullif(target, 0) AS progress, n
FROM g
ORDER BY n DESC, "group"
Read the arc's length as the value on a fixed scale.
Compare with the target tick.
Read the coloured outer rim for the bands, if on.
1Callout 1: The value.
2Callout 2: The target tick.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
n = len(rows)
for i, r in enumerate(rows.itertuples()):
steps = []
if SHOW_BANDS and np.isfinite(r.target) and r.target > 0:
gap = 0.8 / 180 * r.max # small gaps between zones so they read without colour, as in the app
zones = [(0, 0.6, "rgba(201,48,45,0.25)"), (0.6, 0.8, "rgba(98,106,117,0.2)"), (0.8, 1.0, "rgba(24,124,73,0.25)")]
steps = [dict(range=[lo * r.target + (gap if k > 0 else 0), hi * r.target - (gap if k < 2 else 0)], color=colour) for k, (lo, hi, colour) in enumerate(zones)]
met = np.isfinite(r.target) and r.value >= r.target
fig.add_trace(go.Indicator(
mode="gauge+number", value=r.value, title=dict(text=r.group if n > 1 else "", font=dict(size=13)),
domain=dict(x=[i / n + 0.02, (i + 1) / n - 0.02], y=[0, 1]),
gauge=dict(axis=dict(range=[0, r.max]), bar=dict(color=PASS if met else COL), steps=steps, bgcolor=TRACK,
**({"threshold": dict(value=r.target, line=dict(color=FG, width=3), thickness=0.9)} if np.isfinite(r.target) else {}))))
fig.update_layout(width=max(420, 320 * n), height=320)
fig.show()
Needs pandas, numpy, plotly · reads gauge-demo.csv · app theme from the optional codesplash helper
# Gauge — Codesplash Chart Lab (recipe "gauge")# controls: agg=sum, target=0, max=0, bands=true, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("gauge-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
target_rows <- function(d, group, value, target, how, fixed, levels) {
# per group: the aggregate of the values and of the targets (or the fixed target)
out <- do.call(rbind, lapply(levels, function(lv) {
g <- d[as.character(d[[group]]) %in% lv, , drop = FALSE]
t <- if (is.null(target)) (if (is.null(fixed)) NA_real_ else fixed) else agg(g[[target]], how)
data.frame(group = lv, value = agg(g[[value]], how), target = t, n = nrow(g))
}))
out$variance <- out$value - out$target
out$variance_pct <- ifelse(is.finite(out$target) & out$target != 0, out$variance / abs(out$target), NA_real_)
out$progress <- ifelse(is.finite(out$target) & out$target != 0, out$value / out$target, NA_real_)
out
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
AGG <- "sum"; STYLE <- "compact"; SCALE_MAX <- NULL; SHOW_BANDS <- TRUE
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
df_all <- df; df_all[[".all"]] <- "revenue"
rows <- target_rows(df_all, ".all", "revenue", "target", AGG, FIXED_TARGET, "revenue")
nice_ceil <- function(v) {
# a round scale maximum: 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8 or 10 x a power of ten
if (!(v > 0)) return(1)
p <- 10^floor(log10(v))
m <- c(1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10)
m[m * p >= v][1] * p
}
rows$max <- if (!is.null(SCALE_MAX)) SCALE_MAX else mapply(function(v, t) nice_ceil(max(v, if (is.na(t)) 0 else t * 1.25, 0)), rows$value, rows$target)
arc <- function(r0, r1, a0, a1, n = 60) {
# a ring segment between radii r0 < r1 and angles a0 < a1 (radians, pi = 0 on the left, 0 = scale max)
a <- seq(a0, a1, length.out = n)
data.frame(x = c(r1 * cos(a), rev(r0 * cos(a))), y = c(r1 * sin(a), rev(r0 * sin(a))))
}
panel <- function(i) {
r <- rows[i, ]
frac <- if (is.finite(r$value)) min(max(r$value / r$max, 0), 1) else 0
met <- is.finite(r$target) && r$value >= r$target
parts <- list(cbind(arc(0.8, 1, 0, pi), part = "track", fill = track))
if (frac > 0) parts <- c(parts, list(cbind(arc(0.8, 1, pi * (1 - frac), pi), part = "value", fill = if (met) pass else col)))
if (SHOW_BANDS && is.finite(r$target) && r$target > 0) {
gap <- 0.8 * pi / 180 # small gaps between zones so they read without colour, as in the app
for (b in list(c(0, 0.6), c(0.6, 0.8), c(0.8, 1))) {
a <- pi * (1 - pmin(b * r$target / r$max, 1))
a0 <- a[2] + if (b[2] < 1) gap else 0; a1 <- a[1] - if (b[1] > 0) gap else 0
if (a1 > a0) parts <- c(parts, list(cbind(arc(1.05, 1.08, a0, a1), part = paste("band", b[1]), fill = c(fail, muted, pass)[match(b[1], c(0, 0.6, 0.8))])))
}
}
d <- do.call(rbind, parts)
d$group <- r$group
d
}
polys <- do.call(rbind, lapply(seq_len(nrow(rows)), panel))
labs_df <- data.frame(group = rows$group, value = vapply(rows$value, fmt_kpi, character(1), style = STYLE),
sub = ifelse(is.na(rows$target), rows$group, paste0(vapply(rows$progress, fmt_kpi, character(1), style = "percent", decimals = 0), " of ", vapply(rows$target, fmt_kpi, character(1), style = STYLE))))
ticks <- do.call(rbind, lapply(seq_len(nrow(rows)), function(i) {
r <- rows[i, ]
if (!is.finite(r$target)) return(NULL)
a <- pi * (1 - min(max(r$target / r$max, 0), 1))
data.frame(group = r$group, x = 0.76 * cos(a), y = 0.76 * sin(a), xend = 1.04 * cos(a), yend = 1.04 * sin(a))
}))
p <- ggplot() +
geom_polygon(data = polys, aes(x, y, group = interaction(group, part), fill = I(fill))) +
(if (!is.null(ticks)) geom_segment(data = ticks, aes(x = x, y = y, xend = xend, yend = yend), colour = fg, linewidth = 1.2) else NULL) +
geom_text(data = labs_df, aes(0, 0.12, label = value), size = 7, fontface = "bold", colour = fg) +
geom_text(data = labs_df, aes(0, -0.1, label = sub), size = 3, colour = muted) +
(if (nrow(rows) > 1) facet_wrap(~group) else NULL) +
coord_equal(xlim = c(-1.15, 1.15), ylim = c(-0.25, 1.15)) +
labs(x = NULL, y = NULL) +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads gauge-demo.csv · app theme from the optional codesplashr helper
-- Gauge — Codesplash Chart Lab (recipe "gauge")-- controls: agg=sum, target=0, max=0, bands=true, format=compact-- one gauge: sum of the value against the target
SELECT sum("revenue") AS value, sum("target") AS target, count(*) AS n
FROM read_csv('gauge-demo.csv')
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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
labels = ["no target" if not np.isfinite(t) else f"{fmt_kpi(p, 'percent', 0)} {fmt_kpi(v)} / {fmt_kpi(t)}"
for p, v, t in zip(rows["progress"], rows["value"], rows["target"])]
fig = go.Figure(go.Bar(
y=rows["group"], x=np.minimum(rows["progress"].fillna(0), top), orientation="h", text=labels, textposition="outside",
marker_color=[PASS if p >= 1 else COL for p in rows["progress"].fillna(0)], cliponaxis=False))
fig.add_vline(x=1, line_dash="dash", line_color=MUTED)
fig.update_layout(width=760, height=120 + 50 * len(rows), xaxis=dict(range=[0, top], tickformat=".0%", title="% of target"),
yaxis=dict(autorange="reversed"), margin=dict(r=170), showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads target-progress-demo.csv · app theme from the optional codesplash helper
# Progress to target — Codesplash Chart Lab (recipe "target-progress")# controls: agg=sum, target=0, sort=progress, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("target-progress-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
target_rows <- function(d, group, value, target, how, fixed, levels) {
# per group: the aggregate of the values and of the targets (or the fixed target)
out <- do.call(rbind, lapply(levels, function(lv) {
g <- d[as.character(d[[group]]) %in% lv, , drop = FALSE]
t <- if (is.null(target)) (if (is.null(fixed)) NA_real_ else fixed) else agg(g[[target]], how)
data.frame(group = lv, value = agg(g[[value]], how), target = t, n = nrow(g))
}))
out$variance <- out$value - out$target
out$variance_pct <- ifelse(is.finite(out$target) & out$target != 0, out$variance / abs(out$target), NA_real_)
out$progress <- ifelse(is.finite(out$target) & out$target != 0, out$value / out$target, NA_real_)
out
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; STYLE <- "compact"; GOOD <- "up"
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
rows <- target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df[["region"]], 12))
SORT <- "progress"
if (SORT != "order") rows <- rows[order(-rows[[if (SORT == "value") "value" else "progress"]], na.last = TRUE), ]
top <- max(1.2, ceiling(max(c(rows$progress, 0), na.rm = TRUE) * 10) / 10)
rows$group <- factor(rows$group, levels = rev(rows$group))
rows$shown <- pmin(ifelse(is.na(rows$progress), 0, rows$progress), top)
rows$label <- ifelse(is.na(rows$progress), "no target", paste0(vapply(rows$progress, fmt_kpi, character(1), style = "percent", decimals = 0), " ", vapply(rows$value, fmt_kpi, character(1)), " / ", vapply(rows$target, fmt_kpi, character(1))))
p <- ggplot(rows, aes(shown, group)) +
geom_col(aes(x = top), fill = muted, alpha = 0.08, width = 0.7) +
geom_col(aes(fill = I(ifelse(shown >= 1, pass, col))), width = 0.7) +
geom_vline(xintercept = 1, linetype = "dashed", colour = muted) +
geom_text(aes(x = top, label = label), hjust = -0.05, size = 3.2, colour = fg) +
scale_x_continuous(labels = function(v) paste0(round(v * 100), "%"), limits = c(0, top * 1.6), breaks = seq(0, top, 0.2), expand = c(0, 0)) +
labs(x = "% of target", y = NULL) +
theme_cs
print(p)
Needs ggplot2 · reads target-progress-demo.csv · app theme from the optional codesplashr helper
-- Progress to target — Codesplash Chart Lab (recipe "target-progress")-- controls: agg=sum, target=0, sort=progress, format=compact-- per group: sum of the value and the target
WITH g AS (
SELECT "region" AS "group", sum("revenue") AS actual, sum("target") AS target, count(*) AS n
FROM read_csv('target-progress-demo.csv')
WHERE "region" IS NOT NULL
GROUP BY 1
)
SELECT "group", actual, target, actual / nullif(target, 0) AS progress, n
FROM g
ORDER BY n DESC, "group"
Read bars from the centre: right is above target, left is below.
Read colour as better or worse than target.
Compare sizes for how far each is from its target.
1Callout 1: Better than target.
2Callout 2: Worse than target.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
labels = ["no target" if not np.isfinite(x) else ("+" if x > 0 else "") + (fmt_kpi(x, "percent", 1) if MODE == "percent" else fmt_kpi(x, STYLE)) for x in v]
colours = [MUTED if tone_of(x, GOOD) == 0 else (PASS if tone_of(x, GOOD) > 0 else FAIL) for x in v.fillna(0)]
fig = go.Figure(go.Bar(y=rows["group"], x=v.fillna(0), orientation="h", marker_color=colours, text=labels, textposition="outside", cliponaxis=False))
fig.add_vline(x=0, line_color=MUTED)
fig.update_layout(width=720, height=120 + 50 * len(rows), xaxis=dict(range=[-m, m], tickformat=".0%" if MODE == "percent" else None,
title="Actual vs target (%)" if MODE == "percent" else "Actual − target"), yaxis=dict(autorange="reversed"), showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads target-variance-demo.csv · app theme from the optional codesplash helper
# Variance to target — Codesplash Chart Lab (recipe "target-variance")# controls: agg=sum, mode=percent, sort=variance, good=up, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("target-variance-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
target_rows <- function(d, group, value, target, how, fixed, levels) {
# per group: the aggregate of the values and of the targets (or the fixed target)
out <- do.call(rbind, lapply(levels, function(lv) {
g <- d[as.character(d[[group]]) %in% lv, , drop = FALSE]
t <- if (is.null(target)) (if (is.null(fixed)) NA_real_ else fixed) else agg(g[[target]], how)
data.frame(group = lv, value = agg(g[[value]], how), target = t, n = nrow(g))
}))
out$variance <- out$value - out$target
out$variance_pct <- ifelse(is.finite(out$target) & out$target != 0, out$variance / abs(out$target), NA_real_)
out$progress <- ifelse(is.finite(out$target) & out$target != 0, out$value / out$target, NA_real_)
out
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; STYLE <- "compact"; GOOD <- "up"
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
rows <- target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df[["region"]], 12))
MODE <- "percent"; SORT <- "variance"
key <- if (MODE == "percent") "variance_pct" else "variance"
if (SORT != "order") rows <- rows[order(-rows[[if (SORT == "value") "value" else key]], na.last = TRUE), ]
rows$v <- rows[[key]]
m <- max(c(abs(rows$v), if (MODE == "percent") 0.05 else 1), na.rm = TRUE) * 1.25
rows$group <- factor(rows$group, levels = rev(rows$group))
rows$fill <- vapply(rows$v, function(x) if (is.na(x)) muted else switch(as.character(tone_of(x, GOOD)), "1" = pass, "-1" = fail, muted), character(1))
rows$label <- vapply(rows$v, function(x) if (is.na(x)) "no target" else paste0(if (x > 0) "+" else "", if (MODE == "percent") fmt_kpi(x, "percent", 1) else fmt_kpi(x, STYLE)), character(1))
p <- ggplot(rows, aes(ifelse(is.na(v), 0, v), group)) +
geom_col(aes(fill = I(fill)), width = 0.7) +
geom_vline(xintercept = 0, colour = muted) +
geom_text(aes(label = label, hjust = ifelse(is.na(v) | v >= 0, -0.1, 1.1)), size = 3.2, colour = fg) +
scale_x_continuous(limits = c(-m, m), labels = if (MODE == "percent") function(x) paste0(round(x * 100), "%") else waiver()) +
labs(x = if (MODE == "percent") "Actual vs target (%)" else "Actual \u2212 target", y = NULL) +
theme_cs
print(p)
Needs ggplot2 · reads target-variance-demo.csv · app theme from the optional codesplashr helper
-- Variance to target — Codesplash Chart Lab (recipe "target-variance")-- controls: agg=sum, mode=percent, sort=variance, good=up, format=compact-- per group: sum of the value and the target
WITH g AS (
SELECT "region" AS "group", sum("revenue") AS actual, sum("target") AS target, count(*) AS n
FROM read_csv('target-variance-demo.csv')
WHERE "region" IS NOT NULL
GROUP BY 1
)
SELECT "group", actual, target, actual - target AS variance, (actual - target) / nullif(abs(target), 0) AS variance_pct, n
FROM g
ORDER BY n DESC, "group"
Sparklines share no scale, so use them for each group's own shape.
1Callout 1: The group's latest value.
2Callout 2: Its change.
3Callout 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 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)]
from plotly.subplots import make_subplots
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 = make_subplots(rows=nrow, cols=ncol, vertical_spacing=0.25 / nrow, horizontal_spacing=0.06)
for i, (name, k) in enumerate(tiles):
r, c = i // ncol + 1, i % ncol + 1
s = k["series"]
if s is not None and len(s) >= 2:
fig.add_scatter(x=list(range(len(s))), y=s["v"], mode="lines", line=dict(color=COL, width=2), fill="tozeroy",
fillcolor="rgba(41,113,198,0.12)", hovertext=[period_name(t, GRAIN) for t in s["t"]], hoverinfo="text+y", row=r, col=c)
lo, hi = s["v"].min(), s["v"].max()
fig.update_yaxes(range=[lo - (hi - lo) * 0.05, hi + (hi - lo) * 1.6], row=r, col=c) # room for the text above the line
delta = fmt_delta(k["delta"], k["pct"], STYLE)
colour = {1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)]
xref = "x domain" if i == 0 else f"x{i + 1} domain"
yref = "y domain" if i == 0 else f"y{i + 1} domain"
fig.add_annotation(text=f"<span style='color:{MUTED}'>{name}</span><br><b style='font-size:20px'>{fmt_kpi(k['value'], STYLE)}</b><br><span style='color:{colour}'>{delta}</span>",
x=0, y=1, xref=xref, yref=yref, showarrow=False, xanchor="left", yanchor="top", align="left")
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.update_layout(width=280 * ncol, height=220 * nrow, showlegend=False, margin=dict(l=20, r=20, t=20, b=20))
fig.show()
Needs pandas, numpy, plotly · reads kpi-grid-demo.csv · app theme from the optional codesplash helper
# 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
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("kpi-grid-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; GRAIN <- "month"; POINTS <- 12; COMPARE <- TRUE; GOOD <- "up"; STYLE <- "compact"
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
lv <- freq_levels(df[["region"]], 12)
tiles <- lapply(stats::setNames(nm = lv), function(l) kpi(df[as.character(df[["region"]]) %in% l, , drop = FALSE], "date", "revenue", "target", GRAIN, AGG, POINTS, COMPARE))
spark <- do.call(rbind, lapply(names(tiles), function(n) {
s <- tiles[[n]]$series
if (is.null(s) || nrow(s) < 2) return(NULL)
data.frame(group = n, i = seq_len(nrow(s)) - 1, v = (s$v - min(s$v)) / max(diff(range(s$v)), 1e-12)) # scaled per tile
}))
heads <- data.frame(group = names(tiles),
value = vapply(tiles, function(k) fmt_kpi(k$value, STYLE), character(1)),
delta = vapply(tiles, function(k) fmt_delta(k$delta, k$pct, STYLE), character(1)),
tone = vapply(tiles, function(k) c("1" = pass, "-1" = fail, "0" = muted)[[as.character(tone_of(k$delta, GOOD))]], character(1)))
spark$group <- factor(spark$group, levels = names(tiles))
heads$group <- factor(heads$group, levels = names(tiles))
p <- ggplot(spark, aes(i, v)) +
geom_ribbon(aes(ymin = 0, ymax = v), fill = col, alpha = 0.15) +
geom_line(colour = col, linewidth = 0.8) +
geom_text(data = heads, aes(x = -Inf, y = 2.15, label = value), hjust = -0.05, size = 6, fontface = "bold", colour = fg) +
geom_text(data = heads, aes(x = -Inf, y = 1.45, label = delta, colour = I(tone)), hjust = -0.05, size = 3) +
facet_wrap(~group, ncol = ceiling(length(tiles) / ceiling(length(tiles) / 3))) +
scale_y_continuous(limits = c(0, 2.6)) +
labs(x = NULL, y = NULL, caption = paste(AGG, "per", GRAIN, "· latest period vs the previous one")) +
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + theme(strip.text = element_text(hjust = 0, colour = muted))
print(p)
Needs ggplot2 · reads kpi-grid-demo.csv · app theme from the optional codesplashr helper
-- 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-- per group and month: sum, the previous period and the change (UTC periods)
WITH p AS (
SELECT "region" AS "group", date_trunc('month', "date") AS period, sum("revenue") AS value
FROM read_csv('kpi-grid-demo.csv')
WHERE "date" IS NOT NULL AND "region" IS NOT NULL
GROUP BY 1, 2
)
SELECT cur."group", cur.period, cur.value, prev.value AS previous, (cur.value - prev.value) / nullif(abs(prev.value), 0) AS pct_change,
cur.period = max(cur.period) OVER (PARTITION BY cur."group") AS is_latest
FROM p AS cur
LEFT JOIN p AS prev ON prev."group" = cur."group" AND prev.period = cur.period - INTERVAL 1 MONTH
ORDER BY cur."group", cur.period
Read each row across: shape, latest, change, range.
Sort by the column you care about.
Compare change with the row's minimum and maximum to judge whether it's unusual.
1Callout 1: This group's recent shape.
2Callout 2: The change against the previous period.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)]
from plotly.subplots import make_subplots
n = len(tiles)
fig = make_subplots(rows=n, cols=1, vertical_spacing=0.02)
for i, (name, k) in enumerate(tiles, start=1):
s = k["series"]
if s is not None and len(s) >= 2:
fig.add_scatter(x=list(range(len(s))), y=s["v"], mode="lines", line=dict(color=COL, width=1.6), name=name,
hovertext=[period_name(t, GRAIN) for t in s["t"]], hoverinfo="text+y", row=i, col=1)
vals = s["v"].dropna() if s is not None else pd.Series(dtype=float)
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)
colour = {1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)]
yref = "y domain" if i == 1 else f"y{i} domain"
for x, text, anchor in [(-0.02, name, "right"), (1.18, f"<b>{fmt_kpi(k['value'], STYLE)}</b>", "right"),
(1.36, f"<span style='color:{colour}'>{change}</span>", "right"), (1.52, fmt_kpi(vals.min() if len(vals) else None, STYLE), "right"),
(1.68, fmt_kpi(vals.max() if len(vals) else None, STYLE), "right")]:
fig.add_annotation(text=text, x=x, y=0.5, xref="paper", yref=yref, showarrow=False, xanchor=anchor)
for x, text in [(1.18, "Latest"), (1.36, "Change"), (1.52, "Min"), (1.68, "Max")]:
fig.add_annotation(text=f"<b>{text}</b>", x=x, y=1.02, xref="paper", yref="paper", showarrow=False, xanchor="right", yanchor="bottom", font=dict(color=MUTED))
fig.update_xaxes(visible=False)
fig.update_yaxes(visible=False)
fig.update_layout(width=900, height=60 + 45 * n, showlegend=False, margin=dict(l=120, r=380, t=40, b=10))
fig.show()
Needs pandas, numpy, plotly · reads sparkline-table-demo.csv · app theme from the optional codesplash helper
# Sparkline table — Codesplash Chart Lab (recipe "sparkline-table")# controls: agg=sum, grain=month, points=24, good=up, format=compact
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("sparkline-table-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, 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 (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; GRAIN <- "month"; POINTS <- 24; COMPARE <- TRUE; GOOD <- "up"; STYLE <- "compact"
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
lv <- freq_levels(df[["region"]], 12)
tiles <- lapply(stats::setNames(nm = lv), function(l) kpi(df[as.character(df[["region"]]) %in% l, , drop = FALSE], "date", "revenue", NULL, GRAIN, AGG, POINTS, COMPARE))
n <- length(tiles)
rows <- data.frame(group = names(tiles), row = rev(seq_len(n)))
spark <- do.call(rbind, lapply(seq_len(n), function(j) {
s <- tiles[[j]]$series
if (is.null(s) || nrow(s) < 2) return(NULL)
r <- diff(range(s$v, na.rm = TRUE))
data.frame(row = rows$row[j], x = (seq_len(nrow(s)) - 1) / (nrow(s) - 1), y = rows$row[j] - 0.35 + 0.7 * (s$v - min(s$v, na.rm = TRUE)) / max(r, 1e-12))
}))
cells <- do.call(rbind, lapply(seq_len(n), function(j) {
k <- tiles[[j]]
v <- if (is.null(k$series)) numeric() else k$series$v[is.finite(k$series$v)]
change <- if (is.null(k$pct)) "\u2014" else paste0(if (k$pct > 0 && !kpi_is_zero(fmt_kpi(k$pct, "percent", 1))) "+" else "", fmt_kpi(k$pct, "percent", 1))
tone <- c("1" = pass, "-1" = fail, "0" = muted)[[as.character(tone_of(k$delta, GOOD))]]
data.frame(row = rows$row[j], x = c(1.35, 1.65, 1.9, 2.15), hjust = 1,
label = c(fmt_kpi(k$value, STYLE), change, if (length(v)) fmt_kpi(min(v), STYLE) else "\u2014", if (length(v)) fmt_kpi(max(v), STYLE) else "\u2014"),
colour = c(fg, tone, muted, muted), face = c("bold", "plain", "plain", "plain"))
}))
heads <- data.frame(x = c(0, 1.35, 1.65, 1.9, 2.15), hjust = c(0, 1, 1, 1, 1), label = c(paste(AGG, "per", GRAIN), "Latest", "Change", "Min", "Max"))
p <- ggplot() +
geom_line(data = spark, aes(x, y, group = row), colour = col, linewidth = 0.7) +
geom_text(data = cells, aes(x, row, label = label, colour = I(colour), fontface = face, hjust = hjust), size = 3.3) +
geom_text(data = heads, aes(x, n + 0.75, label = label, hjust = hjust), size = 3, fontface = "bold", colour = muted) +
scale_y_continuous(breaks = rows$row, labels = rows$group, limits = c(0.5, n + 0.9)) +
scale_x_continuous(limits = c(-0.02, 2.2)) +
labs(x = NULL, y = NULL) +
theme_cs + theme(axis.text.x = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)
Needs ggplot2 · reads sparkline-table-demo.csv · app theme from the optional codesplashr helper
-- Sparkline table — Codesplash Chart Lab (recipe "sparkline-table")-- controls: agg=sum, grain=month, points=24, good=up, format=compact-- per group and month: sum, the previous period and the change (UTC periods)
WITH p AS (
SELECT "region" AS "group", date_trunc('month', "date") AS period, sum("revenue") AS value
FROM read_csv('sparkline-table-demo.csv')
WHERE "date" IS NOT NULL AND "region" IS NOT NULL
GROUP BY 1, 2
)
SELECT cur."group", cur.period, cur.value, prev.value AS previous, (cur.value - prev.value) / nullif(abs(prev.value), 0) AS pct_change,
cur.period = max(cur.period) OVER (PARTITION BY cur."group") AS is_latest
FROM p AS cur
LEFT JOIN p AS prev ON prev."group" = cur."group" AND prev.period = cur.period - INTERVAL 1 MONTH
ORDER BY cur."group", cur.period
Needs duckdb · reads sparkline-table-demo.csv
Causal inference
Balance and overlap, event studies, regression discontinuity, synthetic control gaps, uplift (Qini) curves and bias contours — the Causal studio's charts.
Read each row as one covariate's imbalance: the standardized difference between groups.
Hollow points are before adjustment, filled ones after.
After adjustment, points should sit inside the threshold band.
1Callout 1: Before adjustment: imbalanced.
2Callout 2: After adjustment: balanced.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
fig = go.Figure()
for j, st in enumerate(stages):
g = d[d["_stage"] == str(st)]
marker = dict(size=9, color="white", line=dict(color="grey", width=1.5)) if j == 0 else dict(size=9, color=PALETTE[(j - 1) % len(PALETTE)])
fig.add_scatter(x=g["shown"], y=g[COV].astype(str), mode="markers", name=st or "SMD", marker=marker)
for t in ([THRESHOLD] if ABSOLUTE else [-THRESHOLD, THRESHOLD]):
fig.add_vline(x=t, line=dict(color=REF, dash="dash", width=1))
fig.update_yaxes(categoryorder="array", categoryarray=order)
fig.update_layout(xaxis_title=("|" + SMD + "|") if ABSOLUTE else SMD, yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads love-plot-demo.csv · app theme from the optional codesplash helper
Read points left of zero: before treatment. They should hover around zero.
Read points right of zero: the effect at each period after.
Check the intervals: do pre-period intervals stay away from zero?
1Callout 1: Pre-period: flat around zero supports parallel trends.
2Callout 2: The reference period.
3Callout 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
# Event study — Codesplash Chart Lab (recipe "event-study")# controls: reference=-1
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
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 = go.Figure()
onset = (REFERENCE if REFERENCE is not None else -1) + 0.5
fig.add_vrect(x0=df[T].min() - 0.6, x1=onset, fillcolor="grey", opacity=0.06, line_width=0)
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.add_vline(x=onset, line=dict(color=REF, dash="dash", width=1))
for i, (name, d) in enumerate(series):
off = (i - (len(series) - 1) / 2) * 0.16 if len(series) > 1 else 0
fig.add_scatter(x=d[T] + off, y=d[EST], mode="lines+markers", name=name or EST, marker_color=PALETTE[i % len(PALETTE)],
error_y=dict(type="data", symmetric=False, array=d[HI] - d[EST], arrayminus=d[EST] - d[LO]))
fig.update_layout(xaxis_title=T, yaxis_title=EST)
fig.show()
Needs pandas, numpy, plotly · reads event-study-demo.csv · app theme from the optional codesplash helper
# Event study — Codesplash Chart Lab (recipe "event-study")# controls: reference=-1
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("event-study-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["estimator"]] <- factor(df[["estimator"]], levels = c("TWFE", "Callaway–Sant'Anna"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "years relative to adoption"
est_col <- "effect on employment (pp)"
lo_col <- "ci_low"
hi_col <- "ci_high"
g_col <- "estimator"
reference <- -1
d <- data.frame(t = df[[t_col]], est = df[[est_col]], lo = df[[lo_col]], hi = df[[hi_col]],
g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
onset <- (if (is.null(reference)) -1 else reference) + 0.5
pd <- position_dodge(width = if (is.null(g_col)) 0 else 0.35)
p <- ggplot(d, aes(t, est, colour = g)) +
annotate("rect", xmin = -Inf, xmax = onset, ymin = -Inf, ymax = Inf, fill = "grey50", alpha = 0.06) +
geom_hline(yintercept = 0, colour = "grey50") + geom_vline(xintercept = onset, colour = ref_col, linetype = "dashed") +
geom_line(alpha = 0.5, position = pd) + geom_errorbar(aes(ymin = lo, ymax = hi), width = 0, linewidth = 0.8, position = pd) +
geom_point(size = 2.2, position = pd) +
{ if (!is.null(reference)) annotate("point", x = reference, y = 0, shape = 21, fill = "white", colour = "grey40", size = 2.4) } +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") +
labs(x = t_col, y = est_col, colour = NULL) + theme_cs
print(p)
Needs ggplot2 · reads event-study-demo.csv · app theme from the optional codesplashr helper
Read the dots as binned means on each side of the cutoff.
Look for a jump in the fit lines at the cutoff.
Compare the jump with the bands around it.
1Callout 1: The jump at the cutoff: the estimated effect.
2Callout 2: The local fit below the cutoff.
3Callout 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
# Regression discontinuity — Codesplash Chart Lab (recipe "rdd-plot")# controls: cutoff=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, s in enumerate(sides):
col = PALETTE[i % len(PALETTE)]
b = df[(side == str(s)) & df[X].notna() & df[Y].notna()]
fig.add_scatter(x=b[X], y=b[Y], mode="markers", name=str(s), marker=dict(color=col, size=6))
if FX and FY:
f = df[(side == str(s)) & df[FX].notna()].sort_values(FX)
if FL and FH:
fig.add_scatter(x=f[FX], y=f[FL], mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=f[FX], y=f[FH], mode="lines", line_width=0, fill="tonexty", fillcolor=rgba(col, 0.18), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=f[FX], y=f[FY], mode="lines", line=dict(color=col, width=2), showlegend=False)
fig.add_vline(x=CUTOFF, line=dict(color=REF, dash="dash", width=1))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads rdd-plot-demo.csv · app theme from the optional codesplash helper
# Regression discontinuity — Codesplash Chart Lab (recipe "rdd-plot")# controls: cutoff=0
library(ggplot2)
library(dplyr)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("rdd-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["side"]] <- factor(df[["side"]], levels = c("below (Democrat lost)", "above (Democrat won)"))
df[["kind"]] <- factor(df[["kind"]], levels = c("bin", "fit"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "margin of victory (pp)"
y_col <- "vote share next election (%)"
side_col <- "side"
fx_col <- "fit_x"
fy_col <- "fit_y"
fl_col <- "fit_low"
fh_col <- "fit_high"
kind_col <- "kind"
cutoff <- 0
side <- if (is.null(side_col)) ifelse(dplyr::coalesce(df[[x_col]], if (is.null(fx_col)) 0 else df[[fx_col]]) >= cutoff, "above", "below") else as.character(df[[side_col]])
sides <- if (is.null(side_col)) c("below", "above") else levels_of(df[[side_col]])
bins <- data.frame(x = df[[x_col]], y = df[[y_col]], side = factor(side, levels = sides))
bins <- bins[!is.na(bins$x) & !is.na(bins$y), ]
p <- ggplot(bins, aes(x, y, colour = side)) + geom_point(alpha = 0.8)
if (!is.null(fx_col) && !is.null(fy_col)) {
fits <- data.frame(x = df[[fx_col]], y = df[[fy_col]], side = factor(side, levels = sides),
lo = if (is.null(fl_col)) NA else df[[fl_col]], hi = if (is.null(fh_col)) NA else df[[fh_col]])
fits <- fits[!is.na(fits$x), ]
p <- p + geom_ribbon(data = fits, aes(x, ymin = lo, ymax = hi, fill = side), inherit.aes = FALSE, alpha = 0.18) +
geom_line(data = fits, aes(x, y, colour = side), linewidth = 1)
}
p <- p + geom_vline(xintercept = cutoff, colour = ref_col, linetype = "dashed") +
scale_colour_manual(values = cs_cat) + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = x_col, y = y_col, colour = NULL) + theme_cs
print(p)
Needs ggplot2, dplyr · reads rdd-plot-demo.csv · app theme from the optional codesplashr helper
Read the coloured line as the treated unit's gap from its synthetic control.
Grey lines are placebo units: what gaps happen by chance.
A real effect drops outside the grey after the intervention.
1Callout 1: The intervention.
2Callout 2: The treated unit diverges from the placebos.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for unit, d in df.dropna(subset=[T, GAP]).sort_values(T).groupby(UNIT, observed=True):
treated = bool(d[TR].astype(bool).any())
fig.add_scatter(x=d[T], y=d[GAP], mode="lines", name=f"{unit} (treated)" if treated else str(unit), showlegend=treated,
line=dict(color=PALETTE[0] if treated else "rgba(128,128,128,0.35)", width=2.5 if treated else 1))
fig.add_hline(y=0, line=dict(color="grey", width=1))
if INTERVENTION is not None:
fig.add_vline(x=INTERVENTION, line=dict(color=REF, dash="dash", width=1))
fig.update_layout(xaxis_title=T, yaxis_title=GAP)
fig.show()
Needs pandas, numpy, plotly · reads synth-gap-demo.csv · app theme from the optional codesplash helper
# Synthetic control gaps — Codesplash Chart Lab (recipe "synth-gap")# controls: intervention=0, show_intervention=true, max_pre=5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("synth-gap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["treated"]] <- as.logical(df[["treated"]])
df[["state"]] <- factor(df[["state"]], levels = c("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"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "years since program"
gap_col <- "gap in packs per capita"
unit_col <- "state"
tr_col <- "treated"
intervention <- 0
d <- data.frame(t = df[[t_col]], gap = df[[gap_col]], unit = as.character(df[[unit_col]]), treated = as.logical(df[[tr_col]]))
d <- d[!is.na(d$t) & !is.na(d$gap), ]
p <- ggplot(d, aes(t, gap, group = unit)) +
geom_hline(yintercept = 0, colour = "grey50") +
geom_line(data = d[!d$treated, ], colour = "grey50", alpha = 0.35) +
geom_line(data = d[d$treated, ], colour = cs_cat[1], linewidth = 1.2) +
{ if (!is.null(intervention)) geom_vline(xintercept = intervention, colour = ref_col, linetype = "dashed") } +
labs(x = t_col, y = gap_col) + theme_cs
print(p)
Needs ggplot2 · reads synth-gap-demo.csv · app theme from the optional codesplashr helper
Read x as the share targeted, highest predicted uplift first.
Read y as the incremental gain.
The area between a curve and the diagonal is its Qini: bigger is better.
1Callout 1: This model's gain curve.
2Callout 2: Random targeting.
3Callout 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
# Qini curve — Codesplash Chart Lab (recipe "qini-curve")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
k = 0
for name, d in series:
low = str(name).lower()
ref = "random" in low or any(w in low for w in ("optimal", "perfect", "oracle"))
line = dict(color=REF if "random" in low else "grey", dash="dash" if "random" in low else "dot") if ref else dict(color=PALETTE[k % len(PALETTE)], width=2.5)
fig.add_scatter(x=d[F], y=d[GAIN], mode="lines", name=name or GAIN, line=line)
k += 0 if ref else 1
fig.update_layout(xaxis_title=F, yaxis_title=GAIN)
fig.show()
Needs pandas, numpy, plotly · reads qini-curve-demo.csv · app theme from the optional codesplash helper
Follow the bold zero contour: where the conclusion flips.
Check the labelled points: benchmarks for how strong an unmeasured confounder would be.
1Callout 1: Stronger red: a larger bias.
2Callout 2: Benchmark points.
3Callout 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
# Contour grid — Codesplash Chart Lab (recipe "contour-grid")# controls: levels=10, zero_line=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = 10
grid = df[df[KIND].astype(str) != "point"] if KIND else df
wide = grid.pivot_table(index=Y, columns=X, values=Z)
zmin, zmax = np.nanmin(wide.values), np.nanmax(wide.values)
fig = go.Figure(go.Contour(x=wide.columns, y=wide.index, z=wide.values, ncontours=LEVELS + 2, colorscale="RdBu" if zmin < 0 < zmax else "Blues",
zmid=0 if zmin < 0 < zmax else None, colorbar_title=Z))
if KIND:
pts = df[df[KIND].astype(str) == "point"]
fig.add_scatter(x=pts[X], y=pts[Y], mode="markers+text", text=pts[LABEL] if LABEL else None, textposition="middle right",
marker=dict(symbol="diamond", color="black", size=8), showlegend=False)
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads contour-grid-demo.csv · app theme from the optional codesplash helper
Read the black path as the test statistic at each look.
Crossing the upper boundary means stop for efficacy; the lower, for futility.
Boundaries are wider early because evidence is thin.
1Callout 1: The path crosses the efficacy boundary here.
2Callout 2: Efficacy region.
3Callout 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
# Group-sequential boundaries — Codesplash Chart Lab (recipe "sequential-boundary")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, d) in enumerate(series):
low = str(name).lower()
obs = any(w in low for w in ("observ", "path", "stat"))
fig.add_scatter(x=d[I], y=d[Z], mode="lines+markers", name=name,
line=dict(color="black" if obs else PALETTE[i % len(PALETTE)], dash="dash" if "futil" in low else "solid", width=3 if obs else 2))
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.update_layout(xaxis_title=I, yaxis_title=Z)
fig.show()
Needs pandas, numpy, plotly · reads sequential-boundary-demo.csv · app theme from the optional codesplash helper
Read each curve as where that arm's true rate probably lies.
Read the bars below for the 95% highest-density intervals.
Less overlap means more certainty that the arms differ.
1Callout 1: Arm A's most plausible rates.
2Callout 2: Arm B's.
3Callout 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
# Posterior densities — Codesplash Chart Lab (recipe "posterior-density")# controls: rope_low=0, rope_high=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
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 = go.Figure()
for i, (name, d) in enumerate(series):
fig.add_scatter(x=d[X], y=d[D], mode="lines", fill="tozeroy", name=name or D, line=dict(color=PALETTE[i % len(PALETTE)], width=2))
fig.update_layout(xaxis_title=X, yaxis_title="density")
fig.show()
Needs pandas, numpy, plotly · reads posterior-density-demo.csv · app theme from the optional codesplash helper
A steady fall may be novelty; a steady climb, primacy.
1Callout 1: Early: wide, unstable.
2Callout 2: Settled lift.
3Callout 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
# Cumulative lift — Codesplash Chart Lab (recipe "cumulative-lift")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "linear"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape))
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads cumulative-lift-demo.csv · app theme from the optional codesplash helper
Read the black path as the evidence after each observation.
Crossing the upper line: reject H₀; the lower: accept H₀.
Stop at the first crossing.
1Callout 1: The first crossing: stop here.
2Callout 2: The reject-H₀ boundary.
3Callout 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
# SPRT log-likelihood ratio walk — Codesplash Chart Lab (recipe "sprt-path")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, d) in enumerate(series):
low = str(name).lower()
path = not any(w in low for w in ("reject", "log a", "critical", "upper", "signal", "accept", "log b", "lower"))
fig.add_scatter(x=d[X], y=d[L], mode="lines+markers" if path else "lines", name=name,
line=dict(color="black" if path else PALETTE[i % len(PALETTE)], dash="solid" if path else "dash", width=2.5 if path else 1.5))
fig.add_hline(y=0, line=dict(color="grey", width=1))
fig.update_layout(xaxis_title=X, yaxis_title=L)
fig.show()
Needs pandas, numpy, plotly · reads sprt-path-demo.csv · app theme from the optional codesplash helper
Read blue as the expected loss of shipping that arm, orange as that of keeping control.
Compare with your tolerable loss.
Ship only when the loss from shipping is below that threshold.
1Callout 1: Keeping control here risks a large loss.
2Callout 2: Shipping B risks almost nothing.
3Callout 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
# Expected loss by decision — Codesplash Chart Lab (recipe "expected-loss")# controls: threshold=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
fig = go.Figure()
fig.add_bar(x=d[A].astype(str), y=d[SHIP], name="expected loss if shipped", marker_color=PALETTE[0])
fig.add_bar(x=d[A].astype(str), y=d[KEEP], name="expected loss if not shipped", marker_color=PALETTE[1])
if EPS:
fig.add_hline(y=EPS, line=dict(color="black", dash="dash"), annotation_text=f"ε = {EPS:g}")
fig.update_layout(barmode="group", yaxis_title="expected loss")
fig.show()
Needs pandas, numpy, plotly · reads expected-loss-demo.csv · app theme from the optional codesplash helper
# Expected loss by decision — Codesplash Chart Lab (recipe "expected-loss")# controls: threshold=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("expected-loss-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("B", "C", "D"))
a_col <- "arm"
ship_col <- "loss if shipped"
keep_col <- "loss if not shipped"
eps <- 0
arms <- as.character(df[[a_col]])
d <- rbind(data.frame(arm = arms, loss = df[[ship_col]], choice = "if shipped"),
data.frame(arm = arms, loss = df[[keep_col]], choice = "if not shipped"))
d$arm <- factor(d$arm, levels = unique(arms))
d$choice <- factor(d$choice, levels = c("if shipped", "if not shipped"))
p <- ggplot(d[!is.na(d$loss), ], aes(arm, loss, fill = choice)) +
geom_col(position = position_dodge(width = 0.8), width = 0.75) +
{ if (!is.null(eps) && eps > 0) geom_hline(yintercept = eps, linetype = "dashed") } +
scale_fill_manual(values = cs_cat) + labs(x = NULL, y = "expected loss", fill = "Expected loss") + theme_cs
print(p)
Needs ggplot2 · reads expected-loss-demo.csv · app theme from the optional codesplashr helper
DoE & process control
Control charts with rules, capability against specification limits, effect screening (half-normal, Pareto), main effects and gauge R&R.
Read points in time order against the centre line.
Points beyond the red limits, or runs on one side, signal a special cause.
Read the spread chart first: its limits must be stable before the means chart can be trusted.
1Callout 1: Signals: points beyond the limits or breaking a rule.
2Callout 2: The centre line.
3Callout 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
# Control chart — Codesplash Chart Lab (recipe "control-chart")# controls: zones=false
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
from plotly.subplots import make_subplots
charts = levels_of(df[CHART]) if CHART else [None]
fig = make_subplots(rows=len(charts), cols=1, shared_xaxes=True, subplot_titles=[str(ch) if ch is not None else "" for ch in charts])
for k, ch in enumerate(charts, start=1):
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])
for col, name, colour, dash in ((CL, "centre", "grey", "solid"), (UCL, "UCL", REF, "dash"), (LCL, "LCL", REF, "dash")):
fig.add_scatter(x=d[I], y=d[col], mode="lines", line=dict(color=colour, dash=dash, shape="hvh", width=1), name=name, showlegend=k == 1, row=k, col=1)
fig.add_scatter(x=d[I], y=d[V], mode="lines+markers", line=dict(color=PALETTE[0]), name=V, showlegend=k == 1, row=k, col=1)
fig.add_scatter(x=d.loc[out, I], y=d.loc[out, V], mode="markers", marker=dict(color="#ce5342", size=10), name="signal", showlegend=k == 1, row=k, col=1)
fig.update_xaxes(title_text=I, row=len(charts), col=1)
fig.show()
Needs pandas, numpy, plotly · reads control-chart-demo.csv · app theme from the optional codesplash helper
Read the histogram and curve as the process output.
Compare with the red specification limits.
Read the indices at the top: how comfortably the process fits.
1Callout 1: The lower specification limit.
2Callout 2: The upper specification limit.
3Callout 3: A process centred away from the target.
4Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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)
dens, _ = np.histogram(v, bins=edges, density=True)
fig = go.Figure(go.Bar(x=(edges[:-1] + edges[1:]) / 2, y=dens, width=np.diff(edges), marker_color=PALETTE[0], opacity=0.5, name=V))
xs = np.linspace(edges[0], edges[-1], 200)
fit = (df.dropna(subset=[FX, FD]).sort_values(FX)[FX], df.dropna(subset=[FX, FD]).sort_values(FX)[FD]) if FX and FD else (xs, stats.norm.pdf(xs, v.mean(), v.std(ddof=1)))
fig.add_scatter(x=fit[0], y=fit[1], mode="lines", line=dict(color=PALETTE[0], width=2), name="fit")
for x, name, col in ((LSL, "LSL", "#ce5342"), (USL, "USL", "#ce5342"), (TARGET, "target", "#19966e")):
if x is not None:
fig.add_vline(x=x, line=dict(color=col, dash="dash"), annotation_text=name)
fig.update_layout(xaxis_title=V, yaxis_title="density", bargap=0)
fig.show()
Needs pandas, numpy, plotly, scipy · reads capability-histogram-demo.csv · app theme from the optional codesplash helper
Compare with the margin of error (ME) and the simultaneous margin (SME).
Bars past SME stand out even after correcting for many comparisons.
1Callout 1: The largest effect.
2Callout 2: ME: the margin of error.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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")
fig = go.Figure(go.Bar(x=d["a"], y=d[E].astype(str), orientation="h", marker_color=[PALETTE[1] if ME is None or a > ME else "grey" for a in d["a"]]))
if ME is not None: fig.add_vline(x=ME, line=dict(color=REF, dash="dash"), annotation_text="ME")
if SME is not None: fig.add_vline(x=SME, line=dict(color="#ce5342", dash="dot"), annotation_text="SME")
fig.update_layout(xaxis_title=V, yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads pareto-effects-demo.csv · app theme from the optional codesplash helper
# Pareto chart of effects — Codesplash Chart Lab (recipe "pareto-effects")# controls: margin=6.08, smargin=12.36
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pareto-effects-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["effect"]] <- factor(df[["effect"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
e_col <- "effect"
v_col <- "|effect|"
me <- 6.08; sme <- 12.36
d <- data.frame(e = as.character(df[[e_col]]), a = abs(df[[v_col]]))
d$e <- factor(d$e, levels = d$e[order(d$a)])
d$beyond <- if (is.null(me)) TRUE else d$a > me
p <- ggplot(d, aes(a, e, fill = beyond)) + geom_col() +
{ if (!is.null(me)) geom_vline(xintercept = me, colour = ref_col, linetype = "dashed") } +
{ if (!is.null(sme)) geom_vline(xintercept = sme, colour = "#ce5342", linetype = "dotted") } +
scale_fill_manual(values = c("FALSE" = "grey60", "TRUE" = cs_cat[2]), guide = "none") +
labs(x = v_col, y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads pareto-effects-demo.csv · app theme from the optional codesplashr helper
Read each panel as one factor: mean response at each level.
Steeper lines mean larger main effects.
Compare with the dashed grand mean.
1Callout 1: A steep line: a large effect.
2Callout 2: A shallow line: a small effect.
3Callout 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
# Main effects — Codesplash Chart Lab (recipe "main-effects")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
from plotly.subplots import make_subplots
factors = levels_of(df[F])
fig = make_subplots(rows=1, cols=len(factors), shared_yaxes=True, subplot_titles=[str(f) for f in factors])
grand = df[df[F].astype(str) == str(factors[0])][M].mean()
for k, f in enumerate(factors, start=1):
d = df[df[F].astype(str) == str(f)]
fig.add_scatter(x=d[L].astype(str), y=d[M], mode="lines+markers", line=dict(color=PALETTE[0]), showlegend=False, row=1, col=k)
fig.add_hline(y=grand, line=dict(color=REF, dash="dash", width=1), row=1, col=k)
fig.update_yaxes(title_text=M, row=1, col=1)
fig.show()
Needs pandas, numpy, plotly · reads main-effects-demo.csv · app theme from the optional codesplash helper
Read each cluster as one variance source, by three measures.
Compare gauge R&R with the 10% and 30% guidelines.
Part-to-part should dominate if the gauge is good.
1Callout 1: Gauge R&R: the measurement system.
2Callout 2: Part-to-part: what you want to see.
3Callout 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
# Gauge R&R components — Codesplash Chart Lab (recipe "gage-components")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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"
d["pct"] = d[V] * (100 if d[V].max() <= 1.5 else 1)
fig = px.bar(d, x=S, y="pct", color="_m", barmode="group", color_discrete_sequence=PALETTE, category_orders={S: levels_of(d[S])},
pattern_shape="_m", pattern_shape_sequence=SERIES_HATCHES) # texture per measure, as in the app
fig.update_traces(marker_pattern_fgcolor=HATCH_INK, marker_pattern_fillmode="overlay")
for t in (10, 30):
fig.add_hline(y=t, line=dict(color="grey", dash="dash", width=1))
fig.update_layout(yaxis_title="percent", legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads gage-components-demo.csv · app theme from the optional codesplash helper
# Gauge R&R components — Codesplash Chart Lab (recipe "gage-components")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("gage-components-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["source"]] <- factor(df[["source"]], levels = c("Gauge R&R", "Repeatability", "Reproducibility", "Part-to-part"))
df[["measure"]] <- factor(df[["measure"]], levels = c("contribution", "study_var", "tolerance"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
s_col <- "source"
v_col <- "percent"
m_col <- "measure"
d <- data.frame(s = factor(as.character(df[[s_col]]), levels = levels_of(df[[s_col]])), v = df[[v_col]],
m = if (is.null(m_col)) "contribution" else as.character(df[[m_col]]))
if (max(d$v, na.rm = TRUE) <= 1.5) d$v <- d$v * 100 # fractions → percent
d$m <- factor(d$m, levels = unique(d$m))
p <- ggplot(d, aes(s, v, fill = m)) + geom_col(position = position_dodge(0.85), width = 0.8) +
geom_hline(yintercept = c(10, 30), colour = "grey50", linetype = "dashed") +
scale_fill_manual(values = cs_textures(cs_cat)) + labs(x = NULL, y = "percent", fill = NULL) + theme_cs # texture per measure, as in the app
print(p)
Needs ggplot2 · reads gage-components-demo.csv · app theme from the optional codesplashr helper
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.
Check whether the points follow the line: straight points support that family.
On Weibull paper the slope is the shape: above 1 the failure rate rises, below 1 it falls.
1Callout 1: The earliest failures, where a family most often fails to fit.
2Callout 2: The fitted line: a straight run of points supports this family.
3Callout 3: The latest failures, based on the fewest units.
4Callout 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
# Probability plot — Codesplash Chart Lab (recipe "probability-plot")# controls: paper=weibull
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
fig.add_scatter(x=lx, y=ly, mode="lines", line=dict(color=REF), name="fit")
fig.add_scatter(x=xs, y=ys, mode="markers", marker=dict(color=PALETTE[0], size=6), name="failures", customdata=ff, hovertemplate="%{customdata:.1%}<extra></extra>")
fig.update_layout(title=f"{PAPER} probability plot", xaxis_title=T if PAPER in ("exponential", "normal") else f"log {T}", yaxis_title="Paper y")
fig.show()
Needs pandas, numpy, plotly, scipy · reads probability-plot-demo.csv · app theme from the optional codesplash helper
# Probability plot — Codesplash Chart Lab (recipe "probability-plot")# controls: paper=weibull
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("probability-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "hours"
e_col <- "failed"
fit_col <- NULL
fam_col <- NULL
median_ranks <- function(t, e = NULL) {
# Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie
if (is.null(e)) e <- rep(1, length(t))
keep <- is.finite(t) & t > 0
t <- t[keep]
e <- as.numeric(e[keep]) > 0
o <- order(t, !e)
t <- t[o]
e <- e[o]
n <- length(t)
prev <- 0
ts <- numeric(0)
fs <- numeric(0)
for (i in seq_len(n)) {
if (e[i]) {
prev <- prev + (n + 1 - prev) / (n - i + 2)
ts <- c(ts, t[i])
fs <- c(fs, (prev - 0.3) / (n + 0.4))
}
}
data.frame(t = ts, f = fs)
}
paper_x <- function(paper, t) if (paper %in% c("exponential", "normal")) t else log(t)
paper_y <- function(paper, f) {
switch(paper, weibull = log(-log1p(-f)), exponential = -log1p(-f), loglogistic = log(f / (1 - f)), qnorm(f))
}
paper_label <- c(weibull = "Weibull", lognormal = "Log-normal", exponential = "Exponential", loglogistic = "Log-logistic", normal = "Normal")
data_rows <- function(d) if (is.null(fam_col)) d else d[tolower(as.character(d[[fam_col]])) == "data", , drop = FALSE]
fit_rows <- function(d, paper) {
if (is.null(fam_col) || is.null(fit_col)) return(d[0, , drop = FALSE])
r <- d[as.character(d[[fam_col]]) == paper & !is.na(d[[fit_col]]) & d[[fit_col]] > 0 & d[[fit_col]] < 1, , drop = FALSE]
r[order(r[[t_col]]), , drop = FALSE]
}
PAPER <- "weibull"
s <- data_rows(df)
r <- median_ranks(s[[t_col]], if (is.null(e_col)) NULL else s[[e_col]])
pts <- data.frame(x = paper_x(PAPER, r$t), y = paper_y(PAPER, r$f))
fr <- fit_rows(df, PAPER)
ln <- if (nrow(fr)) data.frame(x = paper_x(PAPER, fr[[t_col]]), y = paper_y(PAPER, fr[[fit_col]])) else {
b <- coef(lm(y ~ x, pts))
data.frame(x = range(pts$x), y = b[1] + b[2] * range(pts$x))
}
probs <- c(0.01, 0.05, 0.1, 0.2, 0.5, 0.8, 0.9, 0.99)
probs <- probs[probs >= min(r$f) * 0.9 & probs <= max(r$f) * 1.1]
p <- ggplot(pts, aes(x, y)) + geom_line(data = ln, colour = ref_col) + geom_point(colour = cs_cat[1], alpha = 0.8) +
scale_y_continuous(breaks = paper_y(PAPER, probs), labels = sprintf("%g%%", probs * 100)) +
labs(x = if (PAPER %in% c("exponential", "normal")) t_col else paste("log", t_col), y = "Cumulative failure probability",
title = sprintf("%s probability plot: plot correlation %.3f", paper_label[[PAPER]], cor(pts$x, pts$y))) + theme_cs
print(p)
Needs ggplot2 · reads probability-plot-demo.csv · app theme from the optional codesplashr helper
Read x as age and y as the share of units still working at that age.
Find your mission time on x and read across for the reliability; a line marks it when one is set.
Compare curves by how far apart they are at the age you care about.
1Callout 1: All units start out working.
2Callout 2: A fitted curve: the share still working at each age.
3Callout 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
# Reliability curve — Codesplash Chart Lab (recipe "reliability-curve")# controls: mission=0, bLife=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, t, y) in enumerate(curves()):
fig.add_scatter(x=t, y=y, mode="lines", name=name, line=dict(color=PALETTE[i % len(PALETTE)]))
fig.update_layout(title="Reliability: share of units still working", xaxis_title=T, yaxis_title="Reliability")
fig.show()
Needs pandas, numpy, plotly · reads reliability-curve-demo.csv · app theme from the optional codesplash helper
# Reliability curve — Codesplash Chart Lab (recipe "reliability-curve")# controls: mission=0, bLife=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("reliability-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["supplier"]] <- factor(df[["supplier"]], levels = c("A", "B"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "hours"
y_col <- "reliability"
g_col <- "supplier"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & !is.na(df[[t_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
t <- d[[t_col]]
v <- d[[y_col]]
keep <- is.finite(v)
data.frame(x = t[keep], y = (function(v) v)(v[keep]), g = factor(g, levels = lv))
}))
p <- ggplot(pd, aes(x, y, colour = g)) + geom_line() + scale_colour_manual(values = cs_cat, name = NULL) +
labs(x = t_col, y = "Reliability", title = "Reliability: share of units still working") + theme_cs
print(p)
Needs ggplot2 · reads reliability-curve-demo.csv · app theme from the optional codesplashr helper
Read x as age and y as the failure rate among units still working at that age.
Falling means early failures, flat means random failures, rising means wear-out.
Compare the families' curves where you have data: they often agree there and diverge beyond it.
1Callout 1: A falling hazard: early failures.
2Callout 2: A flat hazard: an exponential lifetime.
3Callout 3: A rising hazard: wear-out.
4Callout 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
# Hazard curve — Codesplash Chart Lab (recipe "hazard-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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 = go.Figure()
for i, (name, t, y) in enumerate(curves()):
fig.add_scatter(x=t, y=y, mode="lines", name=name, line=dict(color=PALETTE[i % len(PALETTE)], dash=SERIES_DASHES[i % 8])) # dash per stratum, as in the app
fig.update_layout(title="Hazard: failure rate among units still working", xaxis_title=T, yaxis_title="Hazard")
fig.show()
Needs pandas, numpy, plotly · reads hazard-plot-demo.csv · app theme from the optional codesplash helper
# Hazard curve — Codesplash Chart Lab (recipe "hazard-plot")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("hazard-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["shape"]] <- factor(df[["shape"]], levels = c("0.7", "1", "2"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
t_col <- "hours"
y_col <- "hazard"
g_col <- "shape"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & !is.na(df[[t_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
t <- d[[t_col]]
v <- d[[y_col]]
keep <- is.finite(v)
data.frame(x = t[keep], y = (function(v) v)(v[keep]), g = factor(g, levels = lv))
}))
p <- ggplot(pd, aes(x, y, colour = g, linetype = g)) + geom_line() + scale_colour_manual(values = cs_cat, name = NULL) + scale_linetype_manual(values = cs_linetypes, name = NULL) + # dash per stratum, as in the app
labs(x = t_col, y = "Hazard", title = "Hazard: failure rate among units still working") + theme_cs
print(p)
Needs ggplot2 · reads hazard-plot-demo.csv · app theme from the optional codesplashr helper
Read bars top down: the inputs that move the output most.
Read each side as the input's low or high value, with others held at base.
Focus effort on the top bars.
1Callout 1: The most influential input.
2Callout 2: A small swing: this input matters little.
3Callout 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
# Tornado diagram — Codesplash Chart Lab (recipe "tornado")# controls: base=1240
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("tornado-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
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")
base = BASE if BASE is not None else (d[LO].iloc[-1] + d[HI].iloc[-1]) / 2
fig = go.Figure()
fig.add_bar(y=d[INPUT].astype(str), x=d[LO] - base, base=base, orientation="h", name="input at its low value", marker_color=PALETTE[1])
fig.add_bar(y=d[INPUT].astype(str), x=d[HI] - base, base=base, orientation="h", name="input at its high value", marker_color=PALETTE[0])
fig.add_vline(x=base, line=dict(color="black", width=1.5))
fig.update_layout(barmode="overlay", xaxis_title="output", yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads tornado-demo.csv · app theme from the optional codesplash helper
# Tornado diagram — Codesplash Chart Lab (recipe "tornado")# controls: base=1240
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("tornado-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["input"]] <- factor(df[["input"]])
input_col <- "input"
lo_col <- "NPV ($k) at low"
hi_col <- "NPV ($k) at high"
base <- 1240
d <- data.frame(input = as.character(df[[input_col]]), lo = df[[lo_col]], hi = df[[hi_col]])
d <- d[stats::complete.cases(d), ]
d$input <- factor(d$input, levels = d$input[order(abs(d$hi - d$lo))]) # widest on top
if (is.null(base)) base <- with(d[which.max(abs(d$hi - d$lo)), ], (lo + hi) / 2)
p <- ggplot(d) +
geom_segment(aes(x = base, xend = lo, y = input, yend = input, colour = "input at its low value"), linewidth = 7) +
geom_segment(aes(x = base, xend = hi, y = input, yend = input, colour = "input at its high value"), linewidth = 7) +
geom_vline(xintercept = base) + scale_colour_manual(values = c(cs_cat[2], cs_cat[1]), name = NULL) +
labs(x = "output", y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads tornado-demo.csv · app theme from the optional codesplashr helper
Read each line as the output as one input moves from base.
Steeper means more sensitive.
All lines cross at the base case.
1Callout 1: A steep line: a sensitive input.
2Callout 2: The base case.
3Callout 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
# Spider plot — Codesplash Chart Lab (recipe "spider")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, d) in enumerate(series):
fig.add_scatter(x=d[CH], y=d[K], mode="lines+markers", name=name, line=dict(color=PALETTE[i % len(PALETTE)]))
fig.update_layout(xaxis_title=CH, yaxis_title=K)
fig.show()
Needs pandas, numpy, plotly · reads spider-demo.csv · app theme from the optional codesplash helper
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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if V:
v = df[V].dropna()
fig.add_histogram(x=v, histnorm="probability", nbinsx=max(30, min(80, 2 * int(np.ceil(np.log2(len(v)) + 1)))), marker_color=PALETTE[0], opacity=0.6, name=V)
pv = np.percentile(v, PCTS)
else:
b = df.dropna(subset=[BL, BH, N]).sort_values(BL)
fig.add_bar(x=(b[BL] + b[BH]) / 2, y=b[N] / b[N].sum(), width=b[BH] - b[BL], marker_color=PALETTE[0], opacity=0.6, name="share")
cum = np.r_[0, np.cumsum(b[N] / b[N].sum())]
pv = np.interp(np.array(PCTS) / 100, cum, np.r_[b[BL].to_numpy(), b[BH].iloc[-1]])
for p, x in zip(PCTS, pv):
fig.add_vline(x=x, line=dict(color=PALETTE[2], dash="dash", width=1), annotation_text=f"P{p}")
if TARGET is not None:
fig.add_vline(x=TARGET, line=dict(color="#ce5342", width=2), annotation_text="target")
fig.update_layout(xaxis_title=V or "value", yaxis_title="share of draws", bargap=0)
fig.show()
Needs pandas, numpy, plotly · reads mc-distribution-demo.csv · app theme from the optional codesplash helper
# Monte Carlo distribution — Codesplash Chart Lab (recipe "mc-distribution")# controls: target=0, percentiles=5-50-95
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mc-distribution-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
v_col <- "profit ($k)"
bl_col <- NULL
bh_col <- NULL
n_col <- NULL
target <- 0; pcts <- c(5, 50, 95)
if (!is.null(v_col)) {
v <- df[[v_col]][!is.na(df[[v_col]])]
k <- max(30, min(80, 2 * ceiling(log2(length(v)) + 1)))
pv <- stats::quantile(v, pcts / 100, type = 7, names = FALSE)
p <- ggplot(data.frame(v = v), aes(v)) + geom_histogram(aes(y = after_stat(count / sum(count))), bins = k, fill = cs_cat[1], alpha = 0.55)
} else {
b <- data.frame(lo = df[[bl_col]], hi = df[[bh_col]], n = df[[n_col]]); b <- b[order(b$lo), ]
b$share <- b$n / sum(b$n)
pv <- stats::approx(c(0, cumsum(b$share)), c(b$lo, utils::tail(b$hi, 1)), xout = pcts / 100)$y
p <- ggplot(b) + geom_rect(aes(xmin = lo, xmax = hi, ymin = 0, ymax = share), fill = cs_cat[1], alpha = 0.55)
}
p <- p + geom_vline(xintercept = pv, colour = cs_cat[3], linetype = "dashed") +
annotate("text", x = pv, y = Inf, label = paste0("P", pcts), vjust = 1.5, hjust = -0.1, size = 3, colour = cs_cat[3]) +
{ if (!is.null(target)) geom_vline(xintercept = target, colour = "#ce5342", linewidth = 0.8) } +
labs(x = if (is.null(v_col)) "value" else v_col, y = "share of draws") + theme_cs
print(p)
Needs ggplot2 · reads mc-distribution-demo.csv · app theme from the optional codesplashr helper
Read each line as how much reward a policy loses compared with always picking the best arm.
A curve that flattens has stopped losing: it found the best arm.
Read the band for replication spread.
1Callout 1: Thompson sampling flattens early.
2Callout 2: A fixed split keeps losing at the same rate.
3Callout 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
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "linear"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape, dash=SERIES_DASHES[i % 8])) # dash per group, as in the app
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads regret-bands-demo.csv · app theme from the optional codesplash helper
# Cumulative regret — Codesplash Chart Lab (recipe "regret-bands")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("regret-bands-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["policy"]] <- factor(df[["policy"]])
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "round"
y_col <- "cumulative regret"
lo_col <- "p10"
hi_col <- "p90"
g_col <- "policy"
d <- data.frame(x = df[[x_col]], y = df[[y_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d <- d[!is.na(d$x) & !is.na(d$y), ]
d <- d[order(d$g, d$x), ]
p <- ggplot(d, aes(x, y, colour = g, fill = g)) +
{ if (!all(is.na(d$lo))) geom_ribbon(aes(ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } + geom_line(aes(linetype = g), linewidth = 0.9) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, guide = if (is.null(g_col)) "none" else "legend") + # dash per group, as in the app
labs(x = x_col, y = y_col, colour = NULL, linetype = NULL) + theme_cs
print(p)
Needs ggplot2 · reads regret-bands-demo.csv · app theme from the optional codesplashr helper
Read each panel as one policy's share of plays per arm over rounds.
A policy that shifts quickly to one arm is exploiting early.
Compare how soon the best arm's band takes over.
1Callout 1: The best arm's share grows.
2Callout 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
# Arm shares — Codesplash Chart Lab (recipe "arm-share")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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"
d = df.dropna(subset=[T, S, ARM]).sort_values(T)
fig = px.area(d, x=T, y=S, color=ARM, facet_col=POL, color_discrete_sequence=PALETTE, groupnorm="fraction",
pattern_shape=ARM, pattern_shape_sequence=SERIES_HATCHES, # texture per arm, as in the app
category_orders={ARM: levels_of(d[ARM])} | ({POL: levels_of(d[POL])} if POL else {}))
fig.update_traces(fillpattern_fgcolor=HATCH_INK, fillpattern_fillmode="overlay")
fig.update_layout(yaxis_title="share of plays", legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads arm-share-demo.csv · app theme from the optional codesplash helper
# Arm shares — Codesplash Chart Lab (recipe "arm-share")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("arm-share-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("A (4.0%)", "B (4.6%)", "C (5.1%)", "D (6.0%)"))
df[["policy"]] <- factor(df[["policy"]], levels = c("UCB1", "Thompson sampling"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
t_col <- "round"
s_col <- "share of plays"
arm_col <- "arm"
pol_col <- "policy"
d <- data.frame(t = df[[t_col]], s = df[[s_col]], arm = factor(as.character(df[[arm_col]]), levels = levels_of(df[[arm_col]])),
pol = if (is.null(pol_col)) "" else factor(as.character(df[[pol_col]]), levels = levels_of(df[[pol_col]])))
p <- ggplot(d, aes(t, s, fill = arm)) + geom_area(position = "fill", alpha = 0.85) + facet_wrap(~pol) +
scale_fill_manual(values = cs_textures(cs_cat)) + scale_y_continuous(labels = function(v) paste0(round(v * 100), "%")) + # texture per arm, as in the app
labs(x = t_col, y = "share of plays", fill = NULL) + theme_cs
print(p)
Needs ggplot2 · reads arm-share-demo.csv · app theme from the optional codesplashr helper
Read one panel per metric with each group's value and interval.
Check the largest gap in the title.
Use the tolerance band: is a difference larger than you can accept?
1Callout 1: The largest gap on this metric.
2Callout 2: One group's value.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"])
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"
d = df.dropna(subset=[G, V]).copy()
kw = dict(error_x=d[HI] - d[V], error_x_minus=d[V] - d[LO]) if LO and HI else {}
fig = px.scatter(d, x=V, y=G, color=G, symbol=G, symbol_sequence=SERIES_MARKERS, facet_col=M, color_discrete_sequence=PALETTE, category_orders={G: levels_of(d[G]), M: levels_of(d[M])}, **kw) # marker shape per group, as in the app
fig.update_traces(marker_size=10, showlegend=False)
fig.update_xaxes(matches=None)
fig.show()
Needs pandas, numpy, plotly · reads group-metrics-demo.csv · app theme from the optional codesplash helper
# Metrics by group (fairness) — Codesplash Chart Lab (recipe "group-metrics")# controls: reference=0, band_low=0, band_high=0
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("group-metrics-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["group"]] <- factor(df[["group"]], levels = c("Group A", "Group B", "Group C", "Group D"))
df[["metric"]] <- factor(df[["metric"]], levels = c("selection rate", "true positive rate", "false positive rate"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
g_col <- "group"
m_col <- "metric"
v_col <- "value"
lo_col <- "ci_low"
hi_col <- "ci_high"
reference <- 0
d <- data.frame(g = factor(as.character(df[[g_col]]), levels = rev(levels_of(df[[g_col]]))), m = factor(as.character(df[[m_col]]), levels = levels_of(df[[m_col]])), v = df[[v_col]],
lo = if (is.null(lo_col)) NA_real_ else df[[lo_col]], hi = if (is.null(hi_col)) NA_real_ else df[[hi_col]])
p <- ggplot(d, aes(v, g, colour = g, shape = g)) + # marker shape per group, as in the app
{ if (!is.null(reference)) geom_vline(xintercept = reference, colour = ref_col, linetype = "dashed") } +
geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0, linewidth = 0.8, na.rm = TRUE) + geom_point(size = 2.6) +
facet_wrap(~m, scales = "free_x") + scale_colour_manual(values = rev(cs_cat[seq_len(nlevels(d$g))]), guide = "none") +
scale_shape_manual(values = rev(rep_len(cs_shapes, nlevels(d$g))), guide = "none") +
labs(x = v_col, y = NULL) + theme_cs
print(p)
Needs ggplot2 · reads group-metrics-demo.csv · app theme from the optional codesplashr helper
Advanced models
Specification curves, random effects (caterpillar), recurrent events, item response curves, parallel analysis, decision curves, prediction intervals and drift.
Read the top panel as estimates across every specification, ranked by size.
Read the dots below for which choices each specification uses.
Look for choices that line up at one end: they drive the result.
1Callout 1: Estimates sorted by size.
2Callout 2: The choices behind each specification.
3Callout 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
# Specification curve — Codesplash Chart Lab (recipe "spec-curve")# controls: null=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
from plotly.subplots import make_subplots
specs = df.drop_duplicates(SPEC).sort_values(SPEC)
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_heights=[0.6, 0.4])
kw = dict(error_y=dict(type="data", symmetric=False, array=specs[HI] - specs[E], arrayminus=specs[E] - specs[LO], thickness=1)) if LO and HI else {}
fig.add_scatter(x=specs[SPEC], y=specs[E], mode="markers", marker=dict(color=np.where(specs[SIG].astype(bool), PALETTE[0], "grey"), size=6), showlegend=False, row=1, col=1, **kw)
lab = df[DIM].astype(str) + ": " + df[OPT].astype(str)
fig.add_scatter(x=df[SPEC], y=lab, mode="markers", marker=dict(color="black", size=4), showlegend=False, row=2, col=1)
fig.update_yaxes(title_text=E, row=1, col=1)
fig.show()
Needs pandas, numpy, plotly · reads spec-curve-demo.csv · app theme from the optional codesplash helper
Read each row as one group's estimated deviation from average.
Rows are sorted by size.
Intervals that stay away from zero mark groups that differ from average.
1Callout 1: A group above average.
2Callout 2: A group below average.
3Callout 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
# Caterpillar plot — Codesplash Chart Lab (recipe "caterpillar")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])
G = "subject"
E = "random effect (ms)"
LO = "ci_low"
HI = "ci_high"
TERM = "term"
d = df.dropna(subset=[G, E]).sort_values(E)
kw = dict(error_x=d[HI] - d[E], error_x_minus=d[E] - d[LO]) if LO and HI else {}
fig = px.scatter(d, x=E, y=G, facet_col=TERM, color_discrete_sequence=PALETTE, **kw)
fig.update_yaxes(matches=None, showticklabels=True)
fig.add_vline(x=0, line=dict(color="grey", width=1))
fig.show()
Needs pandas, numpy, plotly · reads caterpillar-demo.csv · app theme from the optional codesplash helper
Read the curve as the mean number of events per subject by time.
Compare the curves between groups.
A straight line suggests a constant event rate; bending up, an increasing one.
1Callout 1: Placebo accumulates more events.
2Callout 2: Treatment accumulates fewer.
3Callout 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
# Mean cumulative function — Codesplash Chart Lab (recipe "mcf-plot")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)))
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
shape = "hv"
if LO and HI:
fig.add_scatter(x=d[X], y=d[LO], mode="lines", line=dict(width=0, shape=shape), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[HI], mode="lines", line=dict(width=0, shape=shape), fill="tonexty", fillcolor=rgba(col, 0.15), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[X], y=d[Y], mode="lines", name=name or Y, line=dict(color=col, width=2, shape=shape))
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads mcf-plot-demo.csv · app theme from the optional codesplash helper
# Mean cumulative function — Codesplash Chart Lab (recipe "mcf-plot")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mcf-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("placebo", "treatment"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "months"
y_col <- "mean recurrences per patient"
lo_col <- "ci_low"
hi_col <- "ci_high"
g_col <- "arm"
d <- data.frame(x = df[[x_col]], y = df[[y_col]], g = if (is.null(g_col)) "" else factor(as.character(df[[g_col]]), levels = levels_of(df[[g_col]])))
d$lo <- if (is.null(lo_col)) NA_real_ else df[[lo_col]]
d$hi <- if (is.null(hi_col)) NA_real_ else df[[hi_col]]
d <- d[!is.na(d$x) & !is.na(d$y), ]
d <- d[order(d$g, d$x), ]
p <- ggplot(d, aes(x, y, colour = g, fill = g)) +
{ if (!all(is.na(d$lo))) geom_rect(data = transform(d, xend = stats::ave(x, g, FUN = function(v) c(v[-1], v[length(v)]))), aes(xmin = x, xmax = xend, ymin = lo, ymax = hi), colour = NA, alpha = 0.15) } + geom_step(linewidth = 0.9) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = x_col, y = y_col, colour = NULL) + theme_cs
print(p)
Needs ggplot2 · reads mcf-plot-demo.csv · app theme from the optional codesplashr helper
Read each curve as the probability of a correct response at each ability.
Curves further right are harder items.
Steeper curves separate people better.
1Callout 1: An easier item.
2Callout 2: A harder item.
3Callout 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
# Item characteristic curves — Codesplash Chart Lab (recipe "item-curves")# controls: kind=icc
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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
d = df.dropna(subset=[TH, P]).sort_values(TH)
fig = px.line(d, x=TH, y=P, color=CAT or ITEM, line_dash=CAT or ITEM, line_dash_sequence=SERIES_DASHES, facet_col=ITEM if CAT else None, color_discrete_sequence=PALETTE) # dash per curve, as in the app
fig.update_layout(yaxis_title="P(response)", legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads item-curves-demo.csv · app theme from the optional codesplash helper
# Item characteristic curves — Codesplash Chart Lab (recipe "item-curves")# controls: kind=icc
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("item-curves-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["item"]] <- factor(df[["item"]], levels = c("Q1 (easy)", "Q2", "Q3", "Q4", "Q5 (hard)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
th_col <- "ability θ"
p_col <- "P(correct)"
item_col <- "item"
cat_col <- NULL
d <- data.frame(th = df[[th_col]], p = df[[p_col]], item = factor(as.character(df[[item_col]]), levels = levels_of(df[[item_col]])))
d$curve <- if (is.null(cat_col)) d$item else factor(as.character(df[[cat_col]]), levels = levels_of(df[[cat_col]]))
p <- ggplot(d, aes(th, p, colour = curve, linetype = curve, group = interaction(item, curve))) + geom_line(linewidth = 0.9) + # dash per curve, as in the app
{ if (!is.null(cat_col)) facet_wrap(~item) } + scale_colour_manual(values = rep(cs_cat, 4)) + scale_linetype_manual(values = rep(cs_linetypes, 4)) +
labs(x = th_col, y = "P(response)", colour = NULL, linetype = NULL) + theme_cs
print(p)
Needs ggplot2 · reads item-curves-demo.csv · app theme from the optional codesplashr helper
Read the dashed line as those of random data of the same size.
Keep factors where the solid line stays above the dashed one.
1Callout 1: The first factor stands far above random.
2Callout 2: The last factor above random.
3Callout 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
# Parallel analysis — Codesplash Chart Lab (recipe "parallel-analysis")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = px.line(df.dropna(subset=[F, E]).sort_values(F), x=F, y=E, color=K, markers=True, color_discrete_sequence=[PALETTE[0], "grey"])
fig.add_hline(y=1, line=dict(color="grey", dash="dot", width=1))
fig.update_layout(legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads parallel-analysis-demo.csv · app theme from the optional codesplash helper
Read y as net benefit: true positives minus false positives weighted by the threshold.
A model is useful where it's above treat-all and treat-none.
1Callout 1: The model above the treat-all line.
2Callout 2: Treat none: zero benefit.
3Callout 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
# Decision curve — Codesplash Chart Lab (recipe "decision-curve")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
d = df.dropna(subset=[T, NB]).sort_values(T)
top = d[NB].max()
fig = px.line(d, x=T, y=NB, color=S, color_discrete_sequence=PALETTE, category_orders={S: levels_of(d[S])})
fig.update_yaxes(range=[-0.05 * top, top * 1.08])
fig.update_layout(legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads decision-curve-demo.csv · app theme from the optional codesplash helper
Read x as the promised coverage, y as what was achieved.
On the diagonal: honest intervals.
Below the diagonal: intervals are too narrow.
1Callout 1: On the diagonal: honest intervals.
2Callout 2: Below the diagonal: overconfident.
3Callout 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
# Interval coverage — Codesplash Chart Lab (recipe "interval-coverage")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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"
d = df.dropna(subset=[N, C]).sort_values(N)
fig = px.line(d, x=N, y=C, color=M, markers=True, hover_data=[W] if W else None, color_discrete_sequence=PALETTE,
line_dash=M, line_dash_sequence=SERIES_DASHES, symbol=M, symbol_sequence=SERIES_MARKERS) # dash + marker per method, as in the app
lo = max(0, min(d[N].min(), d[C].min()) - 0.05)
fig.add_shape(type="line", x0=lo, y0=lo, x1=1, y1=1, line=dict(color="grey", dash="dash"))
fig.update_layout(legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads interval-coverage-demo.csv · app theme from the optional codesplash helper
Read each line as one feature's drift statistic over scoring runs.
Compare with the alert threshold.
A sudden rise suggests a data change; a slow rise, gradual drift.
1Callout 1: This feature crossed the alert threshold.
2Callout 2: The threshold.
3Callout 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
# Drift over time — Codesplash Chart Lab (recipe "drift-timeline")# controls: threshold=0.25
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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 = list(d.groupby(F, observed=True)[V].max().sort_values(ascending=False).index[:6])
dash = {f: SERIES_DASHES[top.index(f)] if f in top else "solid" for f in d[F].unique()} # the highlighted features also differ by dash, as in the app
fig = px.line(d, x=T, y=V, color=F, line_dash=F, line_dash_map=dash, color_discrete_sequence=PALETTE)
if THRESHOLD is not None:
fig.add_hline(y=THRESHOLD, line=dict(color="#ce5342", dash="dash"), annotation_text="alert")
fig.update_layout(legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads drift-timeline-demo.csv · app theme from the optional codesplash helper
# Drift over time — Codesplash Chart Lab (recipe "drift-timeline")# controls: threshold=0.25
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("drift-timeline-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["scoring week"]] <- as.POSIXct(df[["scoring week"]], tz = "UTC")
df[["feature"]] <- factor(df[["feature"]])
t_col <- "scoring week"
v_col <- "PSI"
f_col <- "feature"
threshold <- 0.25
d <- data.frame(t = df[[t_col]], v = df[[v_col]], f = as.character(df[[f_col]]))
top <- utils::head(names(sort(tapply(d$v, d$f, max), decreasing = TRUE)), 6)
d$shown <- factor(ifelse(d$f %in% top, d$f, "other"), levels = c(top, "other"))
p <- ggplot(d, aes(t, v, group = f, colour = shown, linetype = shown)) + geom_line(aes(alpha = shown != "other")) + # highlighted features also differ by dash, as in the app
{ if (!is.null(threshold)) list(geom_hline(yintercept = threshold, colour = "#ce5342", linetype = "dashed"), geom_point(data = d[d$v > threshold, ], colour = "#ce5342", size = 1.6)) } +
# values named by level (a partly named vector matched only "other", leaving the top features grey)
scale_alpha_manual(values = c("FALSE" = 0.4, "TRUE" = 1), guide = "none") + scale_colour_manual(values = setNames(c(cs_cat[seq_along(top)], "grey55"), c(top, "other"))) +
scale_linetype_manual(values = setNames(c(cs_linetypes[seq_along(top)], "solid"), c(top, "other"))) +
labs(x = t_col, y = v_col, colour = NULL, linetype = NULL) + theme_cs
print(p)
Needs ggplot2 · reads drift-timeline-demo.csv · app theme from the optional codesplashr helper
Read the line as one metric across monitor runs, oldest on the left.
A dashed line marks a run where a detector signalled; its label says which one, or how many.
Online detectors signal a little after a shift, so look at the runs just before a mark.
1Callout 1: A detector signalled at this run.
2Callout 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
# Change-points on a timeline — Codesplash Chart Lab (recipe "changepoint-timeline")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Scatter(x=d[T], y=d[V], mode="lines+markers", marker=dict(size=5), name=V))
if M:
for _, row in d[d[M].fillna("").astype(str).str.len() > 0].iterrows():
fig.add_shape(type="line", x0=row[T], x1=row[T], y0=0, y1=1, yref="paper", line=dict(color="#c0392b", dash="dash", width=1))
fig.add_annotation(x=row[T], y=1, yref="paper", text=str(row[M]), showarrow=False, font=dict(size=10, color="#c0392b"), xanchor="left")
fig.update_layout(xaxis_title=T, yaxis_title=V, template="plotly_white")
fig.show()
Needs pandas, numpy, plotly · reads changepoint-timeline-demo.csv · app theme from the optional codesplash helper
# Change-points on a timeline — Codesplash Chart Lab (recipe "changepoint-timeline")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("changepoint-timeline-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["run"]] <- as.POSIXct(df[["run"]], tz = "UTC")
df[["detectors"]] <- factor(df[["detectors"]])
T <- "run"
V <- "PSI of tenure"
M <- "detectors"
d <- df[!is.na(df[[T]]) & !is.na(df[[V]]), ]
d <- d[order(d[[T]]), ]
p <- ggplot(d, aes(x = .data[[T]], y = .data[[V]]))
if (!is.null(M)) {
hits <- d[!is.na(d[[M]]) & nzchar(as.character(d[[M]])), ]
p <- p + geom_vline(data = hits, aes(xintercept = .data[[T]]), colour = "#c0392b", linetype = "dashed") +
geom_text(data = hits, aes(x = .data[[T]], label = as.character(.data[[M]])), y = Inf, hjust = -0.05, vjust = 1.5, size = 3, colour = "#c0392b", inherit.aes = FALSE)
}
p <- p + geom_line() + geom_point(size = 1.2) + labs(x = T, y = V) + theme_minimal()
print(p)
Needs ggplot2 · reads changepoint-timeline-demo.csv · app theme from the optional codesplashr helper
Each row is one metric: the dot is candidate minus champion, the bar its 95% paired interval.
Right favours the candidate on every row; a lower-is-better metric is flipped first.
The dashed line is the margin. The gate passes when the whole bar stays to its right.
1Callout 1: The whole interval clears the margin: non-inferior.
2Callout 2: Dashed line: the largest loss you accept.
3Callout 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
# Non-inferiority to the champion — Codesplash Chart Lab (recipe "noninferiority-forest")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for _, row in d.iterrows():
color = "#2e8b57" if row[LO] > -row[MG] else "#c0392b"
fig.add_scatter(x=[row[E]], y=[str(row[L])], mode="markers", marker=dict(color=color, size=9), showlegend=False,
error_x=dict(type="data", symmetric=False, array=[row[HI] - row[E]], arrayminus=[row[E] - row[LO]], color=color))
fig.add_scatter(x=[-row[MG], -row[MG]], y=[str(row[L]), str(row[L])], mode="markers", marker=dict(symbol="line-ns-open", size=22, color="#c0392b"), showlegend=False)
fig.add_vline(x=0, line_color="#888888")
fig.update_layout(xaxis_title="candidate minus champion (right = candidate better)", template="plotly_white")
fig.show()
Needs pandas, numpy, plotly · reads noninferiority-forest-demo.csv · app theme from the optional codesplash helper
Use TF-IDF to look past words common to all groups.
1Callout 1: The most frequent term in this group.
2Callout 2: The other group's top term.
3Callout 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
# Top terms — Codesplash Chart Lab (recipe "ngram-bars")# controls: top=20
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"])
TERM = "bigram"
N = "count"
G = "rating"
TOP = 20
keys = [TERM] + ([G] if G else [])
d = df.groupby(keys, observed=True)[N].sum().reset_index()
d = d.sort_values(N, ascending=False).groupby(G, observed=True).head(TOP) if G else d.sort_values(N, ascending=False).head(TOP)
fig = px.bar(d.iloc[::-1], x=N, y=TERM, orientation="h", facet_col=G, color=G, color_discrete_sequence=PALETTE)
fig.update_yaxes(matches=None, showticklabels=True)
fig.update_layout(showlegend=False)
fig.show()
Needs pandas, numpy, plotly · reads ngram-bars-demo.csv · app theme from the optional codesplash helper
Read the fill as the real data, the line as the synthetic.
They should overlap closely.
Look at the humps and tails: synthetic methods often smooth these away.
1Callout 1: Synthetic is lower at this peak.
2Callout 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
# Real vs synthetic distribution — Codesplash Chart Lab (recipe "density-compare")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, (name, d) in enumerate(series):
fig.add_scatter(x=d[X], y=d[D], mode="lines", fill="tozeroy" if i == 0 else None, name=name, line=dict(color=PALETTE[i % len(PALETTE)], width=2))
fig.update_layout(xaxis_title=X, yaxis_title="density")
fig.show()
Needs pandas, numpy, plotly · reads density-compare-demo.csv · app theme from the optional codesplash helper
Read total variation distance in the legend: lower is closer.
1Callout 1: A close match.
2Callout 2: Small categories: often lost or over-sampled.
3Callout 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
# Real vs synthetic category shares — Codesplash Chart Lab (recipe "share-compare")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
fig = px.bar(df, x=SH, y=L, color=S, orientation="h", barmode="group", color_discrete_sequence=PALETTE, category_orders={S: levels_of(df[S])})
fig.update_layout(legend_title=None, yaxis_title=None)
fig.show()
Needs pandas, numpy, plotly · reads share-compare-demo.csv · app theme from the optional codesplash helper
Read one histogram as synthetic rows' distance to their nearest training row.
Read the other as held-out real rows' distance to training.
Synthetic should not be closer: closer suggests copying.
1Callout 1: Distances near zero would suggest copies.
2Callout 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
# Distance to closest record — Codesplash Chart Lab (recipe "dcr-histogram")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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"
fig = px.histogram(df, x=D, color=P, nbins=30, histnorm="probability", barmode="overlay", opacity=0.5, color_discrete_sequence=PALETTE, category_orders={P: levels_of(df[P])})
fig.update_layout(yaxis_title="share of rows", legend_title=None)
fig.show()
Needs pandas, numpy, plotly · reads dcr-histogram-demo.csv · app theme from the optional codesplash helper
Read x as how much noise was added: small steps are nearly clean rows, large steps nearly pure noise.
Read y as how far the model's denoising guess is from the truth at that step.
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.
1Callout 1: Small t: fine-detail denoising.
2Callout 2: Large t: almost pure noise.
3Callout 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
# Diffusion loss by step — Codesplash Chart Lab (recipe "timestep-loss")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for name in levels_of(d[C]):
s = d[d[C].astype(str) == name].sort_values(T)
fig.add_trace(go.Scatter(x=s[T], y=s[V], mode="lines+markers", name=name))
fig.update_layout(xaxis_title=f"{T} (more noise →)", yaxis_title=V, template="plotly_white")
fig.update_yaxes(rangemode="tozero")
fig.show()
Needs pandas, numpy, plotly · reads timestep-loss-demo.csv · app theme from the optional codesplash helper
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.
Topics are ordered from largest to smallest; the grey bar at the end holds the documents that fit no topic.
Check the grey bar first: a long one means many documents were left unassigned by the settings.
1Callout 1: The largest topic and its distinctive words.
2Callout 2: Outliers: documents in no dense group.
3Callout 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
# Topic sizes — Codesplash Chart Lab (recipe "topic-sizes")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure(go.Bar(
x=d[DOCS], y=d[TOPIC].astype(str), orientation="h", text=d[TERMS] if TERMS else None, textposition="outside",
marker_color=[GREY if o else PALETTE[0] for o in d["_out"]],
))
fig.update_yaxes(autorange="reversed")
fig.update_layout(xaxis_title=DOCS, title="Documents per topic (outliers last)")
fig.show()
Needs pandas, numpy, plotly · reads topic-sizes-demo.csv · app theme from the optional codesplash helper
Read each dot as one image: brightness across, sharpness up on a log scale.
The shaded edges are too dark or too bright; dots under the dashed horizontal line are softer than the blur threshold.
Colours give the method's flag, so you can open the flagged files in the table below the chart.
1Callout 1: The dark band: mean brightness below the threshold.
2Callout 2: The blur line: sharpness below it is flagged.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
for i, f in enumerate(order):
m = flags == f
fig.add_scatter(x=d.loc[m, B], y=1 + d.loc[m, S], mode="markers", name=f, text=d.loc[m, LABEL] if LABEL else None,
marker=dict(size=8, color=GREY if f == "OK" else PALETTE[(i - ("OK" in order)) % len(PALETTE)], symbol=SERIES_MARKERS[i % 8], opacity=0.8)) # marker shape per flag
for x in (DARK, BRIGHT):
fig.add_vline(x=x, line_dash="dash", line_color=REF)
fig.add_hline(y=1 + BLUR, line_dash="dash", line_color=REF)
fig.update_yaxes(type="log", title="1 + sharpness (variance of the Laplacian)")
fig.update_xaxes(range=[0, 1], title="brightness (mean luma, 0–1)")
fig.update_layout(title="Brightness and sharpness of each image")
fig.show()
Needs pandas, numpy, plotly · reads image-quality-demo.csv · app theme from the optional codesplash helper
# Image brightness and sharpness — Codesplash Chart Lab (recipe "image-quality")# controls: dark=0.15, bright=0.85, blur=100
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("image-quality-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["flag"]] <- factor(df[["flag"]], levels = c("OK", "Dark", "Bright", "Blurry", "Duplicate"))
df[["file"]] <- factor(df[["file"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
b_col <- "brightness"
s_col <- "sharpness"
flag_col <- "flag"
label_col <- "file"
dark <- 0.15; bright <- 0.85; blur <- 100
flags_all <- c("OK", "Dark", "Bright", "Blurry", "Duplicate")
d <- df[!is.na(df[[b_col]]) & !is.na(df[[s_col]]), ]
d$flag <- if (is.null(flag_col)) "OK" else as.character(d[[flag_col]])
lv <- c(intersect(flags_all, d$flag), setdiff(sort(unique(d$flag)), flags_all))
d$flag <- factor(d$flag, levels = lv)
cols <- setNames(ifelse(lv == "OK", grey_col, rep_len(cs_cat, length(lv))[pmax(1, seq_along(lv) - ("OK" %in% lv))]), lv)
p <- ggplot(d, aes(x = .data[[b_col]], y = 1 + .data[[s_col]], colour = flag, shape = flag)) + # marker shape per flag, as in the app
geom_vline(xintercept = c(dark, bright), colour = ref_col, linetype = "dashed") +
geom_hline(yintercept = 1 + blur, colour = ref_col, linetype = "dashed") +
geom_point(size = 2.2, alpha = 0.8) +
{ if (!is.null(label_col)) geom_text(data = d[d$flag != "OK", ], aes(label = .data[[label_col]]), size = 2.4, vjust = -0.9, show.legend = FALSE) } + # name the flagged files
scale_y_log10() + scale_x_continuous(limits = c(0, 1)) +
scale_colour_manual(values = cols) + scale_shape_manual(values = setNames(rep_len(cs_shapes, length(lv)), lv)) +
labs(x = "brightness (mean luma, 0–1)", y = "1 + sharpness (variance of the Laplacian)", colour = NULL, shape = NULL,
title = "Brightness and sharpness of each image") + theme_cs
print(p)
Needs ggplot2 · reads image-quality-demo.csv · app theme from the optional codesplashr helper
Read each column as one metric: dots are rows, the box spans the middle half and the thick line is the median.
Compare systems side by side within a metric; the spread shows how uneven the outputs are.
Look for rows scoring near zero: they often hold a correct answer worded differently, or a real failure worth reading.
1Callout 1: A box: the middle half of the rows for one metric and system.
2Callout 2: Low-scoring rows worth reading.
3Callout 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
# Generated-text scores per row — Codesplash Chart Lab (recipe "text-metric-scores")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
systems = levels_of(d[SYS]) if SYS else [None]
fig = go.Figure()
for j, s in enumerate(systems):
m = (d[SYS].astype(str) == str(s)) if SYS else np.ones(len(d), bool)
fig.add_box(x=d.loc[m, M], y=d.loc[m, SCORE], name=str(s) if s is not None else "rows", boxpoints="all", jitter=0.5,
pointpos=0, marker=dict(size=4, opacity=0.4, color=PALETTE[j % len(PALETTE)]), line=dict(color=PALETTE[j % len(PALETTE)]))
fig.update_layout(boxmode="group", yaxis=dict(range=[0, 100], title="score (0–100)"), title="Score of each row, by metric")
fig.update_xaxes(categoryorder="array", categoryarray=levels_of(d[M]))
fig.show()
Needs pandas, numpy, plotly · reads text-metric-scores-demo.csv · app theme from the optional codesplash helper
Read each row as one metric: the dot is the corpus score and the bar its bootstrap interval.
Compare dots of different colours within a metric to see which system scores higher.
Use the method's paired p-value to judge the gap; intervals that overlap can still differ significantly.
1Callout 1: A corpus score with its interval.
2Callout 2: A second system on the same metric.
3Callout 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
# Corpus scores with intervals — Codesplash Chart Lab (recipe "text-metric-ci")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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])
systems = levels_of(d[SYS]) if SYS else [None]
fig = go.Figure()
for j, s in enumerate(systems):
r = d[(d[SYS].astype(str) == str(s))] if SYS else d
fig.add_scatter(x=r[EST], y=r[M], mode="markers", name=str(s) if s is not None else "score",
error_x=dict(type="data", symmetric=False, array=r[HI] - r[EST], arrayminus=r[EST] - r[LO]),
marker=dict(size=9, color=PALETTE[j % len(PALETTE)]))
fig.update_yaxes(categoryorder="array", categoryarray=levels_of(d[M])[::-1])
fig.update_layout(scattermode="group", xaxis_title="score (0–100)", title="Corpus scores with bootstrap intervals")
fig.show()
Needs pandas, numpy, plotly · reads text-metric-ci-demo.csv · app theme from the optional codesplash helper
Without bias, points form a symmetric funnel around the pooled effect.
Look for a missing corner: small studies with unfavourable results may be absent.
1Callout 1: Precise studies at the top.
2Callout 2: Imputed studies fill the gap.
3Callout 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
# Funnel plot (contour-enhanced) — Codesplash Chart Lab (recipe "meta-funnel")# controls: contours=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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"
LABEL = "study"
CENTER, ADJUSTED, CONTOURS = None, None, True
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 = go.Figure()
if CONTOURS: # where a study would be significant against zero
for zz, name in zip(stats.norm.ppf([0.995, 0.975, 0.95]), ("p = 0.01", "p = 0.05", "p = 0.10")):
fig.add_scatter(x=[-zz * se_max, 0, zz * se_max], y=[se_max, 0, se_max], mode="lines", line=dict(color=GREY, width=1), name=name)
if CENTER is not None:
z95 = stats.norm.ppf(0.975)
fig.add_scatter(x=[CENTER - z95 * se_max, CENTER, CENTER + z95 * se_max], y=[se_max, 0, se_max], mode="lines", line=dict(color=REF, dash="dash", width=1), name="pseudo 95% limits")
if ADJUSTED is not None:
fig.add_vline(x=ADJUSTED, line=dict(color=PALETTE[1], dash="dot"))
text = d[LABEL].astype(str) if LABEL else None
fig.add_scatter(x=d.loc[~imputed, EST], y=d.loc[~imputed, SE], mode="markers", marker=dict(size=8, color=PALETTE[0]), name="study", text=None if text is None else text[~imputed])
if imputed.any():
fig.add_scatter(x=d.loc[imputed, EST], y=d.loc[imputed, SE], mode="markers", marker=dict(size=8, color="rgba(0,0,0,0)", line=dict(color=PALETTE[0], width=1.5)), name="imputed")
fig.update_yaxes(range=[se_max, 0], title=SE) # the most precise studies at the top
fig.update_xaxes(title=EST)
fig.show()
Needs pandas, numpy, plotly, scipy · reads meta-funnel-demo.csv · app theme from the optional codesplash helper
# Funnel plot (contour-enhanced) — Codesplash Chart Lab (recipe "meta-funnel")# controls: contours=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("meta-funnel-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["study"]] <- factor(df[["study"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
est_col <- "log risk ratio"
se_col <- "standard error"
kind_col <- "study"
center <- NULL; adjusted <- NULL; contours <- TRUE
egger_b0 <- NULL; egger_b1 <- NULL
d <- df[!is.na(df[[est_col]]) & !is.na(df[[se_col]]), ]
d$est <- d[[est_col]]; d$se <- d[[se_col]]
d$kind <- if (is.null(kind_col)) "study" else ifelse(as.character(d[[kind_col]]) == "imputed", "imputed", "study")
se_max <- max(d$se) * 1.08
tri <- function(mid, z) data.frame(x = c(mid - z * se_max, mid, mid + z * se_max), y = c(se_max, 0, se_max))
p <- ggplot()
if (contours) for (z in qnorm(c(0.995, 0.975, 0.95))) p <- p + geom_polygon(data = tri(0, z), aes(x, y), fill = NA, colour = grey_col, linewidth = 0.3)
if (!is.null(center)) {
p <- p + geom_path(data = tri(center, qnorm(0.975)), aes(x, y), colour = ref_col, linetype = "dashed") +
geom_vline(xintercept = center, colour = ref_col)
}
if (!is.null(adjusted)) p <- p + geom_vline(xintercept = adjusted, colour = cs_cat[2], linetype = "dotted")
if (!is.null(egger_b0) && !is.null(egger_b1)) p <- p + annotate("segment", x = egger_b0, xend = egger_b0 + egger_b1 * se_max, y = 0, yend = se_max, colour = cs_cat[3])
p <- p + geom_point(data = d, aes(est, se, shape = kind), colour = cs_cat[1], size = 2.2) +
scale_shape_manual(values = c(study = 16, imputed = 1)) +
scale_y_reverse(limits = c(se_max, 0)) + # the most precise studies at the top
labs(x = est_col, y = se_col, shape = NULL) + theme_cs
print(p)
Needs ggplot2 · reads meta-funnel-demo.csv · app theme from the optional codesplashr helper
Read x as precision and y as the standardized estimate.
Under a common effect, points fall within ±2 of the line.
Points outside the band are the studies driving heterogeneity.
1Callout 1: The pooled slope.
2Callout 2: A study outside the band.
3Callout 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
# Galbraith (radial) plot — Codesplash Chart Lab (recipe "galbraith")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_scatter(x=[0, x_max, x_max, 0, 0], y=[2, SLOPE * x_max + 2, SLOPE * x_max - 2, -2, 2], fill="toself", mode="lines", line=dict(color=GREY, width=0), name="± 2")
fig.add_scatter(x=[0, x_max], y=[0, SLOPE * x_max], mode="lines", line=dict(color=REF, width=1), name="common effect")
fig.add_scatter(x=d[PREC], y=d[Z], mode="markers", marker=dict(size=8, color=[PALETTE[1] if o else PALETTE[0] for o in outside]), name="study", text=d[LABEL].astype(str) if LABEL else None)
fig.update_layout(xaxis_title=PREC, yaxis_title=Z)
fig.show()
Needs pandas, numpy, plotly · reads galbraith-demo.csv · app theme from the optional codesplash helper
Read the line's slope and band for how the effect changes.
1Callout 1: A study at low latitude.
2Callout 2: Effects grow with latitude.
3Callout 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
# Meta-regression bubble plot — Codesplash Chart Lab (recipe "metareg-bubble")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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"
LABEL = None
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 = go.Figure()
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)
fig.add_scatter(x=np.r_[xs, xs[::-1]], y=np.r_[fit + crit * se, (fit - crit * se)[::-1]], fill="toself", mode="lines", line=dict(width=0), fillcolor=PALETTE[0], opacity=0.15, name="interval")
fig.add_scatter(x=xs, y=fit, mode="lines", line=dict(color=PALETTE[0], width=2), name="fit")
fig.add_scatter(x=d[X], y=d[Y], mode="markers", marker=dict(size=6 + 24 * np.sqrt(w / w.max()), color="rgba(0,0,0,0)", line=dict(color=REF, width=1)), name="study", text=d[LABEL].astype(str) if LABEL else None)
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly, scipy · reads metareg-bubble-demo.csv · app theme from the optional codesplash helper
# Meta-regression bubble plot — Codesplash Chart Lab (recipe "metareg-bubble")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("metareg-bubble-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
x_col <- "absolute latitude"
y_col <- "log risk ratio"
weight_col <- "weight"
b0 <- NULL; b1 <- NULL # the fit the engine published
v00 <- NULL; v01 <- NULL; v11 <- NULL; crit <- NULL
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), ]
d$x <- d[[x_col]]; d$y <- d[[y_col]]
d$w <- if (is.null(weight_col)) rep(1, nrow(d)) else d[[weight_col]]
p <- ggplot()
if (!is.null(b0) && !is.null(b1)) {
pad <- diff(range(d$x)) * 0.05
line <- data.frame(x = seq(min(d$x) - pad, max(d$x) + pad, length.out = 65))
line$fit <- b0 + b1 * line$x
if (!is.null(v00) && !is.null(v01) && !is.null(v11)) {
se <- sqrt(pmax(0, v00 + 2 * line$x * v01 + line$x^2 * v11)) # Var(b0 + b1·x) from the coefficient covariance
k <- if (is.null(crit)) qnorm(0.975) else crit
line$low <- line$fit - k * se; line$high <- line$fit + k * se
p <- p + geom_ribbon(data = line, aes(x, ymin = low, ymax = high), fill = cs_cat[1], alpha = 0.15)
}
p <- p + geom_line(data = line, aes(x, fit), colour = cs_cat[1], linewidth = 0.8)
}
p <- p + geom_point(data = d, aes(x, y, size = w), shape = 1, colour = ref_col) +
scale_size_area(max_size = 9, guide = "none") +
labs(x = x_col, y = y_col) + theme_cs
print(p)
Needs ggplot2 · reads metareg-bubble-demo.csv · app theme from the optional codesplashr helper
Read x as the expected p-value on a log scale, y as the observed one.
On the diagonal: as expected under the null.
Above the band: more small p-values than chance would give.
1Callout 1: These tests stand out above the band.
2Callout 2: Most p-values are on the diagonal.
3Callout 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
# p-value Q–Q plot — Codesplash Chart Lab (recipe "pvalue-qq")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
fig.add_scatter(x=np.r_[expected, expected[::-1]], y=np.r_[band_high, band_low[::-1]], fill="toself", mode="lines", line=dict(width=0), fillcolor=GREY, name="95% band under the null")
fig.add_scatter(x=[0, hi], y=[0, hi], mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False)
fig.add_scatter(x=expected, y=observed, mode="markers", marker=dict(size=6, color=PALETTE[0]), name="p-values")
fig.update_xaxes(range=[0, hi], title="Expected −log10 p")
fig.update_yaxes(range=[0, hi], title="Observed −log10 p")
fig.show()
Needs pandas, numpy, plotly, scipy · reads pvalue-qq-demo.csv · app theme from the optional codesplash helper
# p-value Q–Q plot — Codesplash Chart Lab (recipe "pvalue-qq")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("pvalue-qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
p_col <- "p"
p_values <- suppressWarnings(as.numeric(df[[p_col]]))
p_values <- sort(p_values[!is.na(p_values) & p_values > 0 & p_values <= 1])
k <- length(p_values); i <- seq_len(k)
d <- data.frame(expected = -log10(i / (k + 1)), observed = -log10(p_values),
low = -log10(qbeta(0.975, i, k + 1 - i)), high = -log10(qbeta(0.025, i, k + 1 - i))) # order statistics of uniform p-values
hi <- max(1, d$expected, d$observed, d$high) * 1.06
p <- ggplot(d, aes(expected, observed)) +
geom_ribbon(aes(ymin = low, ymax = high), fill = grey_col, alpha = 0.5) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_point(colour = cs_cat[1], size = 1.6) +
coord_cartesian(xlim = c(0, hi), ylim = c(0, hi)) +
labs(x = "Expected −log10 p", y = "Observed −log10 p") + theme_cs
print(p)
Needs ggplot2 · reads pvalue-qq-demo.csv · app theme from the optional codesplashr helper
Read each point as one subset of the studies: x is its pooled estimate, y its I².
A single compact cloud means the answer barely depends on which studies are in.
Separate clouds, or a colour that sits apart, point to a study (or group) that differs from the rest.
1Callout 1: Marginal histogram of the subsets' estimates.
2Callout 2: Subsets without the flagged study.
3Callout 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
# GOSH plot (all study subsets) — Codesplash Chart Lab (recipe "gosh")# controls: center=0, reference=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
for i, g in enumerate(groups):
s = d if g is None else d[d[GROUP].astype(str) == g]
fig.add_scattergl(x=s[EST], y=s[I2], mode="markers", marker=dict(size=3, color=PALETTE[i], opacity=0.5), name=g or "subset")
fig.add_vline(x=REFERENCE, line_dash="dash", line_color=REF)
fig.add_vline(x=CENTER, line_color="black", annotation_text="all studies")
fig.update_layout(xaxis_title=EST, yaxis_title=I2, yaxis_range=[0, 100])
fig.show()
Needs pandas, numpy, plotly · reads gosh-demo.csv · app theme from the optional codesplash helper
Read each curve as a p-value function: it peaks at p = 1 at the estimate and falls away on both sides.
Where a curve crosses a horizontal level α, the two crossings are its (1 − α) confidence interval.
Compare the bold pooled curve with the shaded prediction curve: the second shows where a new study's true effect may land.
1Callout 1: The pooled estimate: p = 1.
2Callout 2: The p = .05 line: crossings give the 95% CI.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
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])
fig = go.Figure()
for name, s in d.groupby(d[CURVE].astype(str), sort=False):
s = s.sort_values(X)
k = str(s[KIND].iloc[0]) if KIND else "study"
if k == "prediction":
fig.add_scatter(x=s[X], y=s[P], mode="lines", fill="tozeroy", line=dict(color=PALETTE[2], width=1, dash=SERIES_DASHES[2]), opacity=0.4, name="prediction") # dotted outline, as in the app
elif k == "pooled":
fig.add_scatter(x=s[X], y=s[P], mode="lines", line=dict(color="black", width=3), name="pooled")
else:
fig.add_scatter(x=s[X], y=s[P], mode="lines", line=dict(color=PALETTE[0], width=1), opacity=0.6, name=name, showlegend=False)
fig.add_hline(y=ALPHA, line_dash="dash", line_color=REF, annotation_text=f"{100 * (1 - ALPHA):g}% CI")
fig.add_vline(x=REFERENCE, line_dash="dot", line_color=REF)
fig.update_layout(xaxis_title=X, yaxis_title="p-value", yaxis_range=[0, 1], xaxis_type="log" if LOG else "linear")
fig.show()
Needs pandas, numpy, plotly · reads drapery-demo.csv · app theme from the optional codesplash helper
# Drapery plot (p-value functions) — Codesplash Chart Lab (recipe "drapery")# controls: log=false, reference=0, alpha=0.05
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("drapery-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["curve"]] <- factor(df[["curve"]])
df[["kind"]] <- factor(df[["kind"]], levels = c("study", "pooled", "prediction"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
x_col <- "risk ratio"
p_col <- "p-value"
curve_col <- "curve"
kind_col <- "kind"
log_x <- FALSE; reference <- 0; alpha <- 0.05
d <- df[!is.na(df[[x_col]]) & !is.na(df[[p_col]]), ]
d$x <- d[[x_col]]; d$p <- d[[p_col]]; d$curve <- as.character(d[[curve_col]])
d$kind <- if (!is.null(kind_col)) as.character(d[[kind_col]]) else "study"
d <- d[order(d$curve, d$x), ]
p <- ggplot() +
geom_area(data = d[d$kind == "prediction", ], aes(x, p, group = curve), fill = cs_cat[3], alpha = 0.18) +
geom_line(data = d[d$kind == "prediction", ], aes(x, p, group = curve), colour = cs_cat[3], alpha = 0.6, linetype = cs_linetypes[3]) + # dotted outline, as in the app
geom_line(data = d[d$kind == "study", ], aes(x, p, group = curve), colour = cs_cat[1], alpha = 0.55) +
geom_line(data = d[d$kind == "pooled", ], aes(x, p, group = curve), colour = "black", linewidth = 1.1) +
geom_hline(yintercept = alpha, colour = ref_col, linetype = "dashed") +
geom_vline(xintercept = reference, colour = ref_col, linetype = "dotted") +
annotate("text", x = Inf, y = alpha, label = sprintf("%g%% CI", 100 * (1 - alpha)), hjust = 1.05, vjust = -0.4, size = 3) +
coord_cartesian(ylim = c(0, 1)) +
labs(x = x_col, y = "p-value") + theme_cs
if (log_x) p <- p + scale_x_log10()
print(p)
Needs ggplot2 · reads drapery-demo.csv · app theme from the optional codesplashr helper
Read only the significant results: each point is the share of their p-values in one .01-wide bin.
A curve that falls from left to right (many very small p-values) is right-skewed, as real effects produce.
A flat curve near 20% looks like no effect; a curve rising towards .05 suggests p-hacking.
1Callout 1: Many p-values below .01: right skew.
2Callout 2: The flat 20% line: no true effect.
3Callout 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
# p-curve — Codesplash Chart Lab (recipe "pcurve")# controls: k=0
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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]]
fig = go.Figure()
if NULL:
fig.add_scatter(x=ticks, y=d[NULL], mode="lines", line=dict(color=PALETTE[3], dash="dot"), name="no effect")
if P33:
fig.add_scatter(x=ticks, y=d[P33], mode="lines", line=dict(color=PALETTE[2], dash="dash"), name="33% power")
fig.add_scatter(x=ticks, y=d[OBS], mode="lines+markers+text", text=[f"{v:.0f}%" for v in d[OBS]], textposition="top center",
line=dict(color=PALETTE[0], width=3), name=f"observed ({K:g} significant)" if K else "observed")
fig.update_layout(xaxis_title=f"p-value ({BIN})", yaxis_title=f"share of significant results (%; {OBS})", yaxis_range=[0, 100])
fig.show()
Needs pandas, numpy, plotly · reads pcurve-demo.csv · app theme from the optional codesplash helper
Small ellipses: the region for each group's mean. Larger ones: where most rows lie.
Means whose ellipses don't overlap are well apart.
1Callout 1: The ellipse around one group's mean.
2Callout 2: Tilt: how the two variables move together inside the group.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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)]
fig.add_scatter(x=xy[:, 0], y=xy[:, 1], mode="markers", marker=dict(color=col, size=6, opacity=0.45, symbol=SERIES_MARKERS[i % 8] if many else "circle"), showlegend=False)
path, m = ellipse(xy, "mean", 0.95)
fig.add_scatter(x=path[:, 0], y=path[:, 1], mode="lines", line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if many else "solid"), name=f"{k} (n = {len(xy)})")
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly, scipy · reads confidence-ellipse-demo.csv · app theme from the optional codesplash helper
# Confidence and data ellipses — Codesplash Chart Lab (recipe "confidence-ellipse")# controls: kind=mean, level=0.95, points=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("confidence-ellipse-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "petal length (cm)"
Y <- "petal width (cm)"
G <- "species"
ellipse <- function(x, y, kind, level) { # data: √χ²₂(level); mean: Hotelling's region
n <- length(x)
if (n <= 2) return(NULL)
r <- if (kind == "data") sqrt(qchisq(level, 2)) else sqrt(2 * (n - 1) * qf(level, 2, n - 2) / (n * (n - 2)))
e <- eigen(cov(cbind(x, y)), symmetric = TRUE)
t <- seq(0, 2 * pi, length.out = 73)
p <- r * e$vectors %*% (sqrt(pmax(e$values, 0)) * rbind(cos(t), sin(t)))
data.frame(x = mean(x) + p[1, ], y = mean(y) + p[2, ])
}
d <- df[complete.cases(df[, c(X, Y, G)]), ]
d$.x <- d[[X]]; d$.y <- d[[Y]]
d$.g <- if (is.null(G)) factor("all rows") else factor(as.character(d[[G]]), levels = levels_of(d[[G]]))
paths <- do.call(rbind, lapply(levels(d$.g), function(k) {
e <- ellipse(d$.x[d$.g == k], d$.y[d$.g == k], "mean", 0.95)
if (is.null(e)) return(NULL)
e$.g <- k; e
}))
p <- ggplot() +
geom_point(aes(.x, .y, colour = .g, shape = .g), d, size = 1.2, alpha = 0.45) +
geom_path(aes(x, y, colour = .g, linetype = .g), paths, linewidth = 0.9) + # shape and dash per group, as in the app
scale_colour_manual(values = cs_cat, name = NULL) + scale_linetype_manual(values = cs_linetypes, name = NULL) +
scale_shape_manual(values = cs_shapes, name = NULL) +
labs(x = X, y = Y) + theme_cs
print(p)
Needs ggplot2 · reads confidence-ellipse-demo.csv · app theme from the optional codesplashr helper
Read points as rows on the combinations that best separate the groups.
Read circles as confidence regions for each group's mean.
Read arrows as outcomes: the direction each one drives.
1Callout 1: A group's mean and confidence circle.
2Callout 2: An outcome's direction.
3Callout 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
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")# controls: vectors=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
for i, k in enumerate(levels_of(points[G])):
g, col = points[points[G].astype(str) == str(k)], PALETTE[i % len(PALETTE)]
fig.add_scatter(x=g[X], y=g[Y] if Y else 0 * g[X], mode="markers", marker=dict(color=col, size=6, opacity=0.5, symbol=SERIES_MARKERS[i % 8]), name=str(k)) # shape per group, as in the app
m = means[means[G].astype(str) == str(k)]
fig.add_scatter(x=m[X], y=m[Y] if Y else 0 * m[X], mode="markers", marker=dict(color=col, size=11, symbol=SERIES_MARKERS[i % 8], line=dict(color="white", width=1)), showlegend=False)
for _, q in m.iterrows():
if RAD and pd.notna(q[RAD]):
qy = q[Y] if Y else 0
fig.add_shape(type="circle", x0=q[X] - q[RAD], x1=q[X] + q[RAD], y0=qy - q[RAD], y1=qy + q[RAD], line=dict(color=col))
for _, s in struct.iterrows():
fig.add_annotation(x=s[X], y=s[Y] if Y else 0, ax=0, ay=0, axref="x", ayref="y", text=str(s[LAB]) if LAB else "", showarrow=True, arrowhead=2, arrowcolor=REF)
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()
Needs pandas, numpy, plotly · reads canonical-plot-demo.csv · app theme from the optional codesplash helper
# Canonical discriminant plot — Codesplash Chart Lab (recipe "canonical-plot")# controls: vectors=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("canonical-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica", ""))
df[["kind"]] <- factor(df[["kind"]])
df[["label"]] <- factor(df[["label"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "Can1 (r = 0.98)"
Y <- "Can2 (r = 0.47)"
G <- "species"
KIND <- "kind"
LAB <- "label"
RAD <- "95% radius of the mean"
d <- data.frame(x = df[[X]], y = if (is.null(Y)) 0 else df[[Y]], g = as.character(df[[G]]), kind = tolower(as.character(df[[KIND]])), label = if (is.null(LAB)) "" else as.character(df[[LAB]]), r = if (is.null(RAD)) NA_real_ else df[[RAD]])
points <- d[!startsWith(d$kind, "struct") & d$kind != "mean", ]
means <- d[d$kind == "mean", ]
struct <- d[startsWith(d$kind, "struct"), ]
theta <- seq(0, 2 * pi, length.out = 73)
circles <- do.call(rbind, lapply(which(is.finite(means$r)), function(i) data.frame(x = means$x[i] + means$r[i] * cos(theta), y = means$y[i] + means$r[i] * sin(theta), g = means$g[i])))
p <- ggplot() +
geom_hline(yintercept = 0, colour = ref_col, linewidth = 0.2, linetype = "dotted") +
geom_vline(xintercept = 0, colour = ref_col, linewidth = 0.2, linetype = "dotted") +
geom_point(aes(x, y, colour = g, shape = g), points, size = 1.2, alpha = 0.5) + # shape per group, as in the app
geom_point(aes(x, y, colour = g, shape = g), means, size = 3) +
(if (!is.null(circles)) geom_path(aes(x, y, colour = g), circles)) +
geom_segment(aes(0, 0, xend = x, yend = y), struct, colour = ref_col, arrow = arrow(length = unit(0.15, "cm"))) +
geom_text(aes(x, y, label = label), struct, size = 2.6, vjust = -0.6) +
scale_colour_manual(values = cs_cat, name = NULL) + scale_shape_manual(values = cs_shapes, name = NULL) +
labs(x = X, y = if (is.null(Y)) "" else Y) + theme_cs
print(p)
Needs ggplot2 · reads canonical-plot-demo.csv · app theme from the optional codesplashr helper
Read points as rows' squared distance from the centre, sorted.
Under multivariate normality they follow the dashed line.
Points above the horizontal cutoff are candidate outliers.
1Callout 1: Rows above the cutoff: candidate multivariate outliers.
2Callout 2: On the line: consistent with normality.
3Callout 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
# χ² 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
fig.add_scatter(x=np.r_[theo, theo[::-1]], y=np.r_[lo, hi[::-1]], fill="toself", fillcolor="rgba(120,120,120,0.15)", line=dict(width=0), name="95% pointwise envelope")
fig.add_scatter(x=theo, y=theo, mode="lines", line=dict(color=REF, dash="dash", width=1), showlegend=False)
fig.add_hline(y=cut, line_dash="dot", line_color=REF)
fig.add_scatter(x=theo[obs <= cut], y=obs[obs <= cut], mode="markers", marker=dict(color=PALETTE[0], size=5), name="rows")
fig.add_scatter(x=theo[obs > cut], y=obs[obs > cut], mode="markers", marker=dict(color=PALETTE[1], size=6), name=f"beyond χ² 97.5% ({(obs > cut).sum()})")
fig.update_layout(xaxis_title="χ² quantile", yaxis_title="Squared Mahalanobis distance")
fig.show()
Needs pandas, numpy, plotly, scipy · reads mahalanobis-qq-demo.csv · app theme from the optional codesplash helper
# χ² Q–Q plot of Mahalanobis distances — Codesplash Chart Lab (recipe "mahalanobis-qq")# controls: df=2, envelope=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("mahalanobis-qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
D <- "D² of each row"
K <- 2 # degrees of freedom: the number of variables
obs <- sort(df[[D]])
n <- length(obs); r <- seq_len(n)
d <- data.frame(theo = qchisq((r - 0.5) / n, K), obs = obs, lo = qchisq(qbeta(0.025, r, n - r + 1), K), hi = qchisq(qbeta(0.975, r, n - r + 1), K))
cut <- qchisq(0.975, K)
d$out <- d$obs > cut
p <- ggplot(d, aes(theo, obs)) +
geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.12) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_hline(yintercept = cut, colour = ref_col, linetype = "dotted") +
geom_point(aes(colour = out), size = 1.3) +
scale_colour_manual(values = cs_cat[1:2], labels = c("rows", "beyond χ² 97.5%"), name = NULL) +
labs(x = "χ² quantile", y = "Squared Mahalanobis distance") + theme_cs
print(p)
Needs ggplot2 · reads mahalanobis-qq-demo.csv · app theme from the optional codesplashr helper
Read each line as a group's means across measures.
Parallel lines: the same shape, possibly at different levels.
Non-parallel lines: the groups change differently.
1Callout 1: Lines run roughly parallel here.
2Callout 2: The vertical gap: the level difference.
3Callout 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
# Profile plot — Codesplash Chart Lab (recipe "profile-plot")# controls: intervals=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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])
fig = go.Figure()
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
g = g.set_index(g[M].astype(str)).reindex(measures)
err = dict(type="data", array=g[HI] - g[V], arrayminus=g[V] - g[LO]) if LO and HI else None
fig.add_scatter(x=measures, y=g[V], mode="lines+markers", name=str(k), line=dict(color=PALETTE[i % len(PALETTE)], dash=SERIES_DASHES[i % 8] if many else "solid"), marker=dict(symbol=SERIES_MARKERS[i % 8] if many else "circle", size=8), error_y=err)
fig.update_layout(xaxis_title=M, yaxis_title=V)
fig.show()
Needs pandas, numpy, plotly · reads profile-plot-demo.csv · app theme from the optional codesplash helper
# Profile plot — Codesplash Chart Lab (recipe "profile-plot")# controls: intervals=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("profile-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["measure"]] <- factor(df[["measure"]], levels = c("hour 1", "hour 2", "hour 3", "hour 4", "hour 5"))
df[["treatment"]] <- factor(df[["treatment"]], levels = c("control", "A", "B"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
M <- "measure"
V <- "mean score"
G <- "treatment"
LO <- "CI low"
HI <- "CI high"
d <- data.frame(m = factor(as.character(df[[M]]), levels = levels_of(df[[M]])), v = df[[V]], g = if (is.null(G)) "all" else as.character(df[[G]]))
if (!is.null(LO) && !is.null(HI)) { d$lo <- df[[LO]]; d$hi <- df[[HI]] }
p <- ggplot(d, aes(m, v, colour = g, group = g, linetype = g, shape = g)) + # dash and marker shape per profile, as in the app
geom_line() + geom_point(size = 2) +
(if (!is.null(LO) && !is.null(HI)) geom_linerange(aes(ymin = lo, ymax = hi), alpha = 0.6)) +
scale_colour_manual(values = cs_cat, name = G) + scale_linetype_manual(values = cs_linetypes, name = G) + scale_shape_manual(values = cs_shapes, name = G) +
labs(x = M, y = V) + theme_cs
print(p)
Needs ggplot2 · reads profile-plot-demo.csv · app theme from the optional codesplashr helper
Read points as rows placed so that distances match their dissimilarities.
Read diamonds as group centres.
Separated centres suggest different locations; different hull sizes suggest different spreads.
1Callout 1: A group centre.
2Callout 2: Hull: the group's spread.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
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 = go.Figure()
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 = list(ConvexHull(xy).vertices)
h.append(h[0])
fig.add_scatter(x=xy[h, 0], y=xy[h, 1], mode="lines", fill="toself", fillcolor=rgba(col, 0.07), line=dict(color=col, width=1), showlegend=False, hoverinfo="skip")
except Exception:
pass
if SPOKES:
sx = [v for px in xy[:, 0] for v in (ctr[0], px, None)]
sy = [v for py in xy[:, 1] for v in (ctr[1], py, None)]
fig.add_scatter(x=sx, y=sy, mode="lines", line=dict(color=rgba(col, 0.3), width=0.8), showlegend=False, hoverinfo="skip")
fig.add_scatter(x=xy[:, 0], y=xy[:, 1], mode="markers", name=f"{k} (n = {len(xy)})", marker=dict(color=col, symbol=SERIES_MARKERS[i % 8], size=6, opacity=0.6)) # shape per group, as in the app
if G:
fig.add_scatter(x=[ctr[0]], y=[ctr[1]], mode="markers", showlegend=False, marker=dict(symbol="diamond", size=11, color=col, line=dict(color="white", width=1.2)))
fig.update_layout(xaxis_title=X, yaxis_title=Y, legend_title_text=G or "")
fig.update_yaxes(scaleanchor="x", scaleratio=1) # equal units
fig.show()
Needs pandas, numpy, plotly, scipy · reads pcoa-centroids-demo.csv · app theme from the optional codesplash helper
# Principal coordinates by group — Codesplash Chart Lab (recipe "pcoa-centroids")# controls: center=centroid, spokes=false, hulls=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("pcoa-centroids-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["management"]] <- factor(df[["management"]], levels = c("grazed", "mown", "natural"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
centre <- function(xy, how) {
y <- colMeans(xy) # centroid, or the spatial median by Weiszfeld's iterations from the mean
if (how != "median") return(y)
for (it in 1:1000) {
d <- sqrt(rowSums(sweep(xy, 2, y)^2)); keep <- d > 1e-15
if (!any(keep)) return(y)
w <- 1 / d[keep]
nxt <- colSums(xy[keep, , drop = FALSE] * w) / sum(w)
if (sqrt(sum((nxt - y)^2)) <= 1e-10 * (1 + sqrt(sum(y^2)))) return(nxt)
y <- nxt
}
y
}
x_col <- "PCoA 1 (31.4%)"
y_col <- "PCoA 2 (17.9%)"
g_col <- "management"
center <- "centroid"; show_spokes <- FALSE; show_hulls <- TRUE
keep <- !is.na(df[[x_col]]) & !is.na(df[[y_col]]) & (if (is.null(g_col)) TRUE else !is.na(df[[g_col]]))
d <- data.frame(x = df[[x_col]][keep], y = df[[y_col]][keep], k = if (is.null(g_col)) "All rows" else as.character(df[[g_col]][keep]))
ks <- if (is.null(g_col)) "All rows" else levels_of(df[[g_col]][keep])
d$k <- factor(d$k, levels = ks)
parts <- split(d, d$k, drop = TRUE)
ctr <- do.call(rbind, lapply(names(parts), function(k) { m <- centre(as.matrix(parts[[k]][c("x", "y")]), center); data.frame(k = k, cx = m[1], cy = m[2]) }))
ctr$k <- factor(ctr$k, levels = ks)
hulls <- do.call(rbind, lapply(parts, function(g) if (nrow(g) >= 3) g[grDevices::chull(g$x, g$y), ] else NULL))
spk <- merge(d, ctr, by = "k")
p <- ggplot(d, aes(x, y, colour = k)) +
{ if (show_hulls && !is.null(hulls)) geom_polygon(data = hulls, aes(fill = k), alpha = 0.07, show.legend = FALSE) } +
{ if (show_spokes) geom_segment(data = spk, aes(x = cx, y = cy, xend = x, yend = y), alpha = 0.3, linewidth = 0.3, show.legend = FALSE) } +
geom_point(aes(shape = k), size = 1.4, alpha = 0.6) + # shape per group, as in the app
{ if (!is.null(g_col)) geom_point(data = ctr, aes(cx, cy, fill = k), shape = 23, size = 3.2, colour = "white", stroke = 1, show.legend = FALSE) } +
scale_colour_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
scale_fill_manual(values = setNames(rep_len(cs_cat, length(ks)), ks)) +
scale_shape_manual(values = setNames(rep_len(cs_shapes, length(ks)), ks)) +
coord_equal() + # equal units: distances read the same both ways
labs(x = x_col, y = y_col, colour = g_col, shape = g_col) + theme_cs
print(p)
Needs ggplot2 · reads pcoa-centroids-demo.csv · app theme from the optional codesplashr helper
Read x as distance classes, y as Mantel r in each class.
Filled points are significant.
Positive at short distances and falling suggests rows close together are alike.
1Callout 1: At short distances: rows are alike.
2Callout 2: No association here.
3Callout 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
# Mantel correlogram — Codesplash Chart Lab (recipe "mantel-correlogram")# controls: alpha=0.05
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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
d = df.dropna(subset=[MID, R]).sort_values(MID)
sig = (d[P] < ALPHA).to_numpy() if P else np.zeros(len(d), bool)
fig = go.Figure(go.Scatter(x=d[MID], y=d[R], mode="lines+markers", name="Mantel r", line=dict(color=PALETTE[0], width=1.6),
marker=dict(size=9, color=[PALETTE[0] if s else "white" for s in sig], line=dict(color=[PALETTE[0] if s else REF for s in sig], width=1.5))))
if PAIRS: # pair counts in the hover
fig.update_traces(customdata=d[PAIRS], hovertemplate="class %{x}<br>r = %{y:.3f}<br>%{customdata:.0f} pairs<extra></extra>")
fig.add_hline(y=0, line=dict(color=GREY, dash="dash"))
fig.update_layout(xaxis_title=MID, yaxis_title="Mantel r", title=f"Filled: corrected p < {ALPHA:g}")
fig.show()
Needs pandas, numpy, plotly · reads mantel-correlogram-demo.csv · app theme from the optional codesplash helper
Read colour as the value in each region; check the legend's classes.
Look for clusters of similar colours.
Light grey regions have no data.
1Callout 1: The darkest class: the highest values.
2Callout 2: Legend: classes and their ranges.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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
if features is None:
d = d.sort_values(VALUE).tail(40)
fig = go.Figure(go.Bar(x=d[VALUE], y=d[REGION].astype(str), orientation="h", marker_color=[ramp(0.12 + 0.88 * tone(float(v))) for v in d[VALUE]]))
fig.update_layout(title=f"{VALUE} by {REGION}", xaxis_title=VALUE)
else:
fill = lambda i: ramp(0.12 + 0.88 * tone(value_at[i])) if i in value_at else NO_DATA
edges = [lo, *breaks, hi]
names = {ramp(0.12 + 0.88 * i / max(1, len(breaks))): f"{edges[i]:.3g} to {edges[i + 1]:.3g}" for i in range(len(edges) - 1)} if breaks else {}
fig = go.Figure(region_traces(features, project, fill, lambda col: "No data" if col == NO_DATA else names.get(col, "value"), "white"))
fig.update_layout(title=f"{VALUE} by {REGION}", **MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads choropleth-demo.csv · app theme from the optional codesplash helper
# Choropleth map — Codesplash Chart Lab (recipe "choropleth")# controls: boundaries=world-countries-110m, breaks=quantile, classes=5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("choropleth-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["country"]] <- factor(df[["country"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
class_breaks <- function(values, k, method) {
# k − 1 thresholds: type-7 quantiles or equal widths; a value on a break goes to the upper class.
if (method == "quantile") return(as.numeric(stats::quantile(values, (1:(k - 1)) / k, type = 7, names = FALSE)))
min(values) + (max(values) - min(values)) * (1:(k - 1)) / k
}
ramp <- grDevices::colorRamp(c(seq_ramp[1], seq_ramp[length(seq_ramp)]))
ramp_hex <- function(t) { m <- ramp(pmin(1, pmax(0, t))); grDevices::rgb(m[, 1], m[, 2], m[, 3], maxColorValue = 255) }
region_col <- "country"
value_col <- "index (simulated)"
boundaries_file <- "choropleth-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "world"; method <- "quantile"; k <- 5
d <- df[!is.na(df[[region_col]]) & !is.na(df[[value_col]]), , drop = FALSE]
m <- load_map(boundaries_file, scope)
if (is.null(m)) {
d <- utils::tail(d[order(d[[value_col]]), , drop = FALSE], 40)
d$label <- factor(as.character(d[[region_col]]), levels = as.character(d[[region_col]]))
p <- ggplot(d, aes(.data[[value_col]], label)) + geom_col(fill = seq_ramp[length(seq_ramp)]) + labs(x = value_col, y = NULL) + theme_cs
} else {
fi <- match_regions(m$features, d[[region_col]])
value_at <- rep(NA_real_, length(m$features))
value_at[fi[!is.na(fi)]] <- d[[value_col]][!is.na(fi)]
values <- value_at[!is.na(value_at)]
breaks <- if (method == "continuous") numeric() else class_breaks(values, k, method)
tone <- if (method == "continuous") (value_at - min(values)) / max(1e-12, max(values) - min(values)) else vapply(value_at, function(v) sum(v >= breaks) / max(1, length(breaks)), 0)
m$rings$fill <- ramp_hex(0.12 + 0.88 * ifelse(is.na(tone), 0, tone[m$rings$feature]))
m$rings$fill[is.na(value_at[m$rings$feature])] <- grey_col
p <- ggplot(m$rings, aes(x, y, group = piece, subgroup = ring)) + geom_polygon(aes(fill = I(fill)), colour = "white", linewidth = 0.2) + coord_equal() +
labs(title = paste(value_col, "by", region_col)) + theme_cs + theme_map
}
print(p)
Needs ggplot2 · reads choropleth-demo.csv · app theme from the optional codesplashr helper
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
# Point map — Codesplash Chart Lab (recipe "point-map")# controls: basemap=us-states, size=2.5
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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 pixels
traces = region_traces(base, project, lambda i: GREY, lambda col: "outlines", "white") if base is not None else []
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)
traces.append(go.Scattergl(x=xy[mask, 0], y=xy[mask, 1], mode="markers", name=g or "points", marker=dict(size=2 * SIZE, opacity=0.75, color=PALETTE[k % len(PALETTE)], symbol=SERIES_MARKERS[k % 8]))) # shape per group, as in the app
fig = go.Figure(traces)
fig.update_layout(**MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads point-map-demo.csv · app theme from the optional codesplash helper
# Point map — Codesplash Chart Lab (recipe "point-map")# controls: basemap=us-states, size=2.5
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("point-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["format"]] <- factor(df[["format"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
lon_col <- "longitude"
lat_col <- "latitude"
color_col <- "format"
boundaries_file <- "point-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "us"
base <- if (TRUE) load_map(boundaries_file, scope) else NULL
d <- df[!is.na(df[[lon_col]]) & !is.na(df[[lat_col]]) & abs(df[[lat_col]]) <= 90, , drop = FALSE]
project <- if (!is.null(base)) base$project else make_projection(d[[lon_col]], d[[lat_col]], scope)
d <- cbind(d, project(d[[lon_col]], d[[lat_col]]))
outlines <- if (!is.null(base)) geom_polygon(data = base$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, colour = "white", linewidth = 0.2, alpha = 0.35) else NULL
d$group <- if (!is.null(color_col)) as.character(d[[color_col]]) else "points"
p <- ggplot() + outlines + geom_point(data = d, aes(x, y, colour = group, shape = group), size = 1.75, alpha = 0.75) + # shape per group, as in the app
scale_colour_manual(values = rep(cs_cat, length.out = length(unique(d$group))), name = color_col, guide = if (is.null(color_col)) "none" else "legend") +
scale_shape_manual(values = rep(cs_shapes, length.out = length(unique(d$group))), name = color_col, guide = if (is.null(color_col)) "none" else "legend") + coord_equal() + theme_cs + theme_map
print(p)
Needs ggplot2 · reads point-map-demo.csv · app theme from the optional codesplashr helper
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
# Bubble map — Codesplash Chart Lab (recipe "bubble-map")# controls: basemap=us-states, maxRadius=18
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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 pixels; 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])
traces = region_traces(base, project, lambda i: GREY, lambda col: "outlines", "white") if base is not None else []
for k, g in enumerate(levels):
idx = [i for i in order if labels[i] == g]
traces.append(go.Scatter(x=xy[idx, 0], y=xy[idx, 1], mode="markers", name=g, text=[f"{v[i]:.4g}" for i in idx], hoverinfo="text+name",
marker=dict(size=2 * r[idx], opacity=0.55, color=PALETTE[k % len(PALETTE)], symbol=SERIES_MARKERS[k % 8], line=dict(width=1, color=PALETTE[k % len(PALETTE)])))) # shape per group, as in the app
fig = go.Figure(traces)
fig.update_layout(title=f"{SIZE} at each location", **MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads bubble-map-demo.csv · app theme from the optional codesplash helper
# Bubble map — Codesplash Chart Lab (recipe "bubble-map")# controls: basemap=us-states, maxRadius=18
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("bubble-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
lon_col <- "longitude"
lat_col <- "latitude"
size_col <- "orders (k)"
color_col <- "region"
boundaries_file <- "bubble-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "us"
base <- if (TRUE) load_map(boundaries_file, scope) else NULL
d <- df[!is.na(df[[lon_col]]) & !is.na(df[[lat_col]]) & abs(df[[lat_col]]) <= 90, , drop = FALSE]
project <- if (!is.null(base)) base$project else make_projection(d[[lon_col]], d[[lat_col]], scope)
d <- cbind(d, project(d[[lon_col]], d[[lat_col]]))
outlines <- if (!is.null(base)) geom_polygon(data = base$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, colour = "white", linewidth = 0.2, alpha = 0.35) else NULL
r_max <- 12.6 # largest radius; area ∝ value
d <- d[!is.na(d[[size_col]]), , drop = FALSE]
d <- d[order(-d[[size_col]]), , drop = FALSE] # largest first, so small bubbles stay visible
d$group <- if (!is.null(color_col)) as.character(d[[color_col]]) else "all"
d$area <- pmax(d[[size_col]], 0)
p <- ggplot() + outlines + geom_point(data = d, aes(x, y, size = area, colour = group, shape = group), alpha = 0.55) + # shape per group, as in the app
scale_size_area(max_size = 2 * r_max, name = size_col) +
scale_colour_manual(values = rep(cs_cat, length.out = length(unique(d$group))), name = color_col, guide = if (is.null(color_col)) "none" else "legend") +
scale_shape_manual(values = rep(cs_shapes, length.out = length(unique(d$group))), name = color_col, guide = if (is.null(color_col)) "none" else "legend") +
coord_equal() + labs(title = paste(size_col, "at each location")) + theme_cs + theme_map
print(p)
Needs ggplot2 · reads bubble-map-demo.csv · app theme from the optional codesplashr helper
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
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")# controls: basemap=us-states, radius=10
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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())
traces = region_traces(base, project, lambda i: GREY, lambda col: "outlines", "white") if base is not None else []
xs, ys = [], []
for cx, cy, _v in bins:
pts = hexagon(cx, cy, r * 0.96)
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
traces.append(go.Scatter(x=bins[:, 0], y=bins[:, 1], mode="markers", name=WEIGHT or "points", text=[f"{v:.4g}" for v in bins[:, 2]], hoverinfo="text",
marker=dict(symbol="hexagon", size=14, color=np.sqrt(np.maximum(bins[:, 2], 0)) / math.sqrt(peak), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], showscale=False)))
fig = go.Figure(traces)
fig.update_layout(title=f"{WEIGHT or 'points'} per hexagon (colour on a square-root scale)", **MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads hexbin-map-demo.csv · app theme from the optional codesplash helper
# Hex-bin map — Codesplash Chart Lab (recipe "hexbin-map")# controls: basemap=us-states, radius=10
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("hexbin-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
hexbin_points <- function(x, y, w, r) {
# Pointy-top hexagon bins of radius r (d3-hexbin's layout): centres and summed weights.
dx <- r * 2 * sin(pi / 3); dy <- r * 1.5
py <- y / dy; pj <- round(py)
px <- x / dx - (pj %% 2) / 2; pi_ <- round(px)
py1 <- py - pj
for (i in which(abs(py1) * 3 > 1)) {
px1 <- px[i] - pi_[i]
pi2 <- pi_[i] + (if (px[i] < pi_[i]) -1 else 1) / 2
pj2 <- pj[i] + (if (py[i] < pj[i]) -1 else 1)
if (px1^2 + py1[i]^2 > (px[i] - pi2)^2 + (py[i] - pj2)^2) {
pi_[i] <- pi2 + (if (pj[i] %% 2 == 1) 1 else -1) / 2
pj[i] <- pj2
}
}
key <- paste(pi_, pj)
out <- stats::aggregate(w, list(key = key), sum)
first <- match(out$key, key)
data.frame(cx = (pi_[first] + (pj[first] %% 2) / 2) * dx, cy = pj[first] * dy, value = out$x)
}
lon_col <- "longitude"
lat_col <- "latitude"
weight_col <- NULL
boundaries_file <- "hexbin-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "us"
base <- if (TRUE) load_map(boundaries_file, scope) else NULL
d <- df[!is.na(df[[lon_col]]) & !is.na(df[[lat_col]]) & abs(df[[lat_col]]) <= 90, , drop = FALSE]
project <- if (!is.null(base)) base$project else make_projection(d[[lon_col]], d[[lat_col]], scope)
d <- cbind(d, project(d[[lon_col]], d[[lat_col]]))
outlines <- if (!is.null(base)) geom_polygon(data = base$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, colour = "white", linewidth = 0.2, alpha = 0.35) else NULL
w <- if (!is.null(weight_col)) d[[weight_col]] else rep(1, nrow(d))
r <- diff(range(d$x)) * 0.0161290322581 # the control's radius at a 640 px chart
bins <- hexbin_points(d$x, d$y, w, r)
angles <- (0:5) * pi / 3
hexes <- do.call(rbind, lapply(seq_len(nrow(bins)), function(i) data.frame(id = i, value = bins$value[i], hx = bins$cx[i] + 0.96 * r * sin(angles), hy = bins$cy[i] - 0.96 * r * cos(angles))))
peak <- max(1, bins$value)
p <- ggplot() + outlines + geom_polygon(data = hexes, aes(hx, hy, group = id, fill = sqrt(pmax(value, 0)) / sqrt(peak))) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], name = if (is.null(weight_col)) "points (√ scale)" else paste(weight_col, "(√ scale)")) + coord_equal() + theme_cs + theme_map
print(p)
Needs ggplot2 · reads hexbin-map-demo.csv · app theme from the optional codesplashr helper
Read each line as a link between neighbouring regions.
Check regions with very few or very many links.
Islands, with no link, need a decision before you test.
1Callout 1: A link between two regions.
2Callout 2: Many links in a dense area.
3Callout 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
# Neighbour graph — Codesplash Chart Lab (recipe "neighbor-graph")# controls: boundaries=us-states
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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])
if features is None:
counts = pd.concat([d[FROM], d[TO]]).astype(str).value_counts().sort_values().tail(40)
fig = go.Figure(go.Bar(x=counts.values, y=counts.index, orientation="h", marker_color=PALETTE[0]))
fig.update_layout(xaxis_title="neighbours")
else:
centres = [centroid_of(f, project) for f in features]
xs, ys, 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
xs += [centres[a][0], centres[b][0], None]
ys += [centres[a][1], centres[b][1], None]
used |= {a, b}
traces = region_traces(features, project, lambda i: GREY, lambda col: "regions", "white")
traces.append(go.Scatter(x=xs, y=ys, mode="lines", name="neighbours", line=dict(color=PALETTE[0], width=1), hoverinfo="skip"))
traces.append(go.Scatter(x=[centres[i][0] for i in used], y=[centres[i][1] for i in used], mode="markers", name="regions with neighbours", marker=dict(size=6, color=PALETTE[0]), text=[features[i]["name"] for i in used], hoverinfo="text"))
fig = go.Figure(traces)
fig.update_layout(title="Which regions are neighbours", **MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads neighbor-graph-demo.csv · app theme from the optional codesplash helper
# Neighbour graph — Codesplash Chart Lab (recipe "neighbor-graph")# controls: boundaries=us-states
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("neighbor-graph-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
df[["neighbour"]] <- factor(df[["neighbour"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
centroid_of <- function(rings, i) {
# Area-weighted centroid of the feature's largest ring, in projected coordinates.
parts <- split(rings[rings$feature == i, ], rings$ring[rings$feature == i])
best <- c(NA_real_, NA_real_); best_area <- -1
for (t in parts) {
n <- nrow(t); j <- c(2:n, 1)
cross <- t$x * t$y[j] - t$x[j] * t$y
a <- sum(cross)
if (a != 0 && abs(a) > best_area) {
best <- c(sum((t$x + t$x[j]) * cross), sum((t$y + t$y[j]) * cross)) / (3 * a)
best_area <- abs(a)
}
}
best
}
from_col <- "state"
to_col <- "neighbour"
boundaries_file <- "neighbor-graph-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
m <- load_map(boundaries_file, "us")
d <- df[!is.na(df[[from_col]]) & !is.na(df[[to_col]]), , drop = FALSE]
if (is.null(m)) {
tab <- sort(table(c(as.character(d[[from_col]]), as.character(d[[to_col]]))))
counts <- utils::tail(data.frame(region = factor(names(tab), levels = names(tab)), n = as.vector(tab)), 40)
p <- ggplot(counts, aes(n, region)) + geom_col(fill = cs_cat[1]) + labs(x = "neighbours", y = NULL) + theme_cs
} else {
centres <- t(vapply(seq_along(m$features), function(i) centroid_of(m$rings, i), c(0, 0)))
a <- match_regions(m$features, d[[from_col]]); b <- match_regions(m$features, d[[to_col]])
keep <- !is.na(a) & !is.na(b) & !is.na(centres[a, 1]) & !is.na(centres[b, 1])
links <- data.frame(x0 = centres[a[keep], 1], y0 = centres[a[keep], 2], x1 = centres[b[keep], 1], y1 = centres[b[keep], 2])
nodes <- as.data.frame(centres[unique(c(a[keep], b[keep])), , drop = FALSE]); names(nodes) <- c("x", "y")
p <- ggplot() + geom_polygon(data = m$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, alpha = 0.35, colour = "white", linewidth = 0.2) +
geom_segment(data = links, aes(x0, y0, xend = x1, yend = y1), colour = cs_cat[1], alpha = 0.7) + geom_point(data = nodes, aes(x, y), colour = cs_cat[1], size = 1.4) +
coord_equal() + labs(title = "Which regions are neighbours") + theme_cs + theme_map
}
print(p)
Needs ggplot2 · reads neighbor-graph-demo.csv · app theme from the optional codesplashr helper
Read High-High and Low-Low as clusters: a site and its neighbours are alike.
Read High-Low and Low-High as spatial outliers: a site unlike its neighbours.
Grey sites did not pass the adjusted significance level; the faintest have no data.
1Callout 1: A High-High cluster: high values among high neighbours.
2Callout 2: A Low-Low cluster.
3Callout 3: Not significant after the correction.
4Callout 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
# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")# controls: boundaries=us-states
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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))
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])])
lab = pts[LABEL].astype(str).to_numpy()
traces = [go.Scatter(x=xy[lab == p, 0], y=xy[lab == p, 1], mode="markers", name=f"{p} ({labels.count(p)})", text=pts[SITE].astype(str).to_numpy()[lab == p], hoverinfo="text+name", marker=dict(size=9, color=PATTERN_COLOURS.get(p, GREY))) for p in present]
fig = go.Figure(traces)
fig.update_layout(**MAP_LAYOUT)
elif features is None:
v = d[VALUE].to_numpy(dtype=float)
order = np.argsort(v)[-40:]
fig = go.Figure(go.Bar(x=v[order], y=d[SITE].astype(str).to_numpy()[order], orientation="h", marker_color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order]))
fig.update_layout(xaxis_title=VALUE)
else:
names = {PATTERN_COLOURS.get(p, GREY): f"{p} ({labels.count(p)})" for p in present}
fig = go.Figure(region_traces(features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, lambda col: names.get(col, "No data"), "white"))
fig.update_layout(**MAP_LAYOUT)
fig.update_layout(title=f"Local spatial patterns of {VALUE}")
fig.show()
Needs pandas, numpy, plotly · reads lisa-map-demo.csv · app theme from the optional codesplash helper
# Local Moran cluster map (LISA) — Codesplash Chart Lab (recipe "lisa-map")# controls: boundaries=us-states
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("lisa-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
df[["pattern"]] <- factor(df[["pattern"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
pattern_order <- c("High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant")
blend <- function(a, b, t) grDevices::rgb(grDevices::colorRamp(c(a, b))(t), maxColorValue = 255)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
pattern_colours <- c("High-High" = div_ramp[1], "Hot spot" = div_ramp[1], "High-Low" = blend(div_ramp[2], div_ramp[1], 0.45), "Low-Low" = div_ramp[3], "Cold spot" = div_ramp[3],
"Low-High" = blend(div_ramp[2], div_ramp[3], 0.45), "High variability" = cs_cat[4], "Not significant" = grey_col)
site_col <- "state"
value_col <- "rate (simulated)"
label_col <- "pattern"
stat_col <- "local Moran's I"
p_adj_col <- "adjusted p"
lon_col <- NULL
lat_col <- NULL
boundaries_file <- "lisa-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d <- df[!is.na(df[[site_col]]) & !is.na(df[[label_col]]), , drop = FALSE]
d$pattern <- as.character(d[[label_col]])
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged <- d[d$pattern != "Not significant", c(site_col, value_col, stat_col, p_adj_col, "pattern"), drop = FALSE]
print(if (is.null(p_adj_col)) flagged else flagged[order(flagged[[p_adj_col]]), , drop = FALSE], row.names = FALSE)
present <- c(intersect(pattern_order, d$pattern), sort(setdiff(d$pattern, pattern_order)))
counts <- vapply(present, function(l) sum(d$pattern == l), 0)
legend_labels <- stats::setNames(paste0(present, " (", counts, ")"), present)
fills <- c(pattern_colours, stats::setNames(rep(grey_col, length(setdiff(present, names(pattern_colours)))), setdiff(present, names(pattern_colours))))
m <- if (is.null(lon_col) || is.null(lat_col)) load_map(boundaries_file, "us") else NULL
if (!is.null(lon_col) && !is.null(lat_col)) {
pts <- d[!is.na(d[[lon_col]]) & !is.na(d[[lat_col]]), , drop = FALSE]
pts <- cbind(pts, make_projection(pts[[lon_col]], pts[[lat_col]], "other")(pts[[lon_col]], pts[[lat_col]]))
p <- ggplot(pts, aes(x, y, fill = pattern)) + geom_point(shape = 21, size = 3, colour = "white") + coord_equal() + theme_cs + theme_map
} else if (is.null(m)) {
d <- utils::tail(d[order(d[[value_col]]), , drop = FALSE], 40)
d$site_label <- factor(as.character(d[[site_col]]), levels = as.character(d[[site_col]]))
p <- ggplot(d, aes(.data[[value_col]], site_label, fill = pattern)) + geom_col() + labs(x = value_col, y = NULL) + theme_cs + theme(legend.position = "bottom")
} else {
fi <- match_regions(m$features, d[[site_col]])
label_at <- rep(NA_character_, length(m$features))
label_at[fi[!is.na(fi)]] <- d$pattern[!is.na(fi)]
m$rings$pattern <- label_at[m$rings$feature]
p <- ggplot(m$rings, aes(x, y, group = piece, subgroup = ring, fill = pattern)) + geom_polygon(colour = "white", linewidth = 0.2) + coord_equal() + theme_cs + theme_map
}
p <- p + scale_fill_manual(values = fills, breaks = present, labels = legend_labels, name = NULL, na.value = blend(grey_col, "#ffffff", 0.6)) + labs(title = paste("Local spatial patterns of", value_col))
print(p)
Needs ggplot2 · reads lisa-map-demo.csv · app theme from the optional codesplashr helper
Read a hot spot as high values sitting together, and a cold spot as low values sitting together.
Check the legend: LOSH marks high variability instead, which says nothing about the level.
Grey sites did not pass the adjusted significance level; the faintest have no data.
1Callout 1: A hot spot: this area's values add up higher than chance.
2Callout 2: A cold spot.
3Callout 3: Not significant after the correction.
4Callout 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
# Hot-spot map — Codesplash Chart Lab (recipe "hotspot-map")# controls: boundaries=us-states
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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))
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])])
lab = pts[LABEL].astype(str).to_numpy()
traces = [go.Scatter(x=xy[lab == p, 0], y=xy[lab == p, 1], mode="markers", name=f"{p} ({labels.count(p)})", text=pts[SITE].astype(str).to_numpy()[lab == p], hoverinfo="text+name", marker=dict(size=9, color=PATTERN_COLOURS.get(p, GREY))) for p in present]
fig = go.Figure(traces)
fig.update_layout(**MAP_LAYOUT)
elif features is None:
v = d[VALUE].to_numpy(dtype=float)
order = np.argsort(v)[-40:]
fig = go.Figure(go.Bar(x=v[order], y=d[SITE].astype(str).to_numpy()[order], orientation="h", marker_color=[PATTERN_COLOURS.get(labels[i], GREY) for i in order]))
fig.update_layout(xaxis_title=VALUE)
else:
names = {PATTERN_COLOURS.get(p, GREY): f"{p} ({labels.count(p)})" for p in present}
fig = go.Figure(region_traces(features, project, lambda i: PATTERN_COLOURS.get(label_at[i], GREY) if i in label_at else NO_DATA, lambda col: names.get(col, "No data"), "white"))
fig.update_layout(**MAP_LAYOUT)
fig.update_layout(title=f"Local spatial patterns of {VALUE}")
fig.show()
Needs pandas, numpy, plotly · reads hotspot-map-demo.csv · app theme from the optional codesplash helper
# Hot-spot map — Codesplash Chart Lab (recipe "hotspot-map")# controls: boundaries=us-states
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("hotspot-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
df[["pattern"]] <- factor(df[["pattern"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
# A site's pattern comes from the analysis: only sites past the adjusted significance level take one.
pattern_order <- c("High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant")
blend <- function(a, b, t) grDevices::rgb(grDevices::colorRamp(c(a, b))(t), maxColorValue = 255)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
pattern_colours <- c("High-High" = div_ramp[1], "Hot spot" = div_ramp[1], "High-Low" = blend(div_ramp[2], div_ramp[1], 0.45), "Low-Low" = div_ramp[3], "Cold spot" = div_ramp[3],
"Low-High" = blend(div_ramp[2], div_ramp[3], 0.45), "High variability" = cs_cat[4], "Not significant" = grey_col)
site_col <- "state"
value_col <- "rate (simulated)"
label_col <- "pattern"
stat_col <- "Gi* z"
p_adj_col <- "adjusted p"
lon_col <- NULL
lat_col <- NULL
boundaries_file <- "hotspot-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
d <- df[!is.na(df[[site_col]]) & !is.na(df[[label_col]]), , drop = FALSE]
d$pattern <- as.character(d[[label_col]])
# The flagged sites with their local statistic and adjusted p, which the map's colours can't show.
flagged <- d[d$pattern != "Not significant", c(site_col, value_col, stat_col, p_adj_col, "pattern"), drop = FALSE]
print(if (is.null(p_adj_col)) flagged else flagged[order(flagged[[p_adj_col]]), , drop = FALSE], row.names = FALSE)
present <- c(intersect(pattern_order, d$pattern), sort(setdiff(d$pattern, pattern_order)))
counts <- vapply(present, function(l) sum(d$pattern == l), 0)
legend_labels <- stats::setNames(paste0(present, " (", counts, ")"), present)
fills <- c(pattern_colours, stats::setNames(rep(grey_col, length(setdiff(present, names(pattern_colours)))), setdiff(present, names(pattern_colours))))
m <- if (is.null(lon_col) || is.null(lat_col)) load_map(boundaries_file, "us") else NULL
if (!is.null(lon_col) && !is.null(lat_col)) {
pts <- d[!is.na(d[[lon_col]]) & !is.na(d[[lat_col]]), , drop = FALSE]
pts <- cbind(pts, make_projection(pts[[lon_col]], pts[[lat_col]], "other")(pts[[lon_col]], pts[[lat_col]]))
p <- ggplot(pts, aes(x, y, fill = pattern)) + geom_point(shape = 21, size = 3, colour = "white") + coord_equal() + theme_cs + theme_map
} else if (is.null(m)) {
d <- utils::tail(d[order(d[[value_col]]), , drop = FALSE], 40)
d$site_label <- factor(as.character(d[[site_col]]), levels = as.character(d[[site_col]]))
p <- ggplot(d, aes(.data[[value_col]], site_label, fill = pattern)) + geom_col() + labs(x = value_col, y = NULL) + theme_cs + theme(legend.position = "bottom")
} else {
fi <- match_regions(m$features, d[[site_col]])
label_at <- rep(NA_character_, length(m$features))
label_at[fi[!is.na(fi)]] <- d$pattern[!is.na(fi)]
m$rings$pattern <- label_at[m$rings$feature]
p <- ggplot(m$rings, aes(x, y, group = piece, subgroup = ring, fill = pattern)) + geom_polygon(colour = "white", linewidth = 0.2) + coord_equal() + theme_cs + theme_map
}
p <- p + scale_fill_manual(values = fills, breaks = present, labels = legend_labels, name = NULL, na.value = blend(grey_col, "#ffffff", 0.6)) + labs(title = paste("Local spatial patterns of", value_col))
print(p)
Needs ggplot2 · reads hotspot-map-demo.csv · app theme from the optional codesplashr helper
Read x as each site's standardized value and y as the average of its neighbours.
Read the slope of the line as Moran's I: steeper means neighbours resemble each other more.
Top right and bottom left hold sites like their neighbours; the other two corners hold outliers.
1Callout 1: High-High: high sites among high neighbours.
2Callout 2: Low-Low: low sites among low neighbours.
3Callout 3: Low-High: a low site among high neighbours.
4Callout 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
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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())
sites = d[SITE].astype(str).to_numpy() if SITE else np.array([""] * len(d))
fig = go.Figure()
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
fig.add_trace(go.Scatter(x=x[mask], y=y[mask], mode="markers", name=f"{p} ({mask.sum()})", text=sites[mask], marker=dict(size=7, color=REF if p == "Not significant" else PATTERN_COLOURS.get(p, GREY))))
else:
fig.add_trace(go.Scatter(x=x, y=y, mode="markers", name="sites", text=sites, marker=dict(size=7, opacity=0.65, color=PALETTE[0])))
fig.add_trace(go.Scatter(x=[cx - lim, cx + lim], y=[cy - lim * slope, cy + lim * slope], mode="lines", name=f"slope {slope:.3f}", line=dict(color=REF, width=1.5)))
fig.add_vline(x=cx, line_dash="dash", line_color=REF)
fig.add_hline(y=cy, line_dash="dash", line_color=REF)
fig.update_layout(xaxis_title=X, yaxis_title=Y, xaxis_range=[cx - lim, cx + lim], yaxis_range=[cy - lim, cy + lim])
fig.show()
Needs pandas, numpy, plotly · reads moran-scatter-demo.csv · app theme from the optional codesplash helper
# Moran scatterplot — Codesplash Chart Lab (recipe "moran-scatter")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("moran-scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["state"]] <- factor(df[["state"]])
df[["pattern"]] <- factor(df[["pattern"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
pattern_order <- c("High-High", "Low-Low", "High-Low", "Low-High", "Hot spot", "Cold spot", "High variability", "Not significant")
blend <- function(a, b, t) grDevices::rgb(grDevices::colorRamp(c(a, b))(t), maxColorValue = 255)
# High values on the warm end of the ramp, as on most published LISA maps; outliers are paler.
pattern_colours <- c("High-High" = div_ramp[1], "Hot spot" = div_ramp[1], "High-Low" = blend(div_ramp[2], div_ramp[1], 0.45), "Low-Low" = div_ramp[3], "Cold spot" = div_ramp[3],
"Low-High" = blend(div_ramp[2], div_ramp[3], 0.45), "High variability" = cs_cat[4], "Not significant" = grey_col)
x_col <- "rate (standardized)"
y_col <- "average of neighbours"
site_col <- "state"
label_col <- "pattern"
d <- df[!is.na(df[[x_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
x <- d[[x_col]]; y <- d[[y_col]]
cx <- mean(x); cy <- mean(y)
given <- NULL # the analysis's Moran's I, when it reports one
slope <- if (is.null(given)) sum((x - cx) * (y - cy)) / sum((x - cx)^2) else given
lim <- 1.1 * max(abs(x - cx), abs(y - cy))
quadrants <- data.frame(tx = c(cx + lim, cx - lim, cx - lim, cx + lim), ty = c(cy + lim, cy + lim, cy - lim, cy - lim), hj = c(1, 0, 0, 1), vj = c(1, 1, 0, 0), name = c("High-High", "Low-High", "Low-Low", "High-Low"))
p <- ggplot(d, aes(.data[[x_col]], .data[[y_col]])) + geom_vline(xintercept = cx, linetype = "dashed", colour = ref_col) + geom_hline(yintercept = cy, linetype = "dashed", colour = ref_col) +
geom_text(data = quadrants, aes(tx, ty, label = name, hjust = hj, vjust = vj), size = 2.8, colour = ref_col, inherit.aes = FALSE)
if (!is.null(label_col)) {
d$pattern <- as.character(d[[label_col]])
shown <- pattern_colours; shown["Not significant"] <- ref_col
p <- p + geom_point(data = d, aes(colour = pattern), size = 2) + scale_colour_manual(values = shown, name = NULL)
} else {
p <- p + geom_point(colour = cs_cat[1], alpha = 0.65, size = 2)
}
if (!is.null(site_col)) { # Name the flagged sites or, without patterns, the five furthest from the centre.
named <- if (!is.null(label_col)) which(as.character(d[[label_col]]) != "Not significant") else utils::tail(order(sqrt((x - cx)^2 + (y - cy)^2)), 5)
p <- p + geom_text(data = d[named, , drop = FALSE], aes(label = .data[[site_col]]), size = 2.4, hjust = -0.15, vjust = -0.3, colour = ref_col)
}
p <- p + geom_abline(intercept = cy - slope * cx, slope = slope, colour = ref_col, linewidth = 0.7) + coord_cartesian(xlim = c(cx - lim, cx + lim), ylim = c(cy - lim, cy + lim)) +
labs(x = x_col, y = y_col, title = sprintf("Slope %.3f", slope)) + theme_cs
print(p)
Needs ggplot2 · reads moran-scatter-demo.csv · app theme from the optional codesplashr helper
Read x as distance and y as how far the points are from random at that distance.
Above the envelope, points are closer together than random; below it, more evenly spaced.
Use the dashed global envelope to judge the whole curve, and the shaded band for one chosen distance.
1Callout 1: Above the global envelope: clustered at these distances.
2Callout 2: Pointwise envelope from random patterns.
3Callout 3: Global envelope: the test of the whole curve.
4Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if LO and HI:
fig.add_trace(go.Scatter(x=np.r_[r, r[::-1]], y=np.r_[d[HI] - shift, (d[LO] - shift)[::-1]], fill="toself", mode="none", fillcolor="rgba(120,150,200,0.25)", name="pointwise envelope"))
if LO_G and HI_G:
fig.add_trace(go.Scatter(x=r, y=d[HI_G] - shift, mode="lines", name="global envelope", line=dict(color=GREY, dash="dash", width=1)))
fig.add_trace(go.Scatter(x=r, y=d[LO_G] - shift, mode="lines", showlegend=False, line=dict(color=GREY, dash="dash", width=1)))
fig.add_trace(go.Scatter(x=r, y=np.zeros_like(r) if CENTRED else r, mode="lines", name="random pattern", line=dict(color=REF, dash="dot")))
fig.add_trace(go.Scatter(x=r, y=d[L] - shift, mode="lines", name="observed", line=dict(color=PALETTE[0], width=2)))
fig.update_layout(xaxis_title=R, yaxis_title="L(r) − r" if CENTRED else "L(r)")
fig.show()
Needs pandas, numpy, plotly · reads ripley-envelope-demo.csv · app theme from the optional codesplash helper
# Ripley's L with envelopes — Codesplash Chart Lab (recipe "ripley-envelope")# controls: centred=true, alpha=0.05
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ripley-envelope-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
r_col <- "distance r"
l_col <- "L(r)"
lo_col <- "pointwise low"
hi_col <- "pointwise high"
lo_g_col <- "global low"
hi_g_col <- "global high"
centred <- TRUE # L(r) − r: a random pattern is the flat line at 0
d <- df[!is.na(df[[r_col]]) & !is.na(df[[l_col]]), , drop = FALSE]
d <- d[order(d[[r_col]]), , drop = FALSE]
d$rr <- d[[r_col]]
shift <- if (centred) d$rr else 0
d$observed <- d[[l_col]] - shift
d$random <- if (centred) 0 else d$rr
p <- ggplot(d, aes(rr))
if (!is.null(lo_col) && !is.null(hi_col)) {
d$low <- d[[lo_col]] - shift; d$high <- d[[hi_col]] - shift
p <- p + geom_ribbon(data = d, aes(ymin = low, ymax = high), fill = cs_cat[1], alpha = 0.16)
}
if (!is.null(lo_g_col) && !is.null(hi_g_col)) {
d$low_g <- d[[lo_g_col]] - shift; d$high_g <- d[[hi_g_col]] - shift
p <- p + geom_line(data = d, aes(y = low_g), linetype = "dashed", colour = grey_col) + geom_line(data = d, aes(y = high_g), linetype = "dashed", colour = grey_col)
}
p <- p + geom_line(data = d, aes(y = random), linetype = "dotted", colour = ref_col) + geom_line(data = d, aes(y = observed), colour = cs_cat[1], linewidth = 0.9) +
labs(x = r_col, y = if (centred) "L(r) − r" else "L(r)") + theme_cs
print(p)
Needs ggplot2 · reads ripley-envelope-demo.csv · app theme from the optional codesplashr helper
Read x as the distance between two sites and y as how much they differ on average.
Follow the rise: near sites are more alike than far ones until the curve levels off at the sill.
Read the distance where it levels off as the range, and the height at distance zero as the nugget.
1Callout 1: The nugget: difference between sites at almost no distance.
2Callout 2: The sill: pairs this far apart are no more alike than any two sites.
3Callout 3: Band from shuffled values: points inside it show no spatial structure.
4Callout 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
# Semivariogram — Codesplash Chart Lab (recipe "variogram")# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
if LO and HI:
fig.add_trace(go.Scatter(x=np.r_[h, h[::-1]], y=np.r_[d[HI], d[LO][::-1]], fill="toself", mode="none", fillcolor="rgba(120,150,200,0.22)", name="shuffled values"))
if VARIANCE is not None:
fig.add_hline(y=VARIANCE, line_dash="dash", line_color=REF)
if FITTED:
fig.add_trace(go.Scatter(x=h, y=d[FITTED], mode="lines", name="fitted model", line=dict(color=PALETTE[1], width=2)))
fig.add_trace(go.Scatter(x=h, y=d[GAMMA], mode="markers", name="semivariance (area = pairs)", marker=dict(size=6 + 10 * np.sqrt(area), color=PALETTE[0], opacity=0.75)))
fig.update_layout(xaxis_title=H, yaxis_title=GAMMA, xaxis_rangemode="tozero", yaxis_rangemode="tozero")
fig.show()
Needs pandas, numpy, plotly · reads variogram-demo.csv · app theme from the optional codesplash helper
# Semivariogram — Codesplash Chart Lab (recipe "variogram")# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("variogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
h_col <- "distance"
gamma_col <- "semivariance"
pairs_col <- "pairs"
lo_col <- "shuffled low"
hi_col <- "shuffled high"
fitted_col <- "fitted"
variance_line <- NULL # the data's variance, when the analysis reports it
d <- df[!is.na(df[[h_col]]) & !is.na(df[[gamma_col]]), , drop = FALSE]
d <- d[order(d[[h_col]]), , drop = FALSE]
d$pair_count <- if (!is.null(pairs_col)) d[[pairs_col]] else 1
p <- ggplot(d, aes(.data[[h_col]], .data[[gamma_col]]))
if (!is.null(lo_col) && !is.null(hi_col)) p <- p + geom_ribbon(aes(ymin = .data[[lo_col]], ymax = .data[[hi_col]]), fill = cs_cat[1], alpha = 0.14)
if (!is.null(variance_line)) p <- p + geom_hline(yintercept = variance_line, linetype = "dashed", colour = ref_col)
if (!is.null(fitted_col)) p <- p + geom_line(aes(y = .data[[fitted_col]]), colour = cs_cat[2], linewidth = 0.9)
p <- p + geom_point(aes(size = pair_count), colour = cs_cat[1], alpha = 0.75) + scale_size_area(max_size = 4.5, name = "pairs") + expand_limits(x = 0, y = 0) + labs(x = h_col, y = gamma_col) + theme_cs
print(p)
Needs ggplot2 · reads variogram-demo.csv · app theme from the optional codesplashr helper
Read the darkest band as where points are most concentrated.
Read the bands as shares of the map's own peak, so compare shapes between maps and not colours.
Try another bandwidth: a smaller one shows more local detail and a larger one merges clusters.
1Callout 1: The peak: the densest area.
2Callout 2: A second concentration.
3Callout 3: The lowest band: few points.
4Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 region_traces(features, project, fill_of, name_of, edge, width=0.5):
"""One filled trace per colour; fill_of(position) gives the colour and name_of(colour) its legend entry."""
groups = {}
for i, f in enumerate(features):
xs, ys = groups.setdefault(fill_of(i), ([], []))
for poly in polygons_of(f["geometry"]):
for ring in poly:
pts = [project(p[0], p[1]) for p in ring]
xs += [p[0] for p in pts] + [pts[0][0], None]
ys += [p[1] for p in pts] + [pts[0][1], None]
return [go.Scatter(x=xs, y=ys, mode="lines", fill="toself", fillcolor=colour, line=dict(color=edge, width=width), hoverinfo="name", name=name_of(colour)) for colour, (xs, ys) in groups.items()]
MAP_LAYOUT = dict(xaxis=dict(visible=False, scaleanchor="y"), yaxis=dict(visible=False))
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
traces = region_traces(base, project, lambda i: GREY, lambda col: "outlines", "white") if base is not None else []
traces.append(go.Contour(x=gx, y=gy, z=np.where(z < 0.142857142857, None, z), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]], opacity=0.62, contours=dict(start=0.142857142857, end=1, size=0.142857142857), line_width=0, colorbar=dict(title="share of peak")))
fig = go.Figure(traces)
fig.update_layout(title="Density of points, as a share of the peak", **MAP_LAYOUT)
fig.show()
Needs pandas, numpy, plotly · reads kde-map-demo.csv · app theme from the optional codesplash helper
# Kernel density map — Codesplash Chart Lab (recipe "kde-map")# controls: basemap=us-states, bandwidth=0.5, bands=6
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("kde-map-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
region_key <- function(s) {
# Ignore case, accents, punctuation and leading zeros (as the app does when matching regions).
t <- tolower(trimws(iconv(as.character(s), to = "ASCII//TRANSLIT", sub = "")))
t <- gsub("[[:space:]._-]+", " ", t)
ifelse(grepl("^[0-9]+$", t), sub("^0+(?=[0-9])", "", t, perl = TRUE), t)
}
read_boundaries <- function(path) {
fc <- jsonlite::read_json(path, simplifyVector = FALSE)
lapply(seq_along(fc$features), function(i) {
f <- fc$features[[i]]
fid <- if (is.null(f$id)) i else f$id
list(id = as.character(fid), name = as.character(if (is.null(f$properties$name)) fid else f$properties$name), geometry = f$geometry)
})
}
ring_table <- function(ring) data.frame(lon = vapply(ring, function(p) as.numeric(p[[1]]), 0), lat = vapply(ring, function(p) as.numeric(p[[2]]), 0))
polygons_of <- function(geometry) {
# Each polygon as its rings (outer first) in longitude and latitude.
if (is.null(geometry)) return(list())
if (geometry$type == "Polygon") return(list(geometry$coordinates))
if (geometry$type == "MultiPolygon") return(geometry$coordinates)
list()
}
feature_rings <- function(features) {
# One row per vertex: feature position, polygon and ring.
parts <- list()
for (i in seq_along(features)) {
polys <- polygons_of(features[[i]]$geometry)
for (p in seq_along(polys)) for (r in seq_along(polys[[p]])) {
tab <- ring_table(polys[[p]][[r]])
if (!nrow(tab)) next
tab$feature <- i; tab$piece <- paste(i, p); tab$ring <- paste(i, p, r)
parts[[length(parts) + 1]] <- tab
}
}
do.call(rbind, parts)
}
contiguous <- function(features) {
# Drop regions wholly outside the lower 48 states (the app draws Alaska and Hawaii as insets).
keep <- vapply(features, function(f) {
polys <- polygons_of(f$geometry)
pts <- do.call(rbind, lapply(polys, function(p) do.call(rbind, lapply(p, ring_table))))
!is.null(pts) && nrow(pts) > 0 && mean(pts$lon) > -126 && mean(pts$lon) < -66 && mean(pts$lat) > 24 && mean(pts$lat) < 50
}, TRUE)
features[keep]
}
match_regions <- function(features, keys) {
# Each key's feature position: by id, else by name.
ids <- region_key(vapply(features, function(f) f$id, ""))
nms <- region_key(vapply(features, function(f) f$name, ""))
k <- region_key(keys)
hit <- match(k, ids)
ifelse(is.na(hit), match(k, nms), hit)
}
make_projection <- function(lons, lats, scope) {
# Equal Earth for world extents, conic equal-area otherwise, scaled degrees for very small extents.
span <- max(lons) - min(lons)
rad <- pi / 180
if (scope == "world" || span > 120) {
return(function(lon, lat) {
th <- asin(sqrt(3) / 2 * sin(lat * rad)); t2 <- th^2; t6 <- t2^3
d <- 3 * (9 * 0.003796 * t6 * t2 + 7 * 0.000893 * t6 + 3 * -0.081106 * t2 + 1.340264)
data.frame(x = 2 * sqrt(3) * lon * rad * cos(th) / d, y = th * (0.003796 * t6 * t2 + 0.000893 * t6 - 0.081106 * t2 + 1.340264))
})
}
lat0 <- (min(lats) + max(lats)) / 2
if (span < 2) return(function(lon, lat) data.frame(x = lon * cos(lat0 * rad), y = lat))
lon0 <- if (scope == "us") -96 else (min(lons) + max(lons)) / 2
third <- (max(lats) - min(lats)) / 3
p1 <- rad * (if (scope == "us") 29.5 else min(lats) + third)
p2 <- rad * (if (scope == "us") 45.5 else max(lats) - third)
n <- (sin(p1) + sin(p2)) / 2
if (n == 0) n <- 1e-9
cc <- cos(p1)^2 + 2 * n * sin(p1)
function(lon, lat) {
rho <- sqrt(pmax(0, cc - 2 * n * sin(lat * rad))) / n
theta <- n * (lon - lon0) * rad
data.frame(x = rho * sin(theta), y = -rho * cos(theta))
}
}
load_map <- function(path, scope) {
# Features, rings and their projection, or NULL when the boundaries file isn't there.
if (!file.exists(path)) {
message("No boundaries file at ", path, ": drawing without the map. Point boundaries_file at a GeoJSON file for the regions.")
return(NULL)
}
features <- read_boundaries(path)
if (scope == "us") features <- contiguous(features)
rings <- feature_rings(features)
project <- make_projection(rings$lon, rings$lat, scope)
rings <- cbind(rings, project(rings$lon, rings$lat))
list(features = features, rings = rings, project = project)
}
theme_map <- theme(axis.title = element_blank(), axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank(), legend.position = "bottom")
density_grid <- function(x, y, w, adjust, nx = 160) {
# Gaussian kernel density on a grid over the points, as a share of the peak. Silverman: h = σ n^(−1/6).
sw <- sum(w); mx <- sum(w * x) / sw; my <- sum(w * y) / sw
sigma <- sqrt(sum(w * ((x - mx)^2 + (y - my)^2)) / (2 * sw))
h <- adjust * sigma * (sw^2 / sum(w^2))^(-1 / 6)
gx <- seq(min(x) - 3 * h, max(x) + 3 * h, length.out = nx)
ny <- max(2, as.integer(nx * (diff(range(y)) + 6 * h) / (diff(range(x)) + 6 * h)))
gy <- seq(min(y) - 3 * h, max(y) + 3 * h, length.out = ny)
kx <- exp(-outer(x, gx, "-")^2 / (2 * h^2)); ky <- exp(-outer(y, gy, "-")^2 / (2 * h^2))
z <- t(kx) %*% (w * ky)
grid <- expand.grid(gx = gx, gy = gy)
grid$density <- as.vector(z / max(z))
grid
}
lon_col <- "longitude"
lat_col <- "latitude"
weight_col <- NULL
boundaries_file <- "kde-map-boundaries.geojson" # GeoJSON with an id or properties.name for each region (Data → Map layers, or any file)
scope <- "us"
base <- if (TRUE) load_map(boundaries_file, scope) else NULL
d <- df[!is.na(df[[lon_col]]) & !is.na(df[[lat_col]]) & abs(df[[lat_col]]) <= 90, , drop = FALSE]
project <- if (!is.null(base)) base$project else make_projection(d[[lon_col]], d[[lat_col]], scope)
d <- cbind(d, project(d[[lon_col]], d[[lat_col]]))
outlines <- if (!is.null(base)) geom_polygon(data = base$rings, aes(x, y, group = piece, subgroup = ring), fill = grey_col, colour = "white", linewidth = 0.2, alpha = 0.35) else NULL
w <- if (!is.null(weight_col)) ifelse(is.na(d[[weight_col]]), 0, d[[weight_col]]) else rep(1, nrow(d))
grid <- density_grid(d$x, d$y, w, 0.5) # 1 is Silverman's rule, which blurs separate clusters together
levels <- (seq_len(6)) / 7
p <- ggplot() + outlines + geom_contour_filled(data = grid, aes(gx, gy, z = density), breaks = c(levels, 1.0001), alpha = 0.62) +
scale_fill_manual(values = grDevices::colorRampPalette(c(seq_ramp[1], seq_ramp[length(seq_ramp)]))(6), name = "share of peak", drop = FALSE) +
coord_equal() + labs(title = "Density of points, as a share of the peak") + theme_cs + theme_map
print(p)
Needs ggplot2 · reads kde-map-demo.csv · app theme from the optional codesplashr helper
Genetics
Genotype data: de Finetti diagrams, linkage disequilibrium, Manhattan plots and site frequency spectra.
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.
Points on the curve have the heterozygote share Hardy–Weinberg predicts; points below it have too few heterozygotes, points above too many.
With the band on, a point outside it fails the χ² test at that sample size; compare its colour with the QC verdict.
1Callout 1: All heterozygotes (AB) at the apex.
2Callout 2: The Hardy–Weinberg parabola.
3Callout 3: A marker below the curve: too few heterozygotes.
4Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
fig.add_scatter(x=[0, 1, 0.5, 0], y=[0, 0, H, 0], mode="lines", line=dict(color=REF, width=1), showlegend=False, hoverinfo="skip")
if N_BAND > 0:
k = np.sqrt(stats.chi2.isf(ALPHA, 1) / N_BAND) # 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))
fig.add_scatter(x=np.r_[q, q[::-1]], y=np.r_[H * hi, (H * lo)[::-1]], fill="toself", mode="none", fillcolor=PALETTE[0], opacity=0.2, name=f"{100 * (1 - ALPHA):g}% χ² band, n = {N_BAND}")
if PARABOLA:
fig.add_scatter(x=q, y=H * het, mode="lines", line=dict(color=REF, width=1.5), name="Hardy–Weinberg")
for i, g in enumerate(groups):
m = (d[GROUP].astype(str) == g).to_numpy() if GROUP else np.ones(len(d), bool)
text = d[LABEL].astype(str)[m] if LABEL else None
fig.add_scatter(x=x[m], y=y[m], mode="markers", text=text, name=g or "markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=7, opacity=0.85, line=dict(color="white", width=0.5)))
for tx, ty, name, anchor in ((-0.03, 0, AA, "right"), (1.03, 0, BB, "left"), (0.5, H + 0.04, AB, "center")):
fig.add_annotation(x=tx, y=ty, text=f"<b>{name}</b>", showarrow=False, xanchor=anchor)
fig.update_layout(xaxis=dict(range=[-0.18, 1.18], tickvals=[0, 0.25, 0.5, 0.75, 1], title="frequency of the second allele", zeroline=False),
yaxis=dict(range=[-0.08, H + 0.12], scaleanchor="x", visible=False))
fig.show()
Needs pandas, numpy, plotly, scipy · reads definetti-demo.csv · app theme from the optional codesplash helper
# De Finetti diagram (genotype frequencies) — Codesplash Chart Lab (recipe "definetti")# controls: parabola=true, n=0, alpha=0.05
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("definetti-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["marker"]] <- factor(df[["marker"]])
df[["HWE"]] <- factor(df[["HWE"]], levels = c("passes", "fails HWE"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
aa_col <- "AA"
ab_col <- "AB"
bb_col <- "BB"
label_col <- "marker"
group_col <- "HWE"
n_band <- 0; alpha <- 0.05; parabola <- TRUE # band n (0 = none), level, HWE curve
h <- sqrt(3) / 2 # AA at (0, 0), BB at (1, 0), AB at (1/2, h)
cnt <- sapply(c(aa_col, ab_col, bb_col), function(v) suppressWarnings(as.numeric(df[[v]])))
cnt <- matrix(cnt, ncol = 3)
tot <- rowSums(cnt)
keep <- !is.na(tot) & tot > 0 & rowSums(cnt < 0, na.rm = TRUE) == 0 # missing, negative or all-zero rows are left out
d <- df[keep, , drop = FALSE]; cnt <- cnt[keep, , drop = FALSE]; tot <- tot[keep]
d$x <- (cnt[, 3] + cnt[, 2] / 2) / tot # frequency of the second allele
d$y <- h * cnt[, 2] / tot
d$group <- if (!is.null(group_col)) factor(as.character(d[[group_col]]), levels = freq_levels(d[[group_col]], 50)) else factor("markers")
q <- seq(0, 1, length.out = 121)
het <- 2 * q * (1 - q) # Hardy–Weinberg heterozygote share
p <- ggplot() + geom_path(data = data.frame(x = c(0, 1, 0.5, 0), y = c(0, 0, h, 0)), aes(x, y), colour = ref_col)
if (n_band > 0) {
k <- sqrt(qchisq(alpha, 1, lower.tail = FALSE) / n_band) # AB = 2pq(1 ± sqrt(c/n)) (Cannings & Edwards 1968)
band <- data.frame(q = q, lo = h * pmax(0, het * (1 - k)), hi = h * pmin(het * (1 + k), 2 * pmin(q, 1 - q)))
p <- p + geom_ribbon(data = band, aes(x = q, ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.16)
}
if (parabola) p <- p + geom_line(data = data.frame(q = q, y = h * het), aes(q, y), colour = ref_col, linewidth = 0.7)
p <- p + geom_point(data = d, aes(x, y, colour = group), size = 1.8, alpha = 0.85) +
scale_colour_manual(values = cs_cat[seq_len(nlevels(d$group))], name = NULL) +
annotate("text", x = -0.03, y = 0, label = aa_col, hjust = 1, fontface = "bold") +
annotate("text", x = 1.03, y = 0, label = bb_col, hjust = 0, fontface = "bold") +
annotate("text", x = 0.5, y = h + 0.04, label = ab_col, vjust = 0, fontface = "bold") +
scale_x_continuous(breaks = c(0, 0.25, 0.5, 0.75, 1)) +
coord_equal(xlim = c(-0.18, 1.18), ylim = c(-0.05, h + 0.1)) +
labs(x = "frequency of the second allele", y = NULL) + theme_cs +
theme(axis.text.y = element_blank(), panel.grid = element_blank())
if (!is.null(label_col) && nrow(d) <= 12) p <- p + geom_text(data = d, aes(x, y, label = .data[[label_col]]), hjust = -0.25, size = 2.8)
print(p)
Needs ggplot2 · reads definetti-demo.csv · app theme from the optional codesplashr helper
Read each cell as one pair of markers: darker means stronger linkage disequilibrium (r² or |D′| near 1).
In the triangle, follow a cell up its two diagonals to the markers it pairs; cells next to the marker row pair neighbours.
Dark triangles along the top are blocks of markers inherited together; a light band between them marks where recombination broke the link.
1Callout 1: A block: neighbouring markers in strong LD.
2Callout 2: Cells far down pair distant markers.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
from plotly.colors import sample_colorscale
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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)
scale = [[0, SEQ[0]], [1, SEQ[-1]]]
fig = go.Figure()
if LAYOUT == "square":
z = M[1:, :-1]
text = [[cell_text(v) if (LABELS and k <= 16 and not np.isnan(v)) else "" for v in row] for row in z]
fig.add_heatmap(z=z, x=markers[:-1], y=markers[1:], colorscale=scale, zmin=0, zmax=1, text=text, texttemplate="%{text}", colorbar=dict(title=VALUE))
fig.update_yaxes(autorange="reversed")
else:
cx, cy, cv, ct = [], [], [], []
for j in range(k):
for i in range(j):
x0, y0, v = (i + j + 1) / 2, -(j - i) / 2, M[j, i] # Haploview diamond centre
path = f"M {x0} {y0 + 0.5} L {x0 + 0.5} {y0} L {x0} {y0 - 0.5} L {x0 - 0.5} {y0} Z"
fill = sample_colorscale(scale, [min(1, max(0, v))])[0] if not np.isnan(v) else "rgba(0,0,0,0)"
fig.add_shape(type="path", path=path, fillcolor=fill, line=dict(color="white", width=0.5))
if not np.isnan(v):
cx.append(x0); cy.append(y0); cv.append(v); ct.append(f"{markers[i]} – {markers[j]}: {v:.3f}")
fig.add_scatter(x=cx, y=cy, mode="markers+text" if (LABELS and k <= 16) else "markers", text=[cell_text(v) for v in cv] if (LABELS and k <= 16) else None,
hovertext=ct, hoverinfo="text", showlegend=False,
marker=dict(size=1, color=cv, colorscale=scale, cmin=0, cmax=1, showscale=True, colorbar=dict(title=VALUE)))
for m, name in enumerate(markers):
fig.add_annotation(x=m + 0.5, y=0.1, text=name, showarrow=False, textangle=-45, xanchor="left", yanchor="bottom")
fig.update_layout(xaxis=dict(range=[0, k], visible=False), yaxis=dict(range=[-k / 2, 1.5], scaleanchor="x", visible=False))
fig.show()
Needs pandas, numpy, plotly · reads ld-heatmap-demo.csv · app theme from the optional codesplash helper
# LD heatmap (pairwise linkage disequilibrium) — Codesplash Chart Lab (recipe "ld-heatmap")# controls: layout=triangle, labels=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("ld-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["marker A"]] <- factor(df[["marker A"]])
df[["marker B"]] <- factor(df[["marker B"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
a_col <- "marker A"
b_col <- "marker B"
value_col <- "r²"
layout <- "triangle"; labels <- TRUE
ab <- cbind(as.character(df[[a_col]]), as.character(df[[b_col]]))
markers <- unique(c(t(ab))) # first appearance over A then B, row by row
markers <- markers[!is.na(markers)]
k <- length(markers)
d <- data.frame(a = ab[, 1], b = ab[, 2], v = suppressWarnings(as.numeric(df[[value_col]])), stringsAsFactors = FALSE)
d <- d[!is.na(d$a) & !is.na(d$b) & !is.na(d$v) & d$a != d$b, ]
d$i <- pmin(match(d$a, markers), match(d$b, markers)); d$j <- pmax(match(d$a, markers), match(d$b, markers))
d <- d[!duplicated(paste(d$i, d$j), fromLast = TRUE), ] # a pair listed twice keeps its last value
r2 <- round(d$v, 2)
d$lab <- ifelse(r2 %in% c(0, 1), as.character(r2), sub("^(-?)0\\.", "\\1.", sprintf("%.2f", d$v)))
show_text <- labels && k <= 16
fill_scale <- scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(0, 1), oob = scales::squish, name = value_col)
if (layout == "square") {
d$col <- factor(markers[d$i], levels = markers[-k]); d$row <- factor(markers[d$j], levels = rev(markers[-1]))
p <- ggplot(d, aes(col, row, fill = v)) + geom_tile(colour = "white") + fill_scale +
labs(x = NULL, y = NULL) + coord_equal() + theme_cs + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank())
if (show_text) p <- p + geom_text(aes(label = lab), size = 2.6)
} else {
# Haploview: each pair a diamond halfway between its markers, (j - i)/2 below them
d$cx <- (d$i + d$j - 1) / 2; d$cy <- -(d$j - d$i) / 2
poly <- do.call(rbind, lapply(seq_len(nrow(d)), function(r) data.frame(id = r, v = d$v[r], x = d$cx[r] + c(0, 0.5, 0, -0.5), y = d$cy[r] + c(0.5, 0, -0.5, 0))))
p <- ggplot(poly, aes(x, y, group = id, fill = v)) + geom_polygon(colour = "white", linewidth = 0.3) + fill_scale +
annotate("text", x = seq_len(k) - 0.5, y = 0.1, label = markers, angle = 45, hjust = 0, size = 2.6) +
coord_equal(xlim = c(0, k), ylim = c(-k / 2, 1.5), clip = "off") + labs(x = NULL, y = NULL) + theme_cs +
theme(axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())
if (show_text) p <- p + geom_text(data = d, aes(cx, cy, label = lab), inherit.aes = FALSE, size = 2.4)
}
print(p)
Needs ggplot2 · reads ld-heatmap-demo.csv · app theme from the optional codesplashr helper
Read each point as one marker: the higher it sits, the smaller its p-value (−log₁₀ p).
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.
Use the suggestive line for markers worth following up, and the labels to name the strongest hits.
1Callout 1: A peak crossing the genome-wide line.
2Callout 2: The genome-wide line (5 × 10⁻⁸).
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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}"
hover = (d["label"].astype(str) + " · " if LABEL else "") + d["chrom"].astype(str) + " " + d["pos"].map("{:g}".format) + " · p = " + d["p"].map("{:.3g}".format)
fig = go.Figure()
for b, alpha in ((0, 1.0), (1, 0.5)): # alternating shades by chromosome
m = (d["band"] == b).to_numpy()
fig.add_scattergl(x=d["x"][m], y=d["y"][m], mode="markers", marker=dict(size=4, color=PALETTE[0], opacity=alpha), hovertext=hover[m], hoverinfo="text", showlegend=False)
if 0 < SUGGESTIVE < 1:
fig.add_hline(y=-np.log10(SUGGESTIVE), line_dash="dash", line_color=REF, annotation_text=f"suggestive {SUGGESTIVE:g}")
if 0 < GW < 1:
fig.add_hline(y=-np.log10(GW), line_color=PALETTE[3], annotation_text=f"genome-wide {GW:g}")
for _, r in top.iterrows():
fig.add_annotation(x=r["x"], y=r["y"], text=top_label(r), showarrow=True, arrowhead=0, ax=20, ay=-20)
if multi:
fig.update_xaxes(tickvals=centres.to_numpy(), ticktext=[re.sub(r"^chr", "", str(ch), flags=re.I) for ch in order], title="chromosome")
else:
fig.update_xaxes(title=POS)
fig.update_yaxes(title="−log₁₀ p", rangemode="tozero")
fig.show()
Needs pandas, numpy, plotly, re · reads manhattan-demo.csv · app theme from the optional codesplash helper
# Manhattan plot (association scan) — Codesplash Chart Lab (recipe "manhattan")# controls: gw=5e-8, suggestive=0.00001, top=3
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("manhattan-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["chromosome"]] <- factor(df[["chromosome"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22"))
df[["marker"]] <- factor(df[["marker"]])
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
pos_col <- "position (bp)"
p_col <- "p"
chrom_col <- "chromosome"
label_col <- "marker"
gw <- 5e-8; suggestive <- 0.00001; top_n <- 3 # lines (0 = none), top markers to label
d <- data.frame(pos = suppressWarnings(as.numeric(df[[pos_col]])), p = suppressWarnings(as.numeric(df[[p_col]])))
d$chrom <- if (!is.null(chrom_col)) ifelse(is.na(df[[chrom_col]]), "unknown", as.character(df[[chrom_col]])) else ""
d$label <- if (!is.null(label_col)) as.character(df[[label_col]]) else NA_character_
d <- d[!is.na(d$pos) & !is.na(d$p) & d$p > 0 & d$p <= 1, ] # a p of 0 has no -log10
ch <- unique(d$chrom)
s <- sub("^chr", "", trimws(ch), ignore.case = TRUE); u <- toupper(s)
special <- c(X = 1000, Y = 1001, XY = 1002, M = 1003, MT = 1003)
key1 <- ifelse(grepl("^[0-9]+$", s), suppressWarnings(as.numeric(s)), ifelse(u %in% names(special), special[u], 2000))
key2 <- ifelse(key1 < 2000, "", u)
ch <- ch[order(key1, key2, ch)] # 1-22, X, Y, XY, MT, then others
lo <- tapply(d$pos, d$chrom, min)[ch]; hi <- tapply(d$pos, d$chrom, max)[ch]
multi <- length(ch) > 1
if (multi) {
gap <- if (sum(hi - lo) > 0) sum(hi - lo) * 0.005 else 1 # 0.5% of the summed spans between chromosomes
off <- c(0, cumsum(hi - lo + gap)[-length(ch)]); names(off) <- ch
d$x <- off[d$chrom] + d$pos - lo[d$chrom]
} else d$x <- d$pos
d$y <- -log10(d$p)
d$band <- factor((match(d$chrom, ch) - 1) %% 2, levels = c(0, 1))
top <- head(d[order(d$p), ], top_n)
top$lab <- ifelse(is.na(top$label), if (multi) paste0(top$chrom, ":", top$pos) else as.character(top$pos), top$label)
p <- ggplot(d, aes(x, y, colour = band)) + geom_point(size = 0.8) +
scale_colour_manual(values = c("0" = cs_cat[1], "1" = grDevices::adjustcolor(cs_cat[1], alpha.f = 0.5)), guide = "none")
if (suggestive > 0 && suggestive < 1) p <- p + geom_hline(yintercept = -log10(suggestive), colour = ref_col, linetype = "dashed")
if (gw > 0 && gw < 1) p <- p + geom_hline(yintercept = -log10(gw), colour = cs_cat[4])
if (nrow(top)) p <- p + geom_point(data = top, aes(x, y), inherit.aes = FALSE, shape = 1, size = 2.4) +
geom_text(data = top, aes(x, y, label = lab), inherit.aes = FALSE, vjust = -0.8, hjust = 0, size = 2.6)
p <- p + (if (multi) scale_x_continuous(breaks = off + (hi - lo) / 2, labels = sub("^chr", "", ch, ignore.case = TRUE)) else scale_x_continuous()) +
labs(x = if (multi) "chromosome" else pos_col, y = "-log10 p") + theme_cs + theme(panel.grid.major.x = element_blank())
print(p)
Needs ggplot2 · reads manhattan-demo.csv · app theme from the optional codesplashr helper
Read the dashed line as what p-values look like when no marker is associated; points on it are null.
Points that follow the line and rise only at the top right are compatible with a few real signals on a calibrated test.
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.
1Callout 1: λ_GC: median χ² relative to the null.
2Callout 2: Most markers on the null line.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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 = go.Figure()
if BAND and n:
fig.add_scatter(x=np.r_[ex, ex[::-1]], y=np.r_[band_hi, band_lo[::-1]], fill="toself", mode="none", fillcolor=PALETTE[0], opacity=0.2, name="95% band")
lim = ex.max() if n else 1
fig.add_scatter(x=[0, lim], y=[0, lim], mode="lines", line=dict(color=REF, dash="dash"), name="expected under the null")
fig.add_scattergl(x=ex, y=ob, mode="markers", marker=dict(size=4, color=PALETTE[0]), name="markers", customdata=p, hovertemplate="p = %{customdata:.3g}<extra></extra>")
fig.add_annotation(xref="paper", yref="paper", x=0.02, y=0.98, text=f"λ<sub>GC</sub> = {lam:.3f}", showarrow=False, xanchor="left")
fig.update_layout(xaxis_title="expected −log₁₀ p", yaxis_title="observed −log₁₀ p", xaxis_rangemode="tozero", yaxis_rangemode="tozero")
fig.show()
Needs pandas, numpy, plotly, scipy · reads gwas-qq-demo.csv · app theme from the optional codesplash helper
# QQ plot of p-values (with λ_GC) — Codesplash Chart Lab (recipe "gwas-qq")# controls: lambda=0, band=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("gwas-qq-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
p_col <- "p"
lambda <- 0; band <- TRUE # lambda_GC from the method (0 = estimate from these p-values), 95% band
pv <- suppressWarnings(as.numeric(df[[p_col]]))
pv <- sort(pv[!is.na(pv) & pv > 0 & pv <= 1]); n <- length(pv)
e <- ppoints(n)
lam <- if (lambda > 0) lambda else median(qchisq(pv, 1, lower.tail = FALSE)) / qchisq(0.5, 1) # Devlin & Roeder (1999)
i <- seq_len(n)
d <- data.frame(x = -log10(e), y = -log10(pv), lo = -log10(qbeta(0.975, i, n - i + 1)), hi = -log10(qbeta(0.025, i, n - i + 1)))
p <- ggplot(d, aes(x, y))
if (band) p <- p + geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.16)
p <- p + geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_point(colour = cs_cat[1], size = 1) +
annotate("text", x = 0, y = max(c(d$y, d$hi), na.rm = TRUE), label = sprintf("lambda[GC] == %.3f", lam), parse = TRUE, hjust = 0, vjust = 1) +
labs(x = "expected -log10 p", y = "observed -log10 p") + theme_cs
print(p)
Needs ggplot2 · reads gwas-qq-demo.csv · app theme from the optional codesplashr helper
Read each bar as the number of segregating sites whose derived allele is carried by that many of the n sequences.
Compare the bars with the dashed neutral expectation θ_W / i, scaled to the same number of sites.
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.
1Callout 1: Singletons: one sequence carries the derived allele.
2Callout 2: Middle classes.
3Callout 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
# 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 plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("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 = go.Figure()
fig.add_bar(x=i, y=obs, marker_color=PALETTE[0], opacity=0.85, name=f"observed (S = {S:g})")
if EXPECTED and S > 0:
fig.add_scatter(x=i, y=exp, mode="lines+markers", line=dict(color=PALETTE[1], dash="dash"), name=f"neutral expectation (θ_W = {S / a1:.4g})")
fig.update_layout(xaxis_title=XLABEL, yaxis_title="sites", bargap=0.22)
fig.show()
Needs pandas, numpy, plotly · reads sfs-bar-demo.csv · app theme from the optional codesplash helper
# Site frequency spectrum — Codesplash Chart Lab (recipe "sfs-bar")# controls: n=0, folded=false, expected=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("sfs-bar-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
count_col <- "derived"
sites_col <- NULL
n_seq <- 0; folded <- FALSE; show_expected <- TRUE # sequences (0 = largest + 1)
kk <- suppressWarnings(as.numeric(df[[count_col]]))
ww <- if (!is.null(sites_col)) suppressWarnings(as.numeric(df[[sites_col]])) else rep(1, nrow(df)) # sites per row or 1
ok <- !is.na(kk) & abs(kk - round(kk)) <= 1e-9 & kk >= 0 & !is.na(ww) & ww >= 0
kk <- round(kk[ok]); ww <- ww[ok]
n <- if (n_seq > 0) round(n_seq) else if (length(kk)) max(kk) + 1 else 0
seg <- kk > 0 & kk < n; kk <- kk[seg]; ww <- ww[seg] # counts 0 and n are not segregating
cls <- if (folded) pmin(kk, n - kk) else kk
K <- if (folded) n %/% 2 else n - 1
obs <- vapply(seq_len(K), function(j) sum(ww[cls == j]), numeric(1))
S <- sum(obs); a1 <- sum(1 / seq_len(n - 1)); i <- seq_len(K)
ex <- if (folded) (S / a1) * (1 / i + 1 / (n - i)) / ifelse(i == n - i, 2, 1) else (S / a1) / i # theta_W / i (Tajima 1989; Fu 1995)
d <- data.frame(k = i, observed = obs, expected = ex)
p <- ggplot(d, aes(k, observed)) + geom_col(fill = cs_cat[1], alpha = 0.85, width = 0.78)
if (show_expected && S > 0) p <- p + geom_line(aes(y = expected), colour = cs_cat[2], linetype = "dashed") + geom_point(aes(y = expected), colour = cs_cat[2], size = 1.6)
p <- p + labs(x = if (folded) "minor-allele count" else "derived-allele count", y = "sites", subtitle = sprintf("S = %g, theta_W = %.4g", S, S / a1)) + theme_cs
print(p)
Needs ggplot2 · reads sfs-bar-demo.csv · app theme from the optional codesplashr helper