Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to add a legend to a Matplotlib pie chart?
A legend in a Matplotlib pie chart helps identify different sections by mapping colors to category names. You can add a legend using the legend() method with the patches returned by pie().
Basic Pie Chart with Legend
Create a simple pie chart and add a legend using patches ?
import matplotlib.pyplot as plt
# Data for the pie chart
labels = ['Walk', 'Talk', 'Sleep', 'Work']
sizes = [23, 45, 12, 20]
colors = ['red', 'blue', 'green', 'yellow']
# Create pie chart and get patches
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
# Add legend
plt.legend(patches, labels, loc="best")
# Make the pie chart circular
plt.axis('equal')
plt.title('Daily Activities')
plt.show()
Legend with Custom Position
You can position the legend at specific locations using the loc parameter ?
import matplotlib.pyplot as plt
labels = ['Python', 'Java', 'JavaScript', 'C++']
sizes = [35, 25, 25, 15]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
patches, texts = plt.pie(sizes, colors=colors, autopct='%1.1f%%', startangle=140)
# Legend positioned on the right
plt.legend(patches, labels, loc='center left', bbox_to_anchor=(1, 0.5))
plt.axis('equal')
plt.title('Programming Languages Usage')
plt.tight_layout()
plt.show()
Legend Options
| Location Parameter | Position | Best For |
|---|---|---|
'best' |
Automatic placement | When unsure about position |
'upper right' |
Top right corner | Standard placement |
'center left' |
Left side, centered | When chart is on the right |
bbox_to_anchor |
Custom coordinates | Precise positioning |
Key Points
- Use
patches, texts = plt.pie()to get legend handles - The
legend()method takes patches and labels as arguments - Use
locparameter to control legend position - Add
bbox_to_anchorfor precise positioning outside the plot area - Use
tight_layout()to prevent legend cutoff
Conclusion
Adding a legend to pie charts improves readability by clearly labeling each section. Use the legend() method with patches from pie() and customize the position as needed.
Advertisements
