gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:16 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com