从饼图matplotlib饼图中获取图例百分比

从饼图matplotlib饼图中获取图例百分比

本文介绍了从饼图matplotlib饼图中获取图例百分比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的matplotlib创建了一个饼图:

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:

狗,34%

猫,24%

鸟,18%

鱼,13%

我知道我可以更改标签以最快和最优雅的方式阅读以上内容,但是如果您不知道 sizes,直到代码出现后该怎么办?跑了吗

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?

推荐答案

我假设在绘制图例时,您应该知道大小。这样的事情可以做到:

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 zip中的l,s(标签,尺寸)])

这篇关于从饼图matplotlib饼图中获取图例百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:18