【问题标题】:Getting percentages in legend from pie matplotlib pie chart从饼图matplotlib饼图中获取图例中的百分比
【发布时间】:2021-05-13 03:36:51
【问题描述】:

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

我知道我可以将“标签”更改为以最快和最优雅的方式阅读上述内容,但是如果您在运行代码之前不知道“大小”怎么办?

【问题讨论】:

    标签: python matplotlib charts


    【解决方案1】:

    我假设在您绘制图例时,您应该知道 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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多