如何在matplotlib散点图中为子组添加第二个图例

Cha*_*e_M 3 python scatter matplotlib

我正在使用matplotlib创建一个绘图,它使用一个colormap来显示绘图中每个子组的不同颜色.但是为了绘图目的,子组都是一组x/y对.

plt.scatter(rs1.x,rs1.y, marker = 'D', color=cmap ,label='data')
plt.plot(rs1.x,rs1.hub_results.predict(), marker = 'x', color = 'g',label = 'Huber Fit')
plt.plot(rs1.ol_x,rs1.ol_y, marker = 'x', color='r', ms=10, mew=2, linestyle = ' ', label='Outliers')
Run Code Online (Sandbox Code Playgroud)

它给出了如下所示的图像.它给我的颜色,因为我绘制它们以便部分工作正常,但我无法弄清楚如何在绘图中添加第二个图例来显示每种颜色的含义.对此提出任何指导意见.

谢谢,查理

在此输入图像描述

tbe*_*lay 5

以下是如何执行此操作的示例.基本上,你最终打两次电话legend.在第一次调用时,将创建的图例保存到变量中.第二个调用将删除您创建的第一个图例,因此您可以使用该Axes.add_artist函数手动将其添加回来.

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)

p1, = plt.plot([1,2,3])
p2, = plt.plot([3,2,1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')

p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')

# This removes l1 from the axes.
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# Add l1 as a separate artist to the axes
plt.gca().add_artist(l1)
Run Code Online (Sandbox Code Playgroud)

两个标签