svgbrushablepareto
Pareto chart
Which few categories account for most of the total?
How to read it
- Read the bars left to right: categories are sorted by size.
- Follow the line for the running share of the total.
- Where the line crosses the reference: everything left of it is the vital few.
- Callout 1: The largest category.
- Callout 2: The running total crosses the reference here.
- Callout 3: The long tail of small categories.
Watch out
- It ranks frequency, not cost or severity. The biggest bar is not always the most important problem.
Defaults
- Categories shown
- 10
- How many categories to show before grouping the rest into Other.
- Range 3 to 30, step 1
- Reference %
- 80
- Where to draw the reference line on the cumulative axis.
- Range 50 to 95, step 5
- Cumulative labels
- Off
- Print the running share at each bar.
Pinned in the code
- Bars are row counts (or the sum of a value) per category, sorted descending (ties alphabetical); categories beyond the first N pool into “Other”, which is kept last as is conventional.
- Cumulative % = running total / grand total, read on the right axis; bars up to and including the one that crosses the reference (80 % by default) are the “vital few”.
- Negative values are not meaningful in a Pareto chart and are excluded.
# Pareto chart — Codesplash Chart Lab (recipe "pareto")
# controls: top=10, threshold=80, cumLabels=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("pareto-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
d = df[["defect"]].dropna().assign(_value=1.0) # no value column: count rows
sums = d.groupby(d["defect"].astype(str))["_value"].sum()
sums = sums[sums > 0] # non-positive totals are not meaningful in a Pareto chart
r = sums.rename("value").reset_index().sort_values(["value", "defect"], ascending=[False, True]) # ties alphabetical
r["share"] = r["value"] / r["value"].sum()
r["cumulative"] = r["share"].cumsum()
if len(r) > 10: # pool the rest into "Other", kept last
rest = r.iloc[10:]
other = pd.DataFrame({"defect": ["Other"], "value": [rest["value"].sum()], "share": [rest["share"].sum()], "cumulative": [1.0]})
r = pd.concat([r.iloc[:10], other], ignore_index=True)
THRESHOLD = 0.8
vital = int(np.argmax(r["cumulative"].to_numpy() >= THRESHOLD - 1e-12)) # bars up to the crossing are the vital few
colors = ["#9aa0a6" if lvl == "Other" else (PALETTE[0] if i <= vital else PALETTE[0] + "73") for i, lvl in enumerate(r["defect"])]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(r["defect"], r["value"], color=colors)
ax.set_ylabel("Count")
ax.set_xlabel("defect")
ax.tick_params(axis="x", labelrotation=35)
ax2 = ax.twinx() # cumulative share on a 0–100 % axis
ax2.plot(r["defect"], r["cumulative"] * 100, color=PALETTE[1], marker="o", linewidth=2)
ax2.axhline(THRESHOLD * 100, color=PALETTE[1], linestyle="--", linewidth=1)
ax2.set_ylim(0, 105)
ax2.set_ylabel("Cumulative %")
ax2.grid(False)
plt.show()Needs pandas, numpy, matplotlib · reads pareto-demo.csv · app theme from the optional codesplash helper
# Pareto chart — Codesplash Chart Lab (recipe "pareto")
# controls: top=10, threshold=80, cumLabels=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("pareto-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
d = df[["defect"]].dropna().assign(_value=1.0) # no value column: count rows
sums = d.groupby(d["defect"].astype(str))["_value"].sum()
sums = sums[sums > 0] # non-positive totals are not meaningful in a Pareto chart
r = sums.rename("value").reset_index().sort_values(["value", "defect"], ascending=[False, True]) # ties alphabetical
r["share"] = r["value"] / r["value"].sum()
r["cumulative"] = r["share"].cumsum()
if len(r) > 10: # pool the rest into "Other", kept last
rest = r.iloc[10:]
other = pd.DataFrame({"defect": ["Other"], "value": [rest["value"].sum()], "share": [rest["share"].sum()], "cumulative": [1.0]})
r = pd.concat([r.iloc[:10], other], ignore_index=True)
THRESHOLD = 0.8
vital = int(np.argmax(r["cumulative"].to_numpy() >= THRESHOLD - 1e-12)) # bars up to the crossing are the vital few
colors = ["#9aa0a6" if lvl == "Other" else (PALETTE[0] if i <= vital else PALETTE[0] + "73") for i, lvl in enumerate(r["defect"])]
from plotly.subplots import make_subplots
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_bar(x=r["defect"], y=r["value"], marker_color=colors, name="Count")
fig.add_scatter(x=r["defect"], y=r["cumulative"] * 100, mode="lines+markers", name="Cumulative %",
line_color=PALETTE[1], text=[f"{v:.0%}" for v in r["cumulative"]], textposition="top center", secondary_y=True)
fig.add_hline(y=THRESHOLD * 100, line_dash="dash", line_color=PALETTE[1], secondary_y=True)
fig.update_yaxes(title_text="Count", secondary_y=False)
fig.update_yaxes(title_text="Cumulative %", range=[0, 105], secondary_y=True)
fig.update_layout(xaxis_title="defect", showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads pareto-demo.csv · app theme from the optional codesplash helper
# Pareto chart — Codesplash Chart Lab (recipe "pareto")
# controls: top=10, threshold=80, cumLabels=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("pareto-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["defect"]] <- factor(df[["defect"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
cat <- as.character(df[["defect"]])
val <- rep(1, length(cat)) # no value column: count rows
ok <- !is.na(cat) & !is.na(val)
sums <- tapply(val[ok], cat[ok], sum)
sums <- sums[sums > 0] # non-positive totals are not meaningful in a Pareto chart
r <- data.frame(level = names(sums), value = as.numeric(sums))
r <- r[order(-r$value, r$level), ] # ties alphabetical
r$share <- r$value / sum(r$value)
r$cumulative <- cumsum(r$share)
if (nrow(r) > 10) { # pool the rest into "Other", kept last
rest <- r[-seq_len(10), ]
r <- rbind(r[seq_len(10), ], data.frame(level = "Other", value = sum(rest$value), share = sum(rest$share), cumulative = 1))
}
threshold <- 0.8
vital <- which(r$cumulative >= threshold - 1e-12)[1] # bars up to the crossing are the vital few
r$kind <- ifelse(r$level == "Other", "other", ifelse(seq_len(nrow(r)) <= vital, "vital", "rest"))
r$level <- factor(r$level, levels = r$level)
ymax <- max(r$value)
p <- ggplot(r, aes(level, value)) +
geom_col(aes(fill = kind), show.legend = FALSE) +
scale_fill_manual(values = c(vital = cs_cat[1], rest = grDevices::adjustcolor(cs_cat[1], 0.45), other = "#9aa0a6")) +
geom_line(aes(y = cumulative * ymax, group = 1), colour = cs_cat[2], linewidth = 0.9) +
geom_point(aes(y = cumulative * ymax), colour = cs_cat[2], size = 1.8) +
geom_hline(yintercept = threshold * ymax, colour = cs_cat[2], linetype = "dashed") +
scale_y_continuous("Count", sec.axis = sec_axis(~ . / ymax * 100, name = "Cumulative %")) +
labs(x = "defect") +
theme_cs +
theme(axis.text.x = element_text(angle = 35, hjust = 1))
print(p)Needs ggplot2 · reads pareto-demo.csv · app theme from the optional codesplashr helper
-- Pareto chart — Codesplash Chart Lab (recipe "pareto")
-- controls: top=10, threshold=80, cumLabels=false
-- per-category totals sorted descending (ties alphabetical) with cumulative share; beyond 10 pooled into 'Other'
WITH sums AS (
SELECT "defect"::VARCHAR AS level, count(*) AS value
FROM read_csv('pareto-demo.csv')
WHERE "defect" IS NOT NULL
GROUP BY 1
HAVING value > 0
),
ranked AS (SELECT *, row_number() OVER (ORDER BY value DESC, level) AS rk FROM sums),
pooled AS (
SELECT CASE WHEN rk <= 10 THEN level ELSE 'Other' END AS level, sum(value) AS value, min(rk) AS rk
FROM ranked GROUP BY 1
)
SELECT level, value,
value / sum(value) OVER () AS share,
sum(value) OVER (ORDER BY rk) / sum(value) OVER () AS cumulative
FROM pooled
ORDER BY rk;Needs duckdb · reads pareto-demo.csv