使用 mplcursors 在同一张图上标记多个数据集

Labels for multiple data sets on the same graph using mplcursors

我有两组数据,我正在使用 matplotlib 在同一个图上绘制它们。我正在使用 mplcursors 使用标签数组来注释每个点。不幸的是,mplcursors 对两个数据集都使用了前五个标签。我的问题是如何让第二个数据集拥有自己的自定义标签?

我意识到对于这个简单的例子我可以合并数据,但我不能为我正在进行的项目做。

import matplotlib.pyplot as plt
import mplcursors
import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([1, 2, 3, 4, 5])
y2 = np.array([2, 3, 4, 5, 6])

fig, ax = plt.subplots()
ax.plot(x, y, "ro")
ax.plot(x, y2, 'bx')

labels = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

mplcursors.cursor(ax, hover=True).connect(
    "add", lambda sel: sel.annotation.set_text(labels[sel.target.index]))
plt.show()

多亏了欧内斯特,我才能够让一个粗略的例子运行起来。我将每个图的标签分别设置为 "one" 和 "two"。然后,将鼠标悬停在某个点上时,使用以下方法将艺术家姓名与标签进行比较:

sel.artist.get_label()

import matplotlib.pyplot as plt
import mplcursors
import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([1, 2, 3, 4, 5])
y2 = np.array([2, 3, 4, 5, 6])

fig, ax = plt.subplots()
ax.plot(x, y, "ro", label="one")
ax.plot(x, y2, 'bx', label="two")

labels = ["a", "b", "c", "d", "e"]
labels2 = ["f", "g", "h", "i", "j"]

c1 = mplcursors.cursor(ax, hover=True)
@c1.connect("add")
def add(sel):
    if sel.artist.get_label() == "one":
        sel.annotation.set_text(labels[sel.target.index])
    elif sel.artist.get_label() == "two":
        sel.annotation.set_text(labels2[sel.target.index])

plt.show()

我对使用字典的评论如下所示:

import matplotlib.pyplot as plt
import mplcursors
import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([1, 2, 3, 4, 5])
y2 = np.array([2, 3, 4, 5, 6])

fig, ax = plt.subplots()
line1, = ax.plot(x, y, "ro")
line2, = ax.plot(x, y2, 'bx')

labels1 = ["a", "b", "c", "d", "e"]
labels2 = ["f", "g", "h", "i", "j"]

d = dict(zip([line1, line2], [labels1, labels2]))

mplcursors.cursor(ax, hover=True).connect(
    "add", lambda sel: sel.annotation.set_text(d[sel.artist][sel.target.index]))

plt.show()