Sub topic 6
Building a Pareto chart in Python
This chapter turns the ideas from earlier chapters into working code. You will go from raw records to a sorted table, then to a finished chart, then to a list of the vital few categories. This chapter assumes you can read basic pandas (Series, DataFrame, groupby) and have drawn a simple matplotlib bar chart. You should also know what a cumulative percentage is.
The build pipeline
A Pareto chart takes five steps. Each step is a small, testable piece of code, so we will write them as separate functions.
Keeping the table step (A to D) separate from the plotting step (E) pays off. You can print and check the table before you draw anything, and you can reuse it for the vital-few selection later.
Step 1: Aggregate raw records into totals
Most real data does not arrive as tidy counts. It arrives as one row per event. To count events per category, use value_counts.
import pandas as pd
log = pd.Series([
"Scratches", "Cracks", "Scratches", "Wrong label",
"Scratches", "Misalignment", "Cracks", "Scratches",
])
counts = log.value_counts()
print(counts)value_counts already sorts from largest to smallest. Do not rely on that, though. Sort explicitly in the next step, because the "Other" bucket needs special handling.
If you measure by cost instead of count, sum a cost column per category with groupby:
import pandas as pd
repairs = pd.DataFrame({
"defect_type": ["Scratches", "Cracks", "Scratches", "Wrong label", "Cracks"],
"cost": [12.0, 340.0, 15.5, 4.0, 410.0],
})
cost_by_type = repairs.groupby("defect_type")["cost"].sum()
print(cost_by_type)Both results are a Series indexed by category name. From here on, the code does not care whether the values are counts or costs. Choosing between them is a separate decision, covered in a later chapter.
Step 2: Sort, and keep "Other" last
Sort from largest to smallest. The one exception is a catch-all bucket such as "Other". By convention it goes at the far right even when it is larger than some named categories. Otherwise a pile of unrelated small items would look like a major cause, and readers might try to "fix Other".
Step 3 adds the cumulative percentage. The function below does both steps and returns one table.
import pandas as pd
def pareto_table(values, other_label="Other"):
"""Return a table sorted for a Pareto chart.
values: mapping or Series of category -> non-negative total.
other_label: name of the catch-all category, kept last if present.
"""
values = pd.Series(values)
if values.empty:
raise ValueError("values is empty")
if (values < 0).any():
raise ValueError("Pareto charts need non-negative totals")
total = values.sum()
if total == 0:
raise ValueError("all totals are zero")
if other_label in values.index:
main = values.drop(other_label).sort_values(ascending=False, kind="stable")
ordered = pd.concat([main, values[[other_label]]])
else:
ordered = values.sort_values(ascending=False, kind="stable")
return pd.DataFrame({
"value": ordered,
"share_pct": (ordered / total * 100).round(1),
"cumulative_pct": (ordered.cumsum() / total * 100).round(1),
})
defects = {
"Scratches": 42,
"Misalignment": 27,
"Wrong label": 11,
"Cracks": 8,
"Discoloration": 5,
"Other": 7,
}
table = pareto_table(defects)
print(table)The output is:
value share_pct cumulative_pct
Scratches 42 42.0 42.0
Misalignment 27 27.0 69.0
Wrong label 11 11.0 80.0
Cracks 8 8.0 88.0
Discoloration 5 5.0 93.0
Other 7 7.0 100.0Check the table against what you know. The last cumulative value must be 100.0, and cumulative_pct must never decrease. If either fails, there is a bug in the data or the sort.
Why the checks and `kind="stable"`
- Negative values break the cumulative line, because it would go down. Pareto analysis needs totals that only add up. If you have credits or refunds, net them out per category first, or leave them out and say so.
- A zero total causes a division by zero and a table full of
NaN. Failing early with a clear message is better than a blank chart. - A stable sort keeps tied categories in their original order. Without it, two categories with equal counts can swap places between runs, and a chart that changes when nothing changed is confusing in a report.
Step 3: Plot bars and the cumulative line
A Pareto chart has two vertical scales. The bars use the left axis, in counts or cost. The line uses the right axis, in percent from 0 to 100. The classic layout also makes the two scales agree. The left axis runs from 0 to the grand total, so the top of the left axis is also 100% on the right axis. This matters because the first bar's top then sits exactly on the first point of the line. Anyone can check the chart by eye.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
def pareto_chart(table, title="Pareto chart", ylabel="Count", threshold=80):
"""Draw bars (left axis) and a cumulative line (right axis).
table: output of pareto_table.
threshold: percent at which to draw a dashed reference line, or None.
"""
total = table["value"].sum()
cum_pct = table["value"].cumsum() / total * 100
x = list(range(len(table)))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.bar(x, table["value"], color="C0")
ax.set_ylim(0, total)
ax.set_xticks(x)
ax.set_xticklabels(table.index, rotation=30, ha="right")
ax.set_ylabel(ylabel)
ax2 = ax.twinx()
ax2.plot(x, cum_pct, color="C1", marker="o")
ax2.set_ylim(0, 100)
ax2.yaxis.set_major_formatter(PercentFormatter())
ax2.set_ylabel("Cumulative share")
if threshold is not None:
ax2.axhline(threshold, color="gray", linestyle="--", linewidth=1)
ax.set_title(title)
fig.tight_layout()
return fig
defects = {
"Scratches": 42,
"Misalignment": 27,
"Wrong label": 11,
"Cracks": 8,
"Discoloration": 5,
"Other": 7,
}
# pareto_table is the function defined in Step 2
fig = pareto_chart(pareto_table(defects), title="Defects by type")
fig.savefig("pareto_defects.png", dpi=150)
plt.show()The code plots against numeric positions (0, 1, 2, ...) and then sets the labels. This avoids a quirk: with twin axes and string categories, matplotlib can assign category positions separately on each axis. Numeric positions keep the bars and the line aligned.
PercentFormatter() assumes its input runs from 0 to 100, which matches our cum_pct. If you ever compute a 0 to 1 fraction instead, pass xmax=1.
Step 4: Select the vital few
The chart lets you see where the cumulative line crosses 80%. Code can state it exactly. The rule is to keep every category whose cumulative share before it is still below the threshold. The category that crosses the line is then included.
import pandas as pd
def vital_few(values, threshold=80):
"""Return the leading categories needed to reach threshold percent."""
values = pd.Series(values)
cum_pct = values.cumsum() / values.sum() * 100
# Share accumulated BEFORE each category; the first category has 0.
before = cum_pct.shift(fill_value=0)
return values[before < threshold]
data = pd.Series({
"Scratches": 42,
"Misalignment": 27,
"Wrong label": 11,
"Cracks": 8,
"Discoloration": 5,
"Other": 7,
})
selected = vital_few(data)
print(selected)
print(f"{len(selected)} of {len(data)} categories give {selected.sum() / data.sum():.0%} of defects")This prints three categories and the line 3 of 6 categories give 80% of defects.
The shift is the key idea. Suppose you filtered on cum_pct <= 80 instead. Here, "Wrong label" lands on exactly 80.0 and is kept. But if it had landed on 82, the filter would drop it, and you would select only two categories covering 69%, which is short of the goal. Comparing the share before each category avoids this. The first category is always kept, and selection stops only once the threshold has been reached.
The function expects the data already sorted, so pass it the value column of pareto_table: vital_few(table["value"]). If "Other" is last, the function will include it only if the threshold is not reached before it. In that case you have a flat distribution and no real vital few, which is a finding in itself.
Edge cases and gotchas
| Situation | What goes wrong | What to do |
|---|---|---|
| Many tiny categories | Labels overlap and the tail is unreadable | Group the smallest into "Other", or show the top 10 to 15 and label the rest |
| Ties at the threshold | Which tied category appears first changes the selection | Use a stable sort and report ties openly |
| "Other" is the largest bucket | It looks like the top problem but is not actionable | Split it into named categories and rebuild the chart |
| Categories that overlap | The same event is counted twice, so totals exceed 100% of the real total | Define categories so each event falls in exactly one |
| Zero-count categories | Bars of height zero add clutter | Drop them before plotting, or keep them if a missing category is meaningful |
| Different time periods | Counts from a week and a month are not comparable | Compare shares, or use equal-length periods |
A last check: the right axis must end at exactly 100%. If you let matplotlib pick the right axis limits, it may stop at 105 or 110, and the line will look as if it never reaches the top. Always call set_ylim(0, 100).
Putting it together
For a new dataset, the full flow is only a few lines:
import pandas as pd
log = pd.Series(
["Scratches"] * 5 + ["Cracks"] * 3 + ["Wrong label"] * 2 + ["Other"] * 1
)
counts = log.value_counts()
table = pareto_table(counts) # from Step 2
fig = pareto_chart(table, title="Defects") # from Step 3
core = vital_few(table["value"]) # from Step 4
print(table)
print(list(core.index))Run the functions from the earlier steps first (in the same file or session). Notice that value_counts produces a Series whose index holds the category names. This is exactly what pareto_table accepts.
Exercise
A table has five categories with values A=50, B=30, C=10, D=6, E=4, sorted in this order. Using the rule "keep every category whose cumulative share before it is below 80%", which categories does vital_few return, and what share of the total do they cover? Then explain why the filter cum_pct <= 80 would give a different answer for the values A=50, B=25, C=15, D=10.
Show answer
The total is 100, so the cumulative shares are A=50, B=80, C=90, D=96, E=100. The shares before each category are 0, 50, 80, 90, 96. Only the first two are below 80, so vital_few returns A and B, covering 80% of the total. For A=50, B=25, C=15, D=10, the cumulative shares are 50, 75, 90, 100. The filter cum_pct <= 80 keeps A and B, which cover only 75%, so it falls short of the goal. The "share before" rule keeps A, B and C (the shares before are 0, 50, 75, all below 80), which reaches 90% and passes the threshold.