Issue
Hi I am trying a plot chart and have some difficulties to show the legend. Here's my code below:
age = ['below 20', '20-30', '30-40', '40-50']
age_count = [23,0,35,0]
labels = age
sizes = age_count
fig1, ax1 = plt.subplots()
ax1.pie(sizes, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.legend(labels,bbox_to_anchor=(1, 0),loc='lower left')
I do not want to show the categories with zero count in the pie chart plot. Still I want to show all the category names (i.e. 20-30,40-50) in the legend. I tried the code above but it is now working. Would like to know where went wrong?
Solution
from matplotlib.pyplot.pie docs:
"autopct None or str or callable, default: None
If not None, is a string or function used to label the wedges with their numeric value. The label will be placed inside the wedge. If it is a format string, the label will be fmt % pct. If it is a function, it will be called."
you can specify a specific bihavier by passing a function to autopct like so:
import matplotlib.pyplot as plt
age = ['below 20', '20-30', '30-40', '40-50']
age_count = [23,0,35,0]
def f(cpt):
if cpt == 0:
return ''
else:
return '%.2f' %cpt
fig1, ax1 = plt.subplots()
ax1.pie(age_count, autopct=f,
shadow=True, startangle=90)
ax1.legend(age,bbox_to_anchor=(1, 0),loc='lower left')
Answered By - Yohai Magan Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.