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