Matplotlib Pie Charts
Communicate proportions with pie and donut charts while preserving clarity and accuracy.
Basic Pie Chart
labels = ["North", "South", "East", "West"]
shares = [30, 25, 20, 25]
fig, ax = plt.subplots()
ax.pie(shares, labels=labels, autopct="%1.0f%%", startangle=90)
ax.axis("equal") # Ensures a circleAlways set equal aspect ratio to avoid distorted wedges.
Exploding a Slice
Highlight a segment by offsetting it from the center with the explode argument.
explode = [0.1 if label == "North" else 0 for label in labels]
ax.pie(shares, labels=labels, explode=explode, autopct="%1.0f%%")Donut Charts
Create donut charts by adding a white circle patch.
wedges, texts, autotexts = ax.pie(shares, labels=labels, autopct="%1.0f%%")
centre_circle = plt.Circle((0, 0), 0.70, fc="white")
fig.gca().add_artist(centre_circle)Display totals or metadata in the center for quick reference.
Color Palettes
Define accessible color palettes and share them throughout the organization via info.studygrid@gmail.com.
colors = ["#2563eb", "#f97316", "#22c55e", "#9333ea"]
ax.pie(shares, colors=colors, labels=labels)When to Use Alternatives
Pie charts are best for limited categories with significant differences. For detailed comparisons, consider bar charts or treemaps.
Next Steps
You have completed the Matplotlib section. Continue to the Machine Learning tutorials to analyze data with statistical and predictive techniques.
Labels, Percentages, and Explode
import matplotlib.pyplot as plt
sizes = [35, 25, 20, 20]
labels = ["Python", "SQL", "JS", "Other"]
explode = [0.1, 0, 0, 0] # pull out the first slice
plt.pie(sizes, labels=labels, explode=explode,
autopct="%1.1f%%", startangle=90)
plt.axis("equal") # keep it circular
plt.show()Pie charts get hard to read past ~5 slices, and humans judge angles poorly. For precise comparisons, a bar chart is usually clearer.
Try It Yourself
Exercise: Make a pie chart of a budget: Rent 50%, Food 30%, Fun 20%, with percentages shown.
Show solution
import matplotlib.pyplot as plt
plt.pie([50, 30, 20], labels=["Rent", "Food", "Fun"], autopct="%1.0f%%")
plt.show()Key Takeaways
- Pie charts show parts of a whole.
autopctadds percentages;explodehighlights a slice.- Prefer bar charts when you have many categories or need precision.
📘 Real-World Deep Dive
Knowing <strong>Matplotlib Pie Charts (Matplotlib)</strong> well is what turns Matplotlib from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Matplotlib Pie Charts that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import matplotlib.pyplot as plt
labels = ["A", "B", "C"]; sizes = [45, 30, 25]
plt.pie(sizes, labels=labels, autopct="%1.1f%%", startangle=90)
plt.axis("equal"); plt.show()Expected Output
(no output)Common mistakes
- Calling
plt.plotwithoutplt.show()in scripts (orplt.savefig) produces no visible output. - Passing mismatched array shapes to
plt.plot(x, y)raises a uselessValueError— verify shapes withx.shapeandy.shapefirst. - Mixing
numpy.float64withpandas.Seriesis OK, but mixingnumpy.datetime64with Pythondatetime.dateneeds an explicit cast. - Treating Matplotlib Pie Charts as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- For large scatter plots use
plt.scatter(..., s=1, rasterised=True)or switch todatashader. - Use the
aggbackend on web services:import matplotlib; matplotlib.use("Agg"). - Plot once and reuse the figure: avoid embedding Matplotlib into tight Python loops without an explicit
clear(). - When working with Matplotlib, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.