如何更改图例中字体的文字颜色?

时间:2013-09-20 05:49:01

标签: python colors fonts matplotlib legend

有没有办法在matplotlib图中更改图例的字体颜色?

特别是在情节背景较暗的情况下,图例中的默认黑色文字很难或无法读取。

5 个答案:

答案 0 :(得分:21)

call 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")

答案 1 :(得分:10)

您也可以使用setp():

import pylab as plt

leg = plt.legend(framealpha = 0, loc = 'best')
for text in leg.get_texts():
    plt.setp(text, color = 'w')

此方法还允许您在一行中设置fontsize和任意数量的其他字体属性(在此处列出:http://matplotlib.org/users/text_props.html

完整示例:

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()

答案 2 :(得分:8)

因为plt.setp广播可迭代,你也可以在一行中修改文字颜色:

# Show some cool graphs
legend = plt.legend()
plt.setp(legend.get_texts(), color='w')

最后一行将颜色应用于文本集合中的所有元素。

答案 3 :(得分:6)

从matplotlib版本3.3.0开始,您现在可以直接在matplotlib.pyplot.legend()中使用关键字参数labelcolor


通过设置labelcolor='linecolor'使用与相应艺术家相同的颜色的示例:

import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(4, 3))
plt.plot(np.arange(10), np.random.rand(10) * 0, '-', label='spam')
plt.plot(np.arange(10), np.random.rand(10) * 1, ':', label='ham')
plt.plot(np.arange(10), np.random.rand(10) * 2, 'o', label='eggs')
plt.legend(labelcolor='linecolor')

matplotlib legend text color: 'linecolor'


示例通过设置labelcolor='w'将所有文本更改为白色,例如对于深色背景:

import matplotlib.pyplot as plt
import numpy as np

plt.figure(figsize=(4, 3))
plt.plot(np.arange(10), np.random.rand(10) * 0, '-', label='spam')
plt.plot(np.arange(10), np.random.rand(10) * 1, ':', label='ham')
plt.plot(np.arange(10), np.random.rand(10) * 2, 'o', label='eggs')
plt.legend(facecolor='k', labelcolor='w')

matplotlib legend text color: all text white for dark backgrounds

答案 4 :(得分:0)

任何想要更改图例标题标题颜色的人;似乎只能通过侧门使用:

leg._legend_title_box._text.set_color('#FFFFFF')

相关问题