Python 如何在matplotlib piechart中以文本格式正确绘制浮点数?

Python 如何在matplotlib piechart中以文本格式正确绘制浮点数?,python,python-3.x,matplotlib,floating-point,integer,Python,Python 3.x,Matplotlib,Floating Point,Integer,我做了一个聚类算法,并用饼图表示结果,如下所示 fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal")) contents = [] for k,v in clusters.items(): indi= str(len(clusters[k])) + " users " + "Cluster_"+ str(k) contents.append(indi) #contents = [

我做了一个聚类算法,并用饼图表示结果,如下所示

fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []

for k,v  in clusters.items():
    indi= str(len(clusters[k])) + " users " +  "Cluster_"+ str(k)
    contents.append(indi)

#contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]


def func(pct, allvals):
    absolute = int(pct/100.*np.sum(allvals))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)


wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")

尽管每个集群中的用户分别是23和21,但柱状图显示的是22和20。在def func中,int转换不是将数字四舍五入到最接近的数字,也就是说,如果它是22.9,则显示为22。如果一定要凑齐的话,不是应该是23吗

将int更改为int:

输出:


非常感谢。我已经做到了。如果值介于22.5的中间,这会失去价值吗?我是说,这是一种有效的方法吗?def funcpct,allvals:absolute=introundpct/100.*np.sumallvals返回{.0f}%\n{:d}users.formatpct,absolute@PH round舍入到最近的偶数,所以round22.5==22和round77.5==78,所以没有。但是如果有两个以上的分区,可能会出现如下情况:round22.5==22,round22.5==22,round0.5==0,round54.5==54,所以sum=98,而不是100,所以在这里你需要小心。我很担心。有没有其他方法可以让我直接从列表中显示数字,而不是计算百分比然后再计算数字?
fig, ax = plt.subplots(figsize=(20, 10), subplot_kw=dict(aspect="equal"))
contents  = []


contents = ['23 users Cluster_0', '21 users Cluster_1']

data = [float(x.split()[0]) for x in contents]
Cluster= [x.split()[-1] for x in contents]


def func(pct, allvals):
    absolute = int(round(pct/100.*np.sum(allvals)))
    return "{:.0f}%\n({:d} users)".format(pct, absolute)


wedges, texts, autotexts = ax.pie(data, autopct=lambda pct: func(pct, data),
                                  textprops=dict(color="w"))

ax.legend(wedges, Cluster,
          title="CLuster",
          loc="center left",
          bbox_to_anchor=(1, 0, 0.5, 1))

plt.setp(autotexts, size=10, weight="bold")

ax.set_title("Distribution of users: A pie chart")