繁体   English   中英

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

[英]matplotlib: match legend text color with symbol in scatter plot

我制作了一个有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())

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

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

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

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

完整代码:

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

在此输入图像描述

这似乎很复杂但确实能满足您的需求。 欢迎提出建议。 我使用ax.get_legend_handles_labels()来获取标记并使用tuple(handle.get_facecolor()[0])来获取matplotlib颜色元组。 用这样一个非常简单的散点图做了一个例子:

编辑:

由于重要性,鲍勃·欧内斯特在他的回答中指出:

  1. leg.legendHandles将返回图例句柄;
  2. List,而不是元组,可用于分配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()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM