Getting percentages in legend from pie matplotlib pie chart?

做~自己de王妃 提交于 2019-12-24 07:48:25

问题


I have created a pie chart using matplotlib below:

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()

(sorry I do not know how to show the pie chart on 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:


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

plt.legend( loc = 'right', labels=['%s, %1.1f %%' % (l, s) for l, s in zip(labels, sizes)])



来源:https://stackoverflow.com/questions/44076203/getting-percentages-in-legend-from-pie-matplotlib-pie-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!