0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Labels to Pie Chart in Matplotlib Easily

To add labels to a pie chart in matplotlib, use the labels parameter inside the plt.pie() function. Pass a list of label names matching the data slices to display them on the chart.
๐Ÿ“

Syntax

The basic syntax to add labels to a pie chart in matplotlib is:

  • plt.pie(data, labels=labels_list): data is a list or array of values for the pie slices.
  • labels_list is a list of strings representing the label for each slice.

This will display the labels next to each slice on the pie chart.

python
plt.pie(data, labels=labels_list)
๐Ÿ’ป

Example

This example shows how to create a pie chart with labels for each slice using matplotlib.

python
import matplotlib.pyplot as plt

# Data values for pie slices
sizes = [30, 20, 45, 5]

# Labels for each slice
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']

# Create pie chart with labels
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Fruit Distribution')
plt.show()
Output
A pie chart window showing four slices labeled 'Apples', 'Bananas', 'Cherries', and 'Dates' with percentage values on each slice.
โš ๏ธ

Common Pitfalls

Common mistakes when adding labels to pie charts include:

  • Not matching the number of labels to the number of data slices, which causes errors or missing labels.
  • Forgetting to pass the labels parameter inside plt.pie().
  • Using labels but not adding autopct to show percentages, which can make the chart less informative.

Always ensure your labels list length matches your data length.

python
import matplotlib.pyplot as plt

sizes = [40, 30, 30]
labels = ['Cats', 'Dogs']  # Wrong: fewer labels than data

# This will cause a mismatch warning or error
plt.pie(sizes, labels=labels)
plt.show()
Output
ValueError or warning about mismatch between sizes and labels length.
๐Ÿ“Š

Quick Reference

Tips for adding labels to pie charts in matplotlib:

  • Use labels to name slices.
  • Add autopct='%1.1f%%' to show percentages.
  • Ensure label list length equals data length.
  • Use plt.title() to add a chart title.
โœ…

Key Takeaways

Use the labels parameter in plt.pie() to add labels to pie chart slices.
Make sure the labels list matches the number of data points exactly.
Add autopct='%1.1f%%' to display percentage values on the chart.
Always label your chart with plt.title() for clarity.