如何使用matplotlib在饼图上显示实际值而不是百分比

9

我希望使用matplotlib创建的饼图能够显示实际值,而不仅仅是百分比。以下是我的代码:

pie_shares= [i for i in mean.values()]
positions = [i for i in mean.keys()]
plt.pie(pie_shares,labels=positions, autopct='%1.1f%%', )
plt.show()

只需删除“autopct=”部分。 - KuboMD
1个回答

10

如果您想显示饼图切片的实际值,您必须将这些值提供给标签:

def autopct_format(values):
    def my_format(pct):
        total = sum(values)
        val = int(round(pct*total/100.0))
        return '{v:d}'.format(v=val)
    return my_format
plt.pie(pie_shares, labels = positions, autopct = autopct_format(pie_shares))

在matplotlib资源中,提到autopct可以是字符串格式和函数形式,因此我们创建了一个自定义函数,以显示通常由此功能使用的百分比中的实际值来格式化每个pct。

这个代码可以运行,但我还需要它同时显示标题(职位)。我应该怎么做? - jd55
请检查我的新编辑。 - SalvadorViramontes
返回逗号分隔的千位数:return '{v:,}'.format(v=val),... - Martin Dvorak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接