Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Make the data visible
EXPERIMENT 54 / 101

Parts of a real whole.

Use a part-to-whole chart only when the categories actually form one whole.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

A pie chart can communicate a few broad shares when categories are nonoverlapping parts of one meaningful total. It is a poor choice for many categories, small differences, negative values, or unrelated quantities. For precise comparisons, a bar chart is often easier to read. Never use a pie merely because the data happens to contain numbers.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

matplotlib_pie.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 4), layout="constrained")
ax.pie([50, 30, 20], labels=["Build", "Test", "Review"], autopct="%1.0f%%", startangle=90,
       colors=["#ed5027", "#a7b88f", "#536643"], wedgeprops={"edgecolor": "white"})
ax.set(title="Share of planned effort")
fig.savefig("matplotlib-pie.png", dpi=140, bbox_inches="tight")
plt.close(fig)
print("Saved matplotlib-pie.png")
↳ EXPECTED OUTPUT
Saved matplotlib-pie.png
Pie charts & percentage caveats: chart generated by the Python example
THE OUTPUT, MADE VISIBLE · Generated from this lesson’s example.
Download chart ↗

03 Under the hood

  1. 1

    The values sum to one hundred in this example, but pie uses their relative shares even when they sum to another positive total.

  2. 2

    autopct formats percentages of the total. The labels need to identify categories, while the title explains what the total represents.

  3. 3

    Check that no observation belongs to multiple categories. Overlapping categories do not represent disjoint slices of one total.

04 Your turn, builder

A SMALL MISSION

Represent a two-part split and include the total count in the title.

Reveal one possible solution +
one_possible_solution.py
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 4), layout="constrained")
ax.pie([8, 2], labels=["Complete", "Open"], autopct="%1.0f%%", colors=["#a7b88f", "#ed5027"])
ax.set(title="10 tasks, two states")
fig.savefig("challenge.png", dpi=140, bbox_inches="tight")
plt.close(fig)
print("Saved challenge.png")

05 Check your signal

QUICK SIGNAL CHECK

Which data is unsuitable for a normal part-to-whole pie?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.