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

4
我正在使用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')

它显示了下面的图像。它按我映射的颜色给出了颜色,所以那部分运行良好,但我无法弄清楚如何添加第二个图例来显示每种颜色的含义。感谢任何关于此的指导。
谢谢, Charlie
1个回答

8
以下是如何实现的示例。基本上,您需要调用两次“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)

Two labels


这非常有帮助 - 谢谢!我有一个后续问题:是否可能将第二个图例(使用“add_artist”制作的那个)放置在图表内部数据之外的某个位置?例如,在您展示的图表中,如果我可以将第二个图例放置在其最左侧边缘仅略微位于x = 2.5处的垂直线稍左侧,那就太完美了。如果有一种方法可以将其移动到那里,我在页面上有空间。 - Charlie_M
我发现我的后续问题在matplotlib文档中已经非常清楚地得到回答了。很抱歉我没先去检查一下那里。关于我的后续问题的答案可以在这里找到:http://matplotlib.org/users/legend_guide.html - Charlie_M

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接