python - 使用 mplcursors 在同一图表上为多个数据集添加标签

标签 python matplotlib annotations cursor 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()

最佳答案

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

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()

关于python - 使用 mplcursors 在同一图表上为多个数据集添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349082/

相关文章:

java - 获取调用方法的注解值

python - 在 Linux Angstrom 上使用 Python 显示图像

python - 关于 np.nonzero(arr)[0] 中 Trailing[0] 的作用的问题

python - 在 Matplotlib 中制作负载持续时间曲线

python - Matplotlib、Pandas、饼图标签错误

java - 修改自定义注解的参数值

python - 与 JupyterHub 中的 Bokeh 服务器交互

python - 字符串格式占位符可最大程度地兼容 python 2.6、2.7 和 3.x

python - 不能设置双轴位置

iphone - 如何检测 map View 上显示的注释标注?