我希望您能在matplotlib生成的图中,跟随光标一起显示一些文字。我知道如何获取鼠标移动事件,但如何动态地改变文字元素的位置呢?下面的代码展示了如何根据鼠标位置来定位一条线:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
line = ax.plot([0, 1], [0,1])[0]
def on_mouse_move(event):
if None not in (event.xdata, event.ydata):
# draws a line from the center (0, 0) to the current cursor position
line.set_data([0, event.xdata], [0, event.ydata])
fig.canvas.draw()
fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
plt.show()
我该如何使用文本实现类似的效果?我尝试过使用 text.set_data
,但没有成功。