Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

python - Getting percentages in legend from pie matplotlib pie chart

I have created a pie chart using matplotlib below:

import matplotlib.pyplot as plt
labels = ['dogs','cats','birds','fish']
sizes = [34, 24,18,13]
pie = plt.pie(sizes,autopct='%1.1f%%', startangle=90)
plt.axis('equal')
plt.legend( loc = 'right', labels=labels)
plt.show()

enter image description here

Instead of having the percentages on the pie slices, is there a way to put these percentages within the legend so that the legend reads:

dogs, 34%

cats, 24%

birds, 18%

fish, 13%

I know I can just change the "labels" to read the above as the fastest and most elegant way, but what if you do not know "sizes" until after the code is ran?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume by the time you draw the legend, you should know sizes. Something like this would do it:

# use a list comprehension to update the labels
labels = [f'{l}, {s:0.1f}%' for l, s in zip(labels, sizes)]
plt.legend(bbox_to_anchor=(0.85, 1), loc='upper left', labels=labels)

enter image description here

  • Older string formatting style
labels = ['%s, %1.1f %%' % (l, s) for l, s in zip(labels, sizes)]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...