向圆环图matplotlib添加值标签(而不是百分比)

2024-06-25 22:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为油炸圈饼图表显示实际值标签,而不是%年龄值。下面的代码生成了一个非常好的油炸圈饼图,但是显示的值是%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();

我的输出如下所示。你知道吗

有人能告诉我如何在这个图上显示实际值(18512230)而不是它们的百分比值吗?或者,显示年龄百分比及其实际对应值(即1851,45.4%和2230,54.6%)?你知道吗


Tags: importlabelsmatplotlibascreateplttabwhite
1条回答
网友
1楼 · 发布于 2024-06-25 22:31:22

总结我的评论,试试这个:

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

相关问题 更多 >