从Matplotlib饼图的图例中获取百分比

6
我已使用matplotlib创建了以下饼图:
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

有没有办法将饼图上的百分比放在图例中,使得图例内容如下:

狗,34%

猫,24%

鸟,18%

鱼,13%

我知道最快、最优雅的方式是将 "labels" 更改为上述内容,但如果直到运行代码后才知道 "sizes" 呢?

1个回答

18

我假设在你绘制图例之前,你应该了解 sizes。类似这样的东西就可以了:

我认为在您绘制图例之前,您应该知道sizes的含义。以下内容可能有所帮助:

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

在此输入图片描述

  • 旧的字符串格式化样式
labels = ['%s, %1.1f %%' % (l, s) for l, s in zip(labels, sizes)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接