svgdist-id-grid
Distribution ID plot
Which lifetime family fits: Weibull, log-normal, exponential or log-logistic?
How to read it
- Each panel is one family's probability paper, and the panel title gives how well the points follow its line.
- Look for the panel where the points lie straightest, across the whole range.
- Read it with the AIC table: agreement between them is stronger evidence than either alone.
- Callout 1: The family and how straight its points are: r nearer 1 is straighter.
- Callout 2: A family that fits: the points stay on the line.
- Callout 3: Points bending away from the line: this family misses the early failures.
Watch out
- With few failures several panels look straight. Compare the B-lives before you pick one, because the choice matters most in the tails.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Median ranks with adjusted order numbers on each paper; r is the plot correlation of the points.
- Lines are the engine's maximum-likelihood fits when it sends them, otherwise rank regression.
- Gamma, generalized gamma and Gompertz have no straight-line paper, so they appear only in the AIC table.
# Distribution ID plot — Codesplash Chart Lab (recipe "dist-id-grid")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("dist-id-grid-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
T = "hours"
E = "failed"
F = None
FAM = None
def median_ranks(t, e=None):
"""Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie."""
t = np.asarray(t, dtype=float)
e = np.ones(t.size, dtype=bool) if e is None else np.asarray(e, dtype=float) > 0
keep = np.isfinite(t) & (t > 0)
t, e = t[keep], e[keep]
o = np.lexsort((~e, t))
t, e = t[o], e[o]
n, prev, ts, fs = t.size, 0.0, [], []
for i in range(n):
if e[i]:
prev += (n + 1 - prev) / (n - i + 1)
ts.append(t[i])
fs.append((prev - 0.3) / (n + 0.4))
return np.array(ts), np.array(fs)
def paper_x(paper, t):
return t if paper in ("exponential", "normal") else np.log(t)
def paper_y(paper, f):
if paper == "weibull":
return np.log(-np.log1p(-f))
if paper == "exponential":
return -np.log1p(-f)
if paper == "loglogistic":
return np.log(f / (1 - f))
return stats.norm.ppf(f)
def paper_line(rows, paper, x):
"""The engine's fitted curve for this family when present, else rank regression of paper y on paper x."""
if rows is not None and len(rows):
curve = rows[(rows[F] > 0) & (rows[F] < 1)].sort_values(T)
return paper_x(paper, curve[T].to_numpy(float)), paper_y(paper, curve[F].to_numpy(float))
xs, ys = x
b, a = np.polyfit(xs, ys, 1)
return np.array([xs.min(), xs.max()]), a + b * np.array([xs.min(), xs.max()])
def split_rows(df):
is_data = df[FAM].astype(str).str.lower().eq("data") if FAM else pd.Series(True, index=df.index)
return df[is_data], df[~is_data]
sample, curves = split_rows(df)
tt, ff = median_ranks(sample[T], sample[E] if E else None)
fig, axes = plt.subplots(2, 2, figsize=(9, 6))
for i, (ax, paper) in enumerate(zip(axes.flat, ["weibull", "lognormal", "exponential", "loglogistic"])):
xs, ys = paper_x(paper, tt), paper_y(paper, ff)
lx, ly = paper_line(curves[curves[FAM].astype(str) == paper] if FAM and F else None, paper, (xs, ys))
ax.plot(lx, ly, color=REF, linewidth=1.4)
ax.scatter(xs, ys, s=12, color=PALETTE[i % len(PALETTE)], alpha=0.8)
ax.set_title(f"{paper}: r = {np.corrcoef(xs, ys)[0, 1]:.3f}", fontsize=9, loc="left")
plt.tight_layout()
plt.show()Needs pandas, numpy, matplotlib, scipy · reads dist-id-grid-demo.csv · app theme from the optional codesplash helper
# Distribution ID plot — Codesplash Chart Lab (recipe "dist-id-grid")
# 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("dist-id-grid-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
T = "hours"
E = "failed"
F = None
FAM = None
def median_ranks(t, e=None):
"""Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie."""
t = np.asarray(t, dtype=float)
e = np.ones(t.size, dtype=bool) if e is None else np.asarray(e, dtype=float) > 0
keep = np.isfinite(t) & (t > 0)
t, e = t[keep], e[keep]
o = np.lexsort((~e, t))
t, e = t[o], e[o]
n, prev, ts, fs = t.size, 0.0, [], []
for i in range(n):
if e[i]:
prev += (n + 1 - prev) / (n - i + 1)
ts.append(t[i])
fs.append((prev - 0.3) / (n + 0.4))
return np.array(ts), np.array(fs)
def paper_x(paper, t):
return t if paper in ("exponential", "normal") else np.log(t)
def paper_y(paper, f):
if paper == "weibull":
return np.log(-np.log1p(-f))
if paper == "exponential":
return -np.log1p(-f)
if paper == "loglogistic":
return np.log(f / (1 - f))
return stats.norm.ppf(f)
def paper_line(rows, paper, x):
"""The engine's fitted curve for this family when present, else rank regression of paper y on paper x."""
if rows is not None and len(rows):
curve = rows[(rows[F] > 0) & (rows[F] < 1)].sort_values(T)
return paper_x(paper, curve[T].to_numpy(float)), paper_y(paper, curve[F].to_numpy(float))
xs, ys = x
b, a = np.polyfit(xs, ys, 1)
return np.array([xs.min(), xs.max()]), a + b * np.array([xs.min(), xs.max()])
def split_rows(df):
is_data = df[FAM].astype(str).str.lower().eq("data") if FAM else pd.Series(True, index=df.index)
return df[is_data], df[~is_data]
from plotly.subplots import make_subplots
sample, curves = split_rows(df)
tt, ff = median_ranks(sample[T], sample[E] if E else None)
papers = ["weibull", "lognormal", "exponential", "loglogistic"]
fig = make_subplots(rows=2, cols=2, subplot_titles=[f"{p}: r = {np.corrcoef(paper_x(p, tt), paper_y(p, ff))[0, 1]:.3f}" for p in papers])
for i, paper in enumerate(papers):
xs, ys = paper_x(paper, tt), paper_y(paper, ff)
lx, ly = paper_line(curves[curves[FAM].astype(str) == paper] if FAM and F else None, paper, (xs, ys))
fig.add_scatter(x=lx, y=ly, mode="lines", line=dict(color=REF), showlegend=False, row=i // 2 + 1, col=i % 2 + 1)
fig.add_scatter(x=xs, y=ys, mode="markers", marker=dict(color=PALETTE[i % len(PALETTE)], size=5), showlegend=False, row=i // 2 + 1, col=i % 2 + 1)
fig.update_layout(title="Distribution ID")
fig.show()Needs pandas, numpy, plotly, scipy · reads dist-id-grid-demo.csv · app theme from the optional codesplash helper
# Distribution ID plot — Codesplash Chart Lab (recipe "dist-id-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("dist-id-grid-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]
}
s <- data_rows(df)
r <- median_ranks(s[[t_col]], if (is.null(e_col)) NULL else s[[e_col]])
papers <- c("weibull", "lognormal", "exponential", "loglogistic")
corr <- vapply(papers, function(pp) cor(paper_x(pp, r$t), paper_y(pp, r$f)), numeric(1))
facet <- function(pp) factor(sprintf("%s: r = %.3f", paper_label[[pp]], corr[[pp]]), levels = sprintf("%s: r = %.3f", paper_label[papers], corr))
pts <- do.call(rbind, lapply(papers, function(pp) data.frame(x = paper_x(pp, r$t), y = paper_y(pp, r$f), panel = facet(pp))))
lns <- do.call(rbind, lapply(papers, function(pp) {
fr <- fit_rows(df, pp)
if (nrow(fr)) return(data.frame(x = paper_x(pp, fr[[t_col]]), y = paper_y(pp, fr[[fit_col]]), panel = facet(pp)))
xs <- paper_x(pp, r$t)
b <- coef(lm(paper_y(pp, r$f) ~ xs))
data.frame(x = range(xs), y = b[1] + b[2] * range(xs), panel = facet(pp))
}))
p <- ggplot(pts, aes(x, y)) + geom_line(data = lns, colour = ref_col) + geom_point(colour = cs_cat[1], alpha = 0.8, size = 1) +
facet_wrap(~panel, scales = "free") + labs(x = "Paper x", y = "Paper y", title = "Distribution ID") + theme_cs
print(p)Needs ggplot2 · reads dist-id-grid-demo.csv · app theme from the optional codesplashr helper