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

标签 python matplotlib scatter

我正在使用 matplotlib 制作绘图,它使用颜色图为绘图中的每个子组显示不同的颜色。然而,出于绘图目的,子组都是一组 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')

它给出了如下所示的图像。它在我映射它们时为我提供颜色,以便该部分工作正常,但我无法弄清楚如何向绘图添加第二个图例以显示每种颜色的含义。对此有任何指导。

谢谢, 查理

enter image description here

最佳答案

下面是如何执行此操作的示例。基本上,您最终会调用两次 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

关于python - 如何在 matplotlib 散点图中为子组添加第二个图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24416096/

相关文章:

python - Seaborn 带状图,点前面有 fiddle 图条

python - 如何将参数传递给 animation.FuncAnimation()?

python - 如何切换 3D 散点图中的 Axis 方向?

Python 字符串格式化

python - 从 Django 表单集中删除表单

python /Matplotlib : convert Axis ⇔ Data coordinates systems

python - 在 x 的范围内运行 y 值的中值

python - matplotlib:如何将 XYZ 散点图转换为像素图像?

python - super 函数在 maya python 模块中不起作用

使用多处理模块创建的进程之间的python类对象共享