Skip to content
svgfit-overlay-grid

Fitted densities by family

Which candidate distribution follows the data's histogram most closely?

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

How to read it

  1. Each panel shows the same histogram with one family's best fit.
  2. Compare how each curve follows the bars, especially in the tails.
  3. Use the fit table's AIC to rank them, then decide with the context.
  1. Callout 1: A curve that follows the bars closely.
  2. Callout 2: A curve that misses the data's shape.

Watch out

  • The best of several fits may still be poor, so test it or use a Q–Q plot.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Rows whose family is “data” carry the sample (histogram, Freedman–Diaconis bins with type-7 quartiles, density scale); other rows carry each family's fitted density on a grid from the engine.
  • Every panel shares the x and y scales so curves are comparable; at most six families are shown, in the engine's AIC order.
# Fitted densities by family — Codesplash Chart Lab (recipe "fit-overlay-grid")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("fit-overlay-grid-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["family"] = pd.Categorical(df["family"].astype("string"), categories=["data", "lognormal", "gamma", "normal", "exponential"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
X = "hours"
D = "density"
F = "family"
is_data = df[F].astype(str).str.lower().isin(["data", "sample", "empirical", "observed"])
sample = df.loc[is_data, X].dropna().to_numpy(float)
curves = df.loc[~is_data].dropna(subset=[X, D])
fams = [f for f in levels_of(curves[F])][:6]
iqr = np.subtract(*np.percentile(sample, [75, 25]))  # Freedman–Diaconis bins (type-7 quartiles)
bins = max(1, min(60, int(np.ceil(np.ptp(sample) / (2 * iqr * len(sample) ** (-1 / 3)))))) if iqr > 0 else "sturges"
cols = 1 if len(fams) <= 1 else 2 if len(fams) <= 4 else 3
rows = int(np.ceil(len(fams) / cols))
fig, axes = plt.subplots(rows, cols, figsize=(4 * cols, 2.8 * rows), sharex=True, sharey=True, squeeze=False)
for ax, (i, fam) in zip(axes.flat, enumerate(fams)):
    ax.hist(sample, bins=bins, density=True, color=GREY, alpha=0.7)
    cv = curves[curves[F].astype(str) == str(fam)].sort_values(X)
    ax.plot(cv[X], cv[D], color=PALETTE[i % len(PALETTE)], linewidth=1.8)
    ax.set_title(str(fam), fontsize=9, loc="left")
for ax in list(axes.flat)[len(fams):]:
    ax.set_visible(False)
plt.show()

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