将值标签(不是百分比)添加到圆环图 - matplotlib

Add value labels (not percentages) to donut chart - matplotlib

我想为圆环图显示实际值标签而不是 %age 值。下面的代码生成了一个非常漂亮的圆环图,但显示的值是 %ages 而不是它们的实际值。

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) 而不是它们的百分比值吗?或者,显示 %ages 及其实际对应值(即 1851、45.4% 和 2230、54.6%)?

总结我的意见,试试这个:

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

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