Matplotlib:在图例中使用彩色文本而不是线条

19

在某些LCD显示器上,很难区分图例中水平线的颜色。(请参见附图)。因此,是否有可能只对文本本身进行编码而不是在图例中画线条?换句话说,将“y=0x”以蓝色表示,“y=1x”以绿色表示,等等...

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend()

plt.show()

在此输入图像描述

提示:如果只是要在图例中加粗线条而不是整个图表,也可以这么做。


从matplotlib版本3.3.0开始,您现在可以直接使用关键字参数labelcolor,如此答案所述:https://dev59.com/OWMk5IYBdhLWcg3w2ReT#63273370。 - Zaus
4个回答

24

我也在想同样的问题。这是我想出来改变图例字体颜色的方法。我对这种方法不是完全满意,因为它似乎有点笨拙,但它似乎能够完成任务[编辑:见下面的更好的方法]:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

colors = []
for i in xrange(5):
    line, = ax.plot(x, i * x, label='$y = %ix$' % i)
    colors.append(plt.getp(line,'color'))

leg = ax.legend()

for color,text in zip(colors,leg.get_texts()):
    text.set_color(color)

plt.show()

丰富多彩的结果

2016 年编辑:

实际上,有更好的方法。您可以简单地迭代图例中的行,这样就不需要在绘制线条时跟踪颜色了。就会少得多笨拙。现在,更改线条颜色基本上只需要一行代码(好吧,实际上是两行)。下面是完整的示例:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i*x, label='$y = %ix$'%i)

leg = ax.legend()

# change the font colors to match the line colors:
for line,text in zip(leg.get_lines(), leg.get_texts()):
    text.set_color(line.get_color())

plt.show()

2017年编辑: 最后,如果你真的想要彩色文字代替线条(正如标题所示),那么你可以使用

来取消图例中的线条。

 leg = ax.legend(handlelength=0)

10

只需设置图例句柄的linewidth

In [55]: fig, ax = plt.subplots()

In [56]: x = np.arange(10)

In [57]: for i in xrange(5):                    
   ....:     ax.plot(x, i * x, label='$y = %ix$' % i)
   ....:     

In [58]: leg = ax.legend(loc='best')

In [59]: for l in leg.legendHandles:            
   ....:     l.set_linewidth(10)
   ....:     

legend_linewidth.png


1
这并没有回答问题。应该接受 https://dev59.com/fmYr5IYBdhLWcg3wQIC-#18476999。 - Max Ghenis

8

在所有绘图完成后,通过图例文本的getter/setter和轴线getter/setter可以干净地执行此操作。在绘图之前,使用for循环将图例文本颜色设置为与线条颜色相同。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

leg = ax.legend()

def color_legend_texts(leg):
    """Color legend texts based on color of corresponding lines"""
    for line, txt in zip(leg.get_lines(), leg.get_texts()):
        txt.set_color(line.get_color())  

color_legend_texts(leg)    

plt.show()

这个答案需要注意的主要区别是,可以将图形格式与绘图操作完全分离。

2
为了提供更通用的解决方案,使图例文本与图例标记的颜色相匹配: 这不仅适用于线条,而且适用于任何图例中的艺术家。它将如下所示:
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)


ax.plot(x, 3 * x, label='$y = %ix$' % 3)
ax.scatter(x, 4 * x, color="red", label='$y = %ix$' % 4)
ax.hist(x, label="hist")
ax.errorbar(x,2*x,yerr=0.3*x, label='$y = %ix$' % 2)

leg = ax.legend()

for artist, text in zip(leg.legendHandles, leg.get_texts()):
    try:
        col = artist.get_color()
    except:
        col = artist.get_facecolor()
    if isinstance(col, np.ndarray):
        col = col[0]
    text.set_color(col)

plt.show()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接