How to Create Pie Chart in Matplotlib: Simple Guide
To create a pie chart in
matplotlib, use the plt.pie() function with a list of values representing the slices. You can add labels, colors, and percentages to make the chart clear and informative.Syntax
The basic syntax for creating a pie chart in Matplotlib is:
plt.pie(x, labels=None, colors=None, autopct=None, startangle=0)
Where:
xis a list or array of numeric values for each slice.labelsis an optional list of names for each slice.colorsis an optional list of colors for the slices.autopctis a format string to display percentages on slices (e.g.,'%1.1f%%').startanglerotates the start of the pie chart for better orientation.
python
plt.pie(x, labels=None, colors=None, autopct=None, startangle=0)
Example
This example shows how to create a simple pie chart with labels and percentage display.
python
import matplotlib.pyplot as plt sizes = [30, 20, 25, 25] labels = ['Apples', 'Bananas', 'Cherries', 'Dates'] colors = ['red', 'yellow', 'pink', 'brown'] plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90) plt.title('Fruit Distribution') plt.axis('equal') # Equal aspect ratio makes the pie circular plt.show()
Output
A circular pie chart with four colored slices labeled Apples, Bananas, Cherries, Dates, each showing their percentage values.
Common Pitfalls
Common mistakes when creating pie charts include:
- Not setting
plt.axis('equal'), which can distort the pie into an ellipse. - Passing non-numeric or empty data to
plt.pie(). - Not matching the length of
labelsorcolorsto the data length. - Using
autopctwithout a proper format string, causing errors or no percentage display.
Always check your data and parameters carefully.
python
import matplotlib.pyplot as plt # Wrong: missing axis equal, labels length mismatch sizes = [40, 30, 30] labels = ['A', 'B'] # fewer labels than sizes # This will cause a warning or error plt.pie(sizes, labels=labels) plt.show() # Right way: labels = ['A', 'B', 'C'] plt.pie(sizes, labels=labels) plt.axis('equal') plt.show()
Output
First plot may show a warning or incorrect labels; second plot shows a correct circular pie chart with matching labels.
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| x | List of slice sizes | [30, 20, 25, 25] |
| labels | Names for slices | ['Apples', 'Bananas', 'Cherries', 'Dates'] |
| colors | Colors for slices | ['red', 'yellow', 'pink', 'brown'] |
| autopct | Show percentage on slices | '%1.1f%%' |
| startangle | Rotate start angle | 90 |
| plt.axis('equal') | Make pie circular | plt.axis('equal') |
Key Takeaways
Use plt.pie() with numeric data and optional labels to create pie charts.
Always call plt.axis('equal') to keep the pie chart circular.
Ensure labels and colors match the number of data points.
Use autopct='%1.1f%%' to display slice percentages clearly.
Check your data to avoid errors or distorted charts.