Pie and Donut Charts
Python · Data Visualization
Theory
A pie chart shows how a whole splits into parts: each slice's angle is its share of the total. ax.pie(values, labels=names, autopct='%1.1f%%') draws the slices and writes each percentage, which matplotlib computes as value / total x 100. A donut chart is the same pie with the centre removed, made with wedgeprops=dict(width=0.4); the hole leaves space for a total in the middle with ax.text.
Pies work only in a narrow case: a few parts (ideally 2 to 5) of one meaningful whole, with clearly different sizes, such as UPI 54%, card 23%, cash 16%. People judge angles much less accurately than lengths, so similar slices like 23% and 21% look the same, many slices become unreadable and comparing two pies side by side is hard. In those cases, a sorted bar chart or a 100% stacked bar shows the same data more clearly.
Why we use it
When the message is simply 'this part is most of the total', a pie or donut gets it across instantly to non-technical readers, and the percentage labels make the shares explicit.
When to use it
Use a pie or donut for 2 to 5 parts of a single total that add up to 100%. Do not use one for many categories, values that do not form a whole, negative numbers, changes over time or close comparisons; use a bar chart instead.
How it works
- Parts of a total
- Do the parts add up to one meaningful whole? Yes: Continue. No: Use a bar chart.
- Five or fewer clearly different parts? Yes: Pie or donut with autopct labels. No: Sorted bar or 100% stacked bar.
- Start at 90 degrees and order slices by size
- Share-of-total chart
Syntax
ax.pie(values, labels=names, autopct='%1.1f%%', startangle=90)
ax.pie(values, wedgeprops=dict(width=0.4)) # donut
ax.text(0, 0, 'Total', ha='center')Example
fig, ax = plt.subplots()
ax.pie([540, 230, 160], labels=['UPI', 'Card', 'Cash'], autopct='%1.1f%%')Key points
- Slices must be parts of one whole that sum to 100%
- Keep to about 2-5 slices; group the rest as 'Other'
- Angles are hard to compare; bars are read more accurately
- A donut is a pie with wedgeprops=dict(width=...)
- autopct='%1.1f%%' prints each slice's percentage