0
0
MatplotlibHow-ToBeginner ยท 3 min read

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:

  • x is a list or array of numeric values for each slice.
  • labels is an optional list of names for each slice.
  • colors is an optional list of colors for the slices.
  • autopct is a format string to display percentages on slices (e.g., '%1.1f%%').
  • startangle rotates 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 labels or colors to the data length.
  • Using autopct without 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

ParameterDescriptionExample
xList of slice sizes[30, 20, 25, 25]
labelsNames for slices['Apples', 'Bananas', 'Cherries', 'Dates']
colorsColors for slices['red', 'yellow', 'pink', 'brown']
autopctShow percentage on slices'%1.1f%%'
startangleRotate start angle90
plt.axis('equal')Make pie circularplt.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.