3

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.

1

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.