Python - 如何在饼图中将autopct文本颜色更改为白色?

时间:2015-01-12 09:31:47

标签: python matplotlib

pie(fbfrac,labels = fblabel,autopct='%1.1f%%',pctdistance=0.8,startangle=90,colors=fbcolor)

我的图表显示正如我想要的那样,但如果文本在白色而不是黑色的情况下会更好地突出显示。

3 个答案:

答案 0 :(得分:11)

来自pyplot.pie documentation

  

返回值:

     

如果autopct不是None,则返回元组(补丁,文本,自动缩放),   补丁和文本如上所述,autotexts是列表   数字标签的文本实例。

您需要更改autotexts的颜色;这只是通过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')

这会产生(Hogs and Dogs example): enter image description here

答案 1 :(得分:4)

Pie 对象返回 patches, texts, autotexts。您可以遍历 textsautotextset_color

import matplotlib.pyplot as plt

fblabels = '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

此外,您可以更改单个标签的颜色,访问列表项,例如:texts[0].set_color('blue')

您可以获得更多灵感here

答案 2 :(得分:1)

您可以使用textprops的{​​{1}}参数在一行中完成此操作。很简单:

pyplot.pie

在您的情况下:

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

可以找到一个启发性的示例here