svgprobability-plot
Probability plot
Do these failures fall on a straight line on this family's probability paper?
How to read it
- 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.
- Callout 1: The earliest failures, where a family most often fails to fit.
- Callout 2: The fitted line: a straight run of points supports this family.
- Callout 3: The latest failures, based on the fewest units.
- Callout 4: Time on a log scale for this paper.
Watch out
- A few points at either end always wander, so judge the middle first and the ends with care.
- Censored units are not plotted, but they raise the order number of later failures, so do not drop them from the data.
Defaults
- Paper
- Weibull
- The family whose straight line you are checking against.
- Also: Log-normal · Exponential · Log-logistic · Normal
Pinned in the code
- Plotting positions: Benard's median ranks (i − 0.3)/(n + 0.4) with Johnson's adjusted order numbers for censored units; failures come before suspensions at a tie.
- Without engine rows the line is rank regression of paper y on paper x. With them it is the fitted CDF the engine sent.
- The plot correlation is Pearson's r of the plotted points.
# Probability plot — Codesplash Chart Lab (recipe "probability-plot")
# controls: paper=weibull
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("probability-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
T = "hours"
E = "failed"
F = None
FAM = None
def median_ranks(t, e=None):
"""Johnson's adjusted order numbers with Benard's median ranks; failures before suspensions at a tie."""
t = np.asarray(t, dtype=float)
e = np.ones(t.size, dtype=bool) if e is None else np.asarray(e, dtype=float) > 0
keep = np.isfinite(t) & (t > 0)
t, e = t[keep], e[keep]
o = np.lexsort((~e, t))
t, e = t[o], e[o]
n, prev, ts, fs = t.size, 0.0, [], []
for i in range(n):
if e[i]:
prev += (n + 1 - prev) / (n - i + 1)
ts.append(t[i])
fs.append((prev - 0.3) / (n + 0.4))
return np.array(ts), np.array(fs)
def paper_x(paper, t):
return t if paper in ("exponential", "normal") else np.log(t)
def paper_y(paper, f):
if paper == "weibull":
return np.log(-np.log1p(-f))
if paper == "exponential":
return -np.log1p(-f)
if paper == "loglogistic":
return np.log(f / (1 - f))
return stats.norm.ppf(f)
def paper_line(rows, paper, x):
"""The engine's fitted curve for this family when present, else rank regression of paper y on paper x."""
if rows is not None and len(rows):
curve = rows[(rows[F] > 0) & (rows[F] < 1)].sort_values(T)
return paper_x(paper, curve[T].to_numpy(float)), paper_y(paper, curve[F].to_numpy(float))
xs, ys = x
b, a = np.polyfit(xs, ys, 1)
return np.array([xs.min(), xs.max()]), a + b * np.array([xs.min(), xs.max()])
def split_rows(df):
is_data = df[FAM].astype(str).str.lower().eq("data") if FAM else pd.Series(True, index=df.index)
return df[is_data], df[~is_data]
PAPER = "weibull"
sample, curves = split_rows(df)
tt, ff = median_ranks(sample[T], sample[E] if E else None)
xs, ys = paper_x(PAPER, tt), paper_y(PAPER, ff)
fit_rows = curves[curves[FAM].astype(str) == PAPER] if FAM and F else None
lx, ly = paper_line(fit_rows, PAPER, (xs, ys))
fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(lx, ly, color=REF, linewidth=1.5)
ax.scatter(xs, ys, s=18, color=PALETTE[0], alpha=0.8)
probs = np.array([0.01, 0.05, 0.1, 0.2, 0.5, 0.8, 0.9, 0.99])
probs = probs[(probs >= ff.min() * 0.9) & (probs <= ff.max() * 1.1)]
ax.set_yticks(paper_y(PAPER, probs), [f"{p:.0%}" for p in probs])
ax.set_xlabel(T if PAPER in ("exponential", "normal") else f"log {T}")
ax.set_ylabel("Cumulative failure probability")
ax.set_title(f"{PAPER} probability plot: plot correlation {np.corrcoef(xs, ys)[0, 1]:.3f}", fontsize=10, loc="left")
plt.show()Needs pandas, numpy, matplotlib, scipy · reads probability-plot-demo.csv · app theme from the optional codesplash helper
# 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