Python 如何更改图例中字体的文本颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18909696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the text colour of font in legend?
提问by firefly
Is there a way to change the font colour of the legend in a matplotlib plot?
有没有办法在 matplotlib 图中更改图例的字体颜色?
Specially in occasions where the background of the plot is dark, the default black text in the legend is hard or impossible to read.
特别是在情节背景较暗的情况下,图例中的默认黑色文本很难或无法阅读。
采纳答案by HYRY
call Legend.get_texts()
will get a list of Text object in the legend object:
调用Legend.get_texts()
将获取图例对象中的 Text 对象列表:
import pylab as pl
pl.plot(randn(100), label="randn")
l = legend()
for text in l.get_texts():
text.set_color("red")
回答by wordsforthewise
You can also do it with setp():
你也可以用 setp() 来做到:
import pylab as plt
leg = plt.legend(framealpha = 0, loc = 'best')
for text in leg.get_texts():
plt.setp(text, color = 'w')
this method also allows you to set the fontsize and any number of other font properties in one line (listed here: http://matplotlib.org/users/text_props.html)
此方法还允许您在一行中设置字体大小和任意数量的其他字体属性(此处列出:http: //matplotlib.org/users/text_props.html)
full example:
完整示例:
import pylab as plt
x = range(100)
y1 = range(100,200)
y2 = range(50,150)
fig = plt.figure(facecolor = 'k')
ax = fig.add_subplot(111, axisbg = 'k')
ax.tick_params(color='w', labelcolor='w')
for spine in ax.spines.values():
spine.set_edgecolor('w')
ax.plot(x, y1, c = 'w', label = 'y1')
ax.plot(x, y2, c = 'g', label = 'y2')
leg = plt.legend(framealpha = 0, loc = 'best')
for text in leg.get_texts():
plt.setp(text, color = 'w')
plt.show()
回答by Till Hoffmann
Because plt.setp
broadcasts over iterables, you can also modify the text color in one line:
因为plt.setp
在迭代器上广播,您还可以在一行中修改文本颜色:
# Show some cool graphs
legend = plt.legend()
plt.setp(legend.get_texts(), color='w')
The last line will apply the colour to all elements in the collection of texts.
最后一行将颜色应用于文本集合中的所有元素。