Python 手动设置图例中点的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23698850/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:21:19  来源:igfitidea点击:

Manually set color of points in legend

pythonnumpymatplotlibcolorslegend

提问by Gabriel

I'm making a scatter plot which looks like this:

我正在制作一个散点图,如下所示:

enter image description here

在此处输入图片说明

(MWE at bottom of question)

(问题底部的 MWE)

As can be seen in the image above the colors of the points in the legend are set to blue automatically by matplotlib. I need to set this points to some other color not present in the colormap (ie: black) so they won't generate confusion with the colors associated with said colormap.

如上图所示,图例中点的颜色由 自动设置为蓝色matplotlib。我需要将此点设置为颜色图中不存在的其他颜色(即:黑色),这样它们就不会与与所述颜色图关联的颜色产生混淆。

I looked around but the matplotlib.legendmodule does not seem to accept a colorkeyword. Is there any way to do this?

我环顾四周,但matplotlib.legend模块似乎不接受color关键字。有没有办法做到这一点?



Here's the MWE:

这是 MWE:

import matplotlib.pyplot as plt
import numpy as np

def rand_data():
    return np.random.uniform(low=0., high=1., size=(100,))

# Generate data.
x, y, x2, x3 = [rand_data() for i in range(4)]
# This data defines the markes and labels used.
x1 = np.random.random_integers(7, 9, size=(100,))

# Order all lists so smaller points are on top.
order = np.argsort(-np.array(x2))
# Order x and y.
x_o, y_o = np.take(x, order), np.take(y, order)
# Order list related to markers and labels.
z1 = np.take(x1, order)
# Order list related to sizes.
z2 = np.take(x2, order)
# Order list related to colors.
z3 = np.take(x3, order)

plt.figure()
cm = plt.cm.get_cmap('RdYlBu')

# Scatter plot where each value in z1 has a different marker and label
# assigned.
mrk = {7: ('o', '7'), 8: ('s', '8'), 9: ('D', '9')}
for key, value in mrk.items():

    s1 = (z1 == key)
    plt.scatter(x_o[s1], y_o[s1], marker=value[0], label=value[1],
        s=z2[s1] * 100., c=z3[s1], cmap=cm, lw=0.2)

# Plot colorbar
plt.colorbar()

# Plot legend.
plt.legend(loc="lower left", markerscale=0.7, scatterpoints=1, fontsize=10)

plt.show()

采纳答案by Saullo G. P. Castro

You can obtain the legend handles and change their colors doing:

您可以通过以下方式获取图例句柄并更改其颜色:

ax = plt.gca()
leg = ax.get_legend()
leg.legendHandles[0].set_color('red')
leg.legendHandles[1].set_color('yellow')

回答by apteryx

You can retrieve the label of each legend handle with lh.get_label()if you want to map colors to specific labels.

lh.get_label()如果要将颜色映射到特定标签,可以使用 检索每个图例句柄的标签。

For my purposes it worked best to create a dict from legendHandles and change the colors like so:

出于我的目的,最好从 legendHandles 创建一个 dict 并像这样更改颜色:

ax = plt.gca()
leg = ax.get_legend()
hl_dict = {handle.get_label(): handle for handle in leg.legendHandles}
hl_dict['9'].set_color('red')
hl_dict['8'].set_color('yellow')