0

我正在使用mplcursors模块来显示标签值。我还想显示给定列表中我将悬停的特定点的索引号。我的示例代码片段:

import matplotlib.pyplot as plt
import mplcursors
lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
plt.ylabel('some numbers')
mplcursors.cursor(hover=True)
plt.show()

有什么方法可以mplcursors用来注释所需的信息(因为它很容易)?谢谢 :)

4

1 回答 1

1

mplcursors允许指定每次在注释显示之前调用的函数。该函数获取一个参数sel,其中包含一个target字段。在“线”的情况下,除了 xy 值之外,目标还包含一个index. 的整数部分是光标所在段左端的和数组index的索引。小数部分告诉我们在段的左端和右端之间有多远。xyindex

import matplotlib.pyplot as plt
import mplcursors

def show_annotation(sel):
    ind = int(sel.target.index)
    frac = sel.target.index - ind
    x, y = sel.target
    sel.annotation.set_text(f'left index:{ind} frac:{frac:.2f}\nx:{x:.2f} y:{y:.2f}')

lines = plt.plot([1, 2, 3, 4], [2, 4, 6, 10])
plt.ylabel('some numbers')
cursor = mplcursors.cursor(hover=True)
cursor.connect("add", show_annotation)
plt.show()

示例注释

于 2020-07-22T18:54:17.313 回答