How do I use matplotlib autopct?

后端 未结 7 1649
野的像风
野的像风 2020-12-12 11:59

I\'d like to create a matplotlib pie chart which has the value of each wedge written on top of the wedge.

The documentation suggests I should use autopct

7条回答
  •  無奈伤痛
    2020-12-12 12:16

    As autopct is a function used to label the wedges with their numeric value, you can write there any label or format items quantity with it as you need. The easiest approach for me to show percentage label is using lambda:

    autopct = lambda p:f'{p:.2f}%'
    

    or for some cases you can label data as

    autopct = lambda p:'any text you want'
    

    and for your code, to show percentage you can use:

    plt.figure()
    values = [3, 12, 5, 8] 
    labels = ['a', 'b', 'c', 'd'] 
    plt.pie(values, labels=labels, autopct=lambda p:f'{p:.2f}%, {p*sum(values)/100 :.0f} items')
    plt.show()
    

    and result will be like:

提交回复
热议问题