Search code examples
pythonmatplotlibpie-chart

How to make matplotlib autopct a function of the label name?


I have a simple pie chart in Python:

values = [3, 5, 12, 8]
labels = ['a', 'b', 'c', 'd']
plt.pie(values, labels)

Which looks something like:

pie chart

I also have a dictionary of values:

dictionary = {'a': 0.31, 'b': 0.11, 'c' : 0.07, 'd': 0.12}

I would like to label each slice with its corresponding value in the dictionary. How do I do that? I read this post which demonstrated how to pass extra arguments to the autopct function, but it seems that the arguments must be the same for each slice, whereas in this case, they are different for each slice.


Solution

  • I understand that what you are looking for is to label each piece with the share of the pie defined as values in the dict, is that right ?

    Something like:

    dictionary = {'a': 0.31, 'b': 0.11, 'c' : 0.07, 'd': 0.12}
    labels = dictionary.keys()
    sizes = dictionary.values()
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
    plt.show()
    

    Hope this works for you.