Skip to content Skip to sidebar Skip to footer

Python - How To Change Autopct Text Color To Be White In A Pie Chart?

pie(fbfrac,labels = fblabel,autopct='%1.1f%%',pctdistance=0.8,startangle=90,colors=fbcolor) I have the chart displaying just as I want it, with the exception that the text will st

Solution 1:

From pyplot.pie documentation:

Return value:

If autopct is not None, return the tuple (patches, texts, autotexts), where patches and texts are as above, and autotexts is a list of Text instances for the numeric labels.

You need to change the color of autotexts; this is done simply by set_color():

_, _, autotexts = pie(fbfrac,labels = fblabel,autopct='%1.1f%%',pctdistance=0.8,startangle=90,colors=fbcolor)
for autotext in autotexts:
    autotext.set_color('white')

This yields (with Hogs and Dogs example): enter image description here

Solution 2:

You can do it in one line using textprops argument of pyplot.pie. It's simple:

plt.pie(data, autopct='%1.1f%%', textprops={'color':"w"})

In your case:

pie(fbfrac, labels=fblabel, autopct='%1.1f%%', pctdistance=0.8, startangle=90, colors=fbcolor, textprops={'color':"w"})

An enlightening example can be found here.

Solution 3:

Pie object returns patches, texts, autotexts. You can loop through the texts and autotext and set_color.

import matplotlib.pyplot as pltfblabels='Frogs', 'Hogs', 'Dogs', 'Logs'
fbfrac = [15, 30, 45, 10]
fbcolor = ["blue", "green", "red", "orange"]


fig, ax = plt.subplots()
patches, texts, autotexts  = ax.pie(fbfrac, labels = fblabels, autopct='%1.1f%%',pctdistance=0.8,startangle=90,colors=fbcolor)
[text.set_color('red') for text in texts]
texts[0].set_color('blue')
[autotext.set_color('white') for autotext in autotexts]

plt.show()

Output

Moreover you can change the color for individual label, accessing the list item, e.g: texts[0].set_color('blue')

You can get more inspiration here.

Post a Comment for "Python - How To Change Autopct Text Color To Be White In A Pie Chart?"