svgfit-overlay-grid
Fitted densities by family
Which candidate distribution follows the data's histogram most closely?
How to read it
- 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.
- Callout 1: A curve that follows the bars closely.
- Callout 2: A curve that misses the data's shape.
Watch out
- The best of several fits may still be poor, so test it or use a Q–Q plot.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Rows whose family is “data” carry the sample (histogram, Freedman–Diaconis bins with type-7 quartiles, density scale); other rows carry each family's fitted density on a grid from the engine.
- Every panel shares the x and y scales so curves are comparable; at most six families are shown, in the engine's AIC order.
# Fitted densities by family — Codesplash Chart Lab (recipe "fit-overlay-grid")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("fit-overlay-grid-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["family"] = pd.Categorical(df["family"].astype("string"), categories=["data", "lognormal", "gamma", "normal", "exponential"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
X = "hours"
D = "density"
F = "family"
is_data = df[F].astype(str).str.lower().isin(["data", "sample", "empirical", "observed"])
sample = df.loc[is_data, X].dropna().to_numpy(float)
curves = df.loc[~is_data].dropna(subset=[X, D])
fams = [f for f in levels_of(curves[F])][:6]
iqr = np.subtract(*np.percentile(sample, [75, 25])) # Freedman–Diaconis bins (type-7 quartiles)
bins = max(1, min(60, int(np.ceil(np.ptp(sample) / (2 * iqr * len(sample) ** (-1 / 3)))))) if iqr > 0 else "sturges"
cols = 1 if len(fams) <= 1 else 2 if len(fams) <= 4 else 3
rows = int(np.ceil(len(fams) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 2.8 * rows), sharex=True, sharey=True, squeeze=False)
for ax, (i, fam) in zip(axes.flat, enumerate(fams)):
ax.hist(sample, bins=bins, density=True, color=GREY, alpha=0.7)
cv = curves[curves[F].astype(str) == str(fam)].sort_values(X)
ax.plot(cv[X], cv[D], color=PALETTE[i % len(PALETTE)], linewidth=1.8)
ax.set_title(str(fam), fontsize=9, loc="left")
for ax in list(axes.flat)[len(fams):]:
ax.set_visible(False)
plt.show()Needs pandas, numpy, matplotlib · reads fit-overlay-grid-demo.csv · app theme from the optional codesplash helper
# 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
# Fitted densities by family — Codesplash Chart Lab (recipe "fit-overlay-grid")
# 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("fit-overlay-grid-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["family"]] <- factor(df[["family"]], levels = c("data", "lognormal", "gamma", "normal", "exponential"))
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 <- "hours"
d_col <- "density"
f_col <- "family"
fam <- as.character(df[[f_col]])
is_data <- tolower(fam) %in% c("data", "sample", "empirical", "observed")
smp <- data.frame(x = df[[x_col]][is_data]); smp <- smp[!is.na(smp$x), , drop = FALSE]
cv <- data.frame(x = df[[x_col]][!is_data], y = df[[d_col]][!is_data], family = fam[!is_data])
cv <- cv[!is.na(cv$x) & !is.na(cv$y), ]
fams <- head(unique(cv$family), 6)
cv <- cv[cv$family %in% fams, ]; cv$family <- factor(cv$family, levels = fams)
smp <- merge(smp, data.frame(family = factor(fams, levels = fams))) # the sample in every panel
p <- ggplot() + geom_histogram(data = smp, aes(x, after_stat(density)), bins = nclass.FD(smp$x[smp$family == fams[1]]), fill = grey_col, alpha = 0.7) +
geom_line(data = cv, aes(x, y, colour = family), linewidth = 0.9, show.legend = FALSE) +
facet_wrap(~family) + scale_colour_manual(values = rep(cs_cat, length.out = length(fams))) + labs(x = x_col, y = "density") + theme_cs
print(p)Needs ggplot2 · reads fit-overlay-grid-demo.csv · app theme from the optional codesplashr helper