Skip to main content
 首页 » 编程设计

python之从 pie matplotlib 饼图中获取图例中的百分比

2025年05月04日25JustinYoung

我在下面使用 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() 

有没有办法将这些百分比放在图例中,而不是在饼图上显示百分比,以便图例显示为:

狗,34%

猫,24%

鸟类,18%

鱼,13%

我知道我可以只更改“标签”来阅读上面的内容,这是最快和最优雅的方式,但是如果您直到代码运行后才知道“大小”怎么办?

请您参考如下方法:

我假设在绘制图例时,您应该知道尺寸。像这样的东西可以做到:

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