0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Add Percentage to Pie Chart in Matplotlib

To add percentage labels to a pie chart in matplotlib, use the autopct parameter in the plt.pie() function. Set autopct='%1.1f%%' to show percentages with one decimal place on each slice.
๐Ÿ“

Syntax

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

plt.pie(data, labels=labels, autopct='%1.1f%%')
  • data: List or array of values for pie slices.
  • labels: List of labels for each slice.
  • autopct: Format string to display percentage on slices.
python
plt.pie(data, labels=labels, autopct='%1.1f%%')
๐Ÿ’ป

Example

This example shows how to create a pie chart with percentage labels on each slice using autopct. The percentages show one decimal place.

python
import matplotlib.pyplot as plt

# Data for pie chart
sizes = [30, 45, 15, 10]
labels = ['Apples', 'Bananas', 'Cherries', 'Dates']

# Create pie chart with percentages
plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title('Fruit Distribution')
plt.show()
Output
A pie chart with four slices labeled 'Apples', 'Bananas', 'Cherries', and 'Dates'. Each slice shows its percentage value like '30.0%', '45.0%', etc.
โš ๏ธ

Common Pitfalls

Common mistakes when adding percentages to pie charts include:

  • Not using autopct, so no percentages appear.
  • Using incorrect format strings, causing errors or wrong display.
  • Passing autopct without percent sign, which shows decimals but no percent symbol.

Always include %% in the format string to show the percent sign.

python
import matplotlib.pyplot as plt

sizes = [40, 35, 25]
labels = ['A', 'B', 'C']

# Wrong: missing percent sign
plt.pie(sizes, labels=labels, autopct='%1.1f')  # Shows decimals but no '%'
plt.title('Wrong autopct usage')
plt.show()

# Correct usage
plt.pie(sizes, labels=labels, autopct='%1.1f%%')  # Shows decimals with '%'
plt.title('Correct autopct usage')
plt.show()
Output
First chart shows slice values like '40.0', '35.0', '25.0' without percent signs. Second chart shows '40.0%', '35.0%', '25.0%' correctly.
๐Ÿ“Š

Quick Reference

Summary tips for adding percentages to pie charts:

  • Use autopct='%1.1f%%' to show one decimal place with percent sign.
  • Use autopct='%1.0f%%' to show whole number percentages.
  • Pass a function to autopct for custom formatting.
  • Always include labels for clarity.
โœ…

Key Takeaways

Use the autopct parameter in plt.pie() to add percentage labels to pie slices.
Include '%%' in the autopct format string to display the percent sign correctly.
Format strings like '%1.1f%%' show percentages with one decimal place.
Labels improve chart readability alongside percentages.
Custom functions can be used in autopct for advanced formatting.