Search code examples
matplotlibpie-chart

Different colors for each label in my pie chart


I know can change all of the label colors using textprops = dict(color = 'white') inside the plt.pie() command however is it possible to have each label have its own color? I have tried the following:

colorlist = ['w','k','r','g']    
textprops = [dict(color = c) for c in colorlist]

which results in the error:

AttributeError: 'list' object has no attribute 'setdefault'

textprops = dict(color = colorlist)

which results in a plot with no labels at all, and finally I tried putting my plt.pie() call into a for loop, but even the simplest version of that didn't work.

sizes = [50,50]
plt.figure(figsize=(15,15))
for i in range(len(sizes)):
    s = sizes[i]
    plt.pie(s)
    plt.axis('equal')
    plt.show()

This gives the error:

TypeError: len() of unsized object

I don't know what else to try, I'm out of ideas.


Solution

  • You can loop over the texts labels returned by the pie and colorize each individually.

    import matplotlib.pyplot as plt
    
    labels = ["AAA", "BBB", "CCC", "DDD"]
    colorlist = ['crimson','k','r','gold']    
    sizes = [10,20,20,40]
    
    plt.figure()
    
    wedges, texts = plt.pie(sizes, labels=labels)
    for text, color in zip(texts, colorlist):
        text.set_color(color)
    
    plt.show()
    

    enter image description here