By the end of this lesson, you will be able to create clear pie charts in Python using Matplotlib to visualize how parts contribute to a whole.
What it is
A pie chart is a circular statistical graphic divided into slices to illustrate numerical proportion. Each slice's arc length (and consequently its central angle and area) is proportional to the quantity it represents. In Python, we primarily use the matplotlib.pyplot.pie() function to generate these visualizations. Key terms include slices (the individual segments), labels (text identifying each segment), and autopct (a format string for displaying percentages).
Why it matters
- Intuitive Proportions: It provides an immediate visual understanding of how much space or budget each category occupies relative to the total.
- Composition Analysis: Ideal for showing market share, survey results, or resource allocation where the sum of parts equals 100%.
- Simplicity: Requires minimal data preparation compared to complex multi-axis charts.
- Stakeholder Communication: Non-technical audiences often find pie charts easier to interpret than bar charts for simple "part-to-whole" relationships.
Syntax or steps
The basic syntax requires a list of values representing the size of each wedge. Optional arguments allow customization of labels, colors, and percentage displays.
plt.pie(x, labels=None, autopct=None, startangle=90)
x: Array-like sequence of sizes.labels: List of strings for each slice.autopct: Format string (e.g.,'%1.1f%%') to display percentages inside slices.startangle: Rotates the start of the pie from the default x-axis.
Example
Here is a realistic example visualizing monthly household expenses.
import matplotlib.pyplot as plt
# Data: Expense categories and amounts
categories = ['Rent', 'Food', 'Transport', 'Entertainment', 'Savings']
amounts = [1200, 400, 150, 200, 300]
# Create the pie chart
plt.figure(figsize=(8, 6))
plt.pie(amounts,
labels=categories,
autopct='%1.1f%%',
startangle=140,
shadow=True)
# Equal aspect ratio ensures that pie is drawn as a circle
plt.axis('equal')
plt.title('Monthly Household Expenses')
plt.show()
Explanation: We define two lists: categories for names and amounts for values. The plt.pie() call maps these together. autopct='%1.1f%%' calculates the percentage automatically based on the sum of amounts. shadow=True adds depth, and plt.axis('equal') prevents the chart from looking like an ellipse due to figure dimensions.
Common mistakes
- Too many slices: Pie charts become unreadable with more than 5-7 categories. Group small items into an "Other" category.
- Misleading 3D effects: Using
explodeexcessively or 3D rendering distorts perspective, making smaller slices look larger than they are. - Ignoring order: By default, slices start at the right side (0 degrees). Use
startangle=90to start at the top, which is often more intuitive for reading clockwise. - Missing totals: If the data doesn't sum to 100%, ensure
autopctis used so viewers understand the proportions relative to the actual sum, not just raw numbers.
When to use it
Pie charts are best for simple composition. For comparing magnitudes across many categories, bar charts are superior.
| Chart Type | Best Used For | Limitation |
|---|---|---|
| Pie Chart | Showing part-to-whole relationship with few categories (<6). | Hard to compare similar-sized slices accurately. |
| Bar Chart | Comparing quantities across many categories. | Does not inherently show contribution to a total. |
Practice
Guided Exercise: Modify the example above to highlight the "Rent" category by pulling it slightly away from the center using the explode parameter.
Challenge: Create a donut chart by adding a white circle in the center of your existing pie chart. Hint: Use plt.Circle((0, 0), 0.70, color='white') and add it to the axes.
Quick check
Question: What does the autopct parameter do?
Answer: It formats and displays the percentage value of each slice directly on the chart.
Summary
Pie charts effectively communicate proportions when kept simple and clearly labeled. Use matplotlib.pyplot.pie() with autopct and appropriate starting angles to create professional, readable visualizations for part-to-whole data.