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

标签 python matplotlib charts

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

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

最佳答案

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

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

enter image description here

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

关于python - 从 pie matplotlib 饼图中获取图例中的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44076203/

相关文章:

python - "Three-bonacchi"序列

python - 为什么 Matplotlib 的 PdfPages 将选项卡打印为框(字体编码)?

带有实时数据和可滚动内容的 JavaScript 图表?

python - 计算 n 个列表的所有可能组合的总和并检查与特定值的比较

python子进程通信卡住

python - 网络x : multiple figure with consistent node placement

python - 将椭圆拟合到python中的一组数据点

python - 如何使用 plotly_express 绘制多折线图?

javascript - 旋转的 X 轴标签与图形本身重叠

python - 更改后强制 scapy 重新剖析图层