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

时间:2018-12-14 15:27:20

标签: python matplotlib

我希望使用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()

1 个答案:

答案 0 :(得分:1)

如果要显示饼图切片的实际值,则必须向标签提供这些值:

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以显示此功能通常使用的百分比的实际值。