svgcontrol-chart
Control chart
Is the process in statistical control, and where are the signals?
How to read it
- 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.
- Callout 1: Signals: points beyond the limits or breaking a rule.
- Callout 2: The centre line.
- Callout 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
# Control chart — Codesplash Chart Lab (recipe "control-chart")
# controls: zones=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("control-chart-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["signal"]] <- as.logical(df[["signal"]])
df[["rule"]] <- factor(df[["rule"]])
df[["chart"]] <- factor(df[["chart"]], levels = c("X̄", "R"))
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)]))
i_col <- "subgroup"
v_col <- "statistic"
cl_col <- "centre"
lcl_col <- "lcl"
ucl_col <- "ucl"
vio_col <- "signal"
rule_col <- "rule"
chart_col <- "chart"
d <- data.frame(i = df[[i_col]], v = df[[v_col]], cl = df[[cl_col]], lcl = df[[lcl_col]], ucl = df[[ucl_col]],
chart = if (is.null(chart_col)) v_col else factor(as.character(df[[chart_col]]), levels = levels_of(df[[chart_col]])))
d$signal <- if (is.null(vio_col)) (d$v > d$ucl | d$v < d$lcl) else as.logical(df[[vio_col]])
p <- ggplot(d, aes(i, v)) +
geom_step(aes(y = cl), colour = "grey50", direction = "mid") +
geom_step(aes(y = ucl), colour = ref_col, linetype = "dashed", direction = "mid") +
geom_step(aes(y = lcl), colour = ref_col, linetype = "dashed", direction = "mid") +
geom_line(colour = cs_cat[1]) + geom_point(colour = cs_cat[1], size = 1.4) +
geom_point(data = d[d$signal %in% TRUE, ], colour = "#ce5342", size = 2.6) +
facet_wrap(~chart, ncol = 1, scales = "free_y") + labs(x = i_col, y = NULL) + theme_cs
print(p)Needs ggplot2 · reads control-chart-demo.csv · app theme from the optional codesplashr helper