简体   繁体   English

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

[英]How to add a second legend for subgroups in matplotlib scatterplot

I am making a plot using matplotlib which uses a colormap to show different colors for each subgroup within the plot. 我正在使用matplotlib创建一个绘图,它使用一个colormap来显示绘图中每个子组的不同颜色。 However for plotting purposes the subgroups are all one set of x/y pairs. 但是为了绘图目的,子组都是一组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')

It gives the image shown below. 它给出了如下所示的图像。 It is giving me the colors as I mapped them so that part is working fine, but I have not been able to figure out how to add a second legend to the plot to show what the meaning of each color is. 它给我的颜色,因为我绘制它们以便部分工作正常,但我无法弄清楚如何在绘图中添加第二个图例来显示每种颜色的含义。 Apprecaite any guidance on this. 对此提出任何指导意见。

Thanks, Charlie 谢谢,查理

在此输入图像描述

Below is an example of how to do this. 以下是如何执行此操作的示例。 Basically, you end up making two calls to legend . 基本上,你最终会对legend进行两次调用。 On the first call, you save the legend that is created to a variable. 在第一次调用时,将创建的图例保存到变量中。 The second call removes the first legend you created, so afterwards you can manually add it back with the Axes.add_artist function. 第二个调用将删除您创建的第一个图例,因此您可以使用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)

两个标签

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

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