Python - How to change autopct text color to be white in a pie chart?

Jsu*_*suf 5 python matplotlib

pie(fbfrac,labels = fblabel,autopct='%1.1f%%',pctdistance=0.8,startangle=90,colors=fbcolor)
Run Code Online (Sandbox Code Playgroud)

I have the chart displaying just as I want it, with the exception that the text will stand out better inside the plot if it is white instead of black.

And*_*lev 14

来自pyplot.pie文档:

返回值:

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

你需要改变颜色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')
Run Code Online (Sandbox Code Playgroud)

这会产生(以Hogs和Dogs为例): 在此输入图像描述


kir*_*ril 11

您可以使用textpropsof 参数在一行中完成pyplot.pie。这很简单:

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

在你的情况下:

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

一个启发性的例子可以在这里找到。

  • 当我使用它时,它也将我的外部标签变成白色,使它们不可见。 (7认同)

小智 5

Pie 对象返回patches, texts, autotexts. 您可以遍历textsandautotextset_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()
Run Code Online (Sandbox Code Playgroud)

输出

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

您可以在这里获得更多灵感。