Matplotlib Pie Charts
A pie chart shows how a whole is split into parts. Each wedge's angle is proportional to its share of the total. Pie charts work best with a handful of categories whose shares differ clearly.
A basic pie
plt.pie(values) computes the shares itself: you don't need percentages, any positive numbers will do.
import matplotlib.pyplot as plt
budget = [1200, 450, 300, 250, 180]
labels = ["Rent", "Food", "Transport", "Leisure", "Savings"]
plt.pie(budget, labels=labels)
plt.title("Monthly budget")
plt.show()
total = sum(budget)
for name, amount in zip(labels, budget):
print(f"{name:<9} {amount / total:6.1%}")Rent 50.4%
Food 18.9%
Transport 12.6%
Leisure 10.5%
Savings 7.6%
The first wedge starts at the positive x axis (3 o'clock) and the wedges go counter-clockwise.
Percentages, start angle and direction
| Argument | Meaning |
|---|---|
labels |
Text next to each wedge |
autopct |
Format string (or function) for the percentage inside each wedge, e.g. "%1.1f%%" |
startangle |
Where the first wedge starts, in degrees counter-clockwise from 3 o'clock |
counterclock |
False to go clockwise |
colors |
List of wedge colours |
explode |
Fraction of the radius to pull each wedge out |
shadow |
Draw a shadow |
Starting at 12 o'clock and going clockwise matches how people read a clock:
import matplotlib.pyplot as plt
votes = [412, 318, 165, 105]
parties = ["Blue", "Orange", "Green", "Other"]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#bbbbbb"]
wedges, texts, autotexts = plt.pie(
votes, labels=parties, colors=colors,
autopct="%1.1f%%", startangle=90, counterclock=False,
)
plt.title("Election result")
plt.show()
print("Percentages:", [t.get_text() for t in autotexts])Percentages: ['41.2%', '31.8%', '16.5%', '10.5%']
With autopct, pie() returns three lists: wedges, label texts and percentage texts. In "%1.1f%%", %1.1f formats the number with one decimal and %% prints a literal percent sign.
Exploding a wedge
explode takes one value per wedge. A small offset on a single wedge draws attention to it:
import matplotlib.pyplot as plt
sources = ["Search", "Direct", "Social", "Email", "Ads"]
visits = [46, 22, 15, 9, 8]
explode = [0.1 if s == "Social" else 0 for s in sources]
plt.pie(visits, labels=sources, explode=explode, autopct="%d%%",
startangle=90, counterclock=False, shadow=True)
plt.title("Where visitors come from")
plt.show()
print("Highlighted:", sources[explode.index(0.1)])Highlighted: Social
Legends and donut charts
With small wedges, labels around the pie can collide. A legend is often cleaner. Setting wedgeprops={"width": 0.4} cuts out the centre and turns the pie into a donut, leaving room for a total in the middle:
import matplotlib.pyplot as plt
storage = {"Photos": 58.2, "Apps": 31.5, "Music": 12.4, "Documents": 6.1, "Other": 9.8}
fig, ax = plt.subplots(figsize=(6, 4))
wedges, _ = ax.pie(storage.values(), startangle=90, counterclock=False,
wedgeprops={"width": 0.4, "edgecolor": "white"})
total = sum(storage.values())
ax.text(0, 0, f"{total:.0f} GB", ha="center", va="center", fontsize=16)
ax.legend(wedges, storage.keys(), loc="center left", bbox_to_anchor=(1, 0.5))
ax.set_title("Phone storage")
plt.show()
print("Total:", round(total, 1), "GB in", len(storage), "categories")Total: 118.0 GB in 5 categories
bbox_to_anchor=(1, 0.5) places the legend just outside the right edge of the Axes. The Legends lesson covers this in detail.
Note: People compare lengths far more accurately than angles. When categories have similar sizes, or there are more than about six, a sorted bar chart communicates better than a pie.
Test yourself
Do the values passed to plt.pie() have to add up to 100?
- Yes, always
- No, Matplotlib divides each value by the total
- Only when autopct is used
- They must add up to 1
What does autopct="%1.1f%%" display?
- The raw values
- Each wedge's percentage with one decimal and a % sign
- The labels in bold
- The angle in degrees
How do you turn a pie into a donut chart?
- plt.donut()
- hole=True
- wedgeprops={"width": 0.4}
- explode=[0.5, 0.5]