【问题标题】:matplotlib: dynamically change text positionmatplotlib:动态更改文本位置
【发布时间】:2017-05-11 13:26:54
【问题描述】:

我想在光标旁边显示一些文本,因为它在 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,但没用。

【问题讨论】:

标签: python matplotlib


【解决方案1】:

经过反复试验,我发现解决方案就像 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 2015-03-07
    • 2020-11-28
    • 1970-01-01
    • 2012-04-14
    • 2013-04-18
    • 2020-01-10
    相关资源
    最近更新 更多