matplotlib:将图例文本颜色与散点图中的符号匹配

Phy*_*nmi 5 python matplotlib legend

我制作了一个有3种不同颜色的散点图,我希望匹配符号的颜色和图例中的文字.

对于线图的情况,存在一个很好的解决方案:

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())
Run Code Online (Sandbox Code Playgroud)

但是,无法访问散点图颜色get_lines().对于3种颜色的情况,我认为我可以使用例如逐个手动设置文本颜色.text.set_color('r').但我很好奇它是否能像线条一样自动完成.谢谢!

Imp*_*est 6

散点图具有面色和边缘颜色.分散的图例处理程序是a PathCollection.

因此,您可以遍历图例句柄并将文本颜色设置为图例句柄的面部颜色

for h, t in zip(leg.legendHandles, leg.get_texts()):
    t.set_color(h.get_facecolor()[0])
Run Code Online (Sandbox Code Playgroud)

完整代码:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
for i in range(3):
    x,y = np.random.rand(2, 20)
    ax.scatter(x, y, label="Label {}".format(i))

leg = ax.legend()

for h, t in zip(leg.legendHandles, leg.get_texts()):
    t.set_color(h.get_facecolor()[0])

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Y. *_*Luo 2

这看起来很复杂,但确实给了你你想要的。欢迎提出建议。我用来ax.get_legend_handles_labels()获取标记并用来tuple(handle.get_facecolor()[0])获取 matplotlib 颜色元组。用一个非常简单的散点图制作了一个例子,如下所示:

编辑:

正如ImportanceOfBeingErnest在他的回答中指出的那样:

  1. leg.legendHandles将返回图例句柄;
  2. 列表(而不是元组)可用于指定 matplotlib 颜色。

代码简化为:

import matplotlib.pyplot as plt
from numpy.random import rand


fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
    x, y = rand(2, 10)
    ax.scatter(x, y, c=color, label=color)

leg = ax.legend()
for handle, text in zip(leg.legendHandles, leg.get_texts()):
    text.set_color(handle.get_facecolor()[0])

plt.show()
Run Code Online (Sandbox Code Playgroud)

我得到的是: 在此输入图像描述