matplotlib:动态更改文本位置

3
我希望您能在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,但没有成功。


请见https://dev59.com/jPz2s4cB2Jgan1znspQB。 - ImportanceOfBeingErnest
1个回答

7

经过一些尝试,我发现解决方案就是如下简单的代码text.set_position((x, y))

以下是一个示例:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
text = ax.text(1, 1, 'Text')

def on_mouse_move(event):
    if None not in (event.xdata, event.ydata):
        text.set_position((event.xdata, event.ydata))
        fig.canvas.draw()

fig.canvas.mpl_connect('motion_notify_event', on_mouse_move)
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接