Felix
Felix

Reputation: 6359

matplotlib: dynamically change text position

I want to display some text next to the cursor as it moves through a plot generated by matplotlib.

I know how to get the mouse motion events, but how do I change the position of the text element dynamically?

The following code shows how to position a line depending on the position of the cursor:

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()

How can I do something similar with text? I've tried text.set_data but that didn't work.

Upvotes: 3

Views: 9614

Answers (1)

Felix
Felix

Reputation: 6359

After some trial and error, I found the solution being as simple as text.set_position((x, y)).

See the following example below:

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()

Upvotes: 8

Related Questions