将值标签(而非百分比)添加到甜甜圈图-Matplotlib

时间:2019-12-27 22:36:17

标签: python matplotlib donut-chart

我想显示实际值标签而不是甜甜圈图的%age值。以下代码生成了一个非常漂亮的甜甜圈图,但是显示的值是%age的值,而不是实际值。

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

#create labels and values for pie/donut plot
labels = 'ms', 'ps'
sizes = [1851, 2230]

#create center white circle
centre_circle = plt.Circle((0, 0), 0.7, color='white')

#create pie chat
plt.pie(sizes, labels= labels, autopct='%1.1f%%',pctdistance = 1.25,startangle=90,
        labeldistance=.8, colors = ["tab:blue", "tab:orange"])
plt.axis('equal')
plt.gca().add_artist(centre_circle)

#Display
plt.show();

我的输出如下所示。

有人可以指导我如何显示实际值(1851、2230),而不是如何在此图中显示其百分比值吗?或者,同时显示百分比年龄及其实际对应值(即1851、45.4%和2230、54.6%)?

1 个答案:

答案 0 :(得分:1)

总结我的评论,请尝试以下操作:

import matplotlib.pyplot as plt


labels = 'ms', 'ps'
sizes = 1851, 2230
pcts = [f'{s} {l}\n({s*100/sum(sizes):.2f}%)' for s,l in zip(sizes, labels)]
width = 0.35

_, ax = plt.subplots()
ax.axis('equal')

pie, _ = ax.pie(
    sizes,
    startangle=90,
    labels=pcts,
#    labeldistance=.8,
#    rotatelabels=True,
    colors = ["tab:blue", "tab:orange"]
)

plt.setp(pie, width=width, edgecolor='white')

plt.show()

这是上面代码片段的输出:

Chart