Getting percentages in legend from pie matplotlib pie chart

Viewed 12622

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?

1 Answers
Related