Python 手动设置图例中点的颜色
我正在做一个散点图,看起来像这样: (问题底部的MWE) 如上图所示,Python 手动设置图例中点的颜色,python,numpy,matplotlib,colors,legend,Python,Numpy,Matplotlib,Colors,Legend,我正在做一个散点图,看起来像这样: (问题底部的MWE) 如上图所示,matplotlib会自动将图例中点的颜色设置为蓝色。我需要将此点设置为颜色映射中不存在的其他颜色(即:黑色),这样它们就不会与所述颜色映射相关的颜色产生混淆 我环顾四周,但模块似乎不接受颜色关键字。有没有办法做到这一点 以下是MWE: import matplotlib.pyplot as plt import numpy as np def rand_data(): return np.random.unif
matplotlib
会自动将图例中点的颜色设置为蓝色。我需要将此点设置为颜色映射中不存在的其他颜色(即:黑色),这样它们就不会与所述颜色映射相关的颜色产生混淆
我环顾四周,但模块似乎不接受颜色
关键字。有没有办法做到这一点
以下是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()
您可以通过以下操作获取图例控制柄并更改其颜色:
ax = plt.gca()
leg = ax.get_legend()
leg.legendHandles[0].set_color('red')
leg.legendHandles[1].set_color('yellow')
如果要将颜色映射到特定标签,可以使用
lh.get_label()
检索每个图例句柄的标签
出于我的目的,最好从legendholds
创建一个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')
除了其他答案之外,我在过去使用
set\u color
更改图例标记的颜色时遇到了麻烦。另一种方法是自己创建图例:
import matplotlib.lines as mlines
eight = mlines.Line2D([], [], color='blue', marker='s', ls='', label='8')
nine = mlines.Line2D([], [], color='blue', marker='D', ls='', label='9')
# etc etc
plt.legend(handles=[eight, nine])
从头开始构建图例有时可以省去处理已构建图例的晦涩内部的麻烦。Matplotlib文档中的详细信息。当我发现带有
legendHandles[I].set_color
的解决方案不适用于errorbar
时,我设法采取了以下解决方法:
ax\u legend=fig.add\u子图(g[3,0])
轴(“关闭”)
句柄\u标记=[]
标记_标签=[]
对于marker\u name,markers\u style.items()中的marker\u样式:
pts=plt.scatter([0],[0],marker=marker\u style,c='black',label=marker\u name)
处理\u标记。附加(pts)
标记\标签。附加(标记\名称)
pts.remove()
ax\u legend.legend(句柄标记,标记标记,loc='center',ncol=len(标记,标记),handlelength=1.5,handletextpad=0.1)
我也看到了