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