1

我有两组数据,我正在使用 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()
4

2 回答 2

3

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

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()
于 2019-10-12T01:12:13.327 回答
0

多亏了欧内斯特,我才能得到一个粗略的例子。我将每个图的标签分别设置为“一”和“二”。然后,当将鼠标悬停在某个点上时,使用以下命令将艺术家姓名与标签进行比较:

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()
于 2019-10-12T01:03:43.413 回答