0
0
Matplotlibdata~20 mins

Cursor and event handling in Matplotlib - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Cursor and Event Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this matplotlib cursor event code?

Consider the following code that uses matplotlib to track mouse clicks on a plot. What will be printed when you click inside the plot area?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3], [4, 5, 6])

class ClickTracker:
    def __init__(self, ax):
        self.ax = ax
        self.cid = ax.figure.canvas.mpl_connect('button_press_event', self.onclick)

    def onclick(self, event):
        if event.inaxes == self.ax:
            print(f'Clicked at x={event.xdata:.2f}, y={event.ydata:.2f}')

tracker = ClickTracker(ax)
plt.show()
APrints the coordinates of the click inside the plot area with two decimals.
BPrints the pixel coordinates of the click on the screen.
CRaises an AttributeError because event.xdata does not exist.
DPrints nothing because the event handler is not connected.
Attempts:
2 left
💡 Hint

Check what event.xdata and event.ydata represent in matplotlib mouse events.

data_output
intermediate
2:00remaining
How many times is the event handler called when clicking outside the axes?

Given this matplotlib event handler connected to button_press_event, how many times will the onclick method print output if you click 3 times outside the plot axes?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

class ClickCounter:
    def __init__(self, ax):
        self.ax = ax
        self.count = 0
        self.cid = ax.figure.canvas.mpl_connect('button_press_event', self.onclick)

    def onclick(self, event):
        if event.inaxes == self.ax:
            self.count += 1
            print(f'Click count inside axes: {self.count}')

counter = ClickCounter(ax)
plt.show()
A0 times, because clicks outside axes do not trigger the print.
B3 times, one for each click regardless of location.
CRaises an error because event.inaxes is None outside axes.
D1 time, because only the first click outside axes triggers the event.
Attempts:
2 left
💡 Hint

Look at the condition if event.inaxes == self.ax and what event.inaxes is when clicking outside.

visualization
advanced
2:30remaining
Which option correctly updates a plot title with cursor position on mouse move?

Which code snippet below will update the plot's title to show the current mouse position inside the axes as you move the cursor?

A
def on_move(event):
    if event.inaxes:
        event.inaxes.set_title(f'x={event.xdata}, y={event.ydata}')
        event.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', on_move)
B
def on_move(event):
    if event.inaxes:
        event.inaxes.set_title(f'x={event.xdata:.1f}, y={event.ydata:.1f}')
        event.canvas.draw_idle()

fig.canvas.mpl_connect('motion_notify_event', on_move)
C
def on_move(event):
    if event.inaxes:
        event.inaxes.title.set_text(f'x={event.x}, y={event.y}')
        event.canvas.draw()

fig.canvas.mpl_connect('button_press_event', on_move)
D
def on_move(event):
    if event.inaxes:
        event.inaxes.set_title(f'x={event.xdata:.1f}, y={event.ydata:.1f}')
        event.canvas.flush_events()

fig.canvas.mpl_connect('motion_notify_event', on_move)
Attempts:
2 left
💡 Hint

Check the event type for mouse movement and how to update the title with formatted floats.

🔧 Debug
advanced
2:00remaining
Why does this matplotlib event handler not print anything on click?

Examine the code below. Why does clicking on the plot not produce any printed output?

Matplotlib
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

class Handler:
    def __init__(self, ax):
        self.ax = ax
        self.cid = ax.figure.canvas.mpl_connect('button_press_event', self.on_click)

    def on_click(self, event):
        if event.inaxes == self.ax:
            print('Clicked!')

handler = Handler(ax)
plt.show()
AThe event handler is connected correctly, but the plot window is not shown.
BThe condition compares event.inaxes to ax, but event.inaxes is None when clicking inside.
CThe event handler is connected to the figure canvas, but the method name is misspelled.
DThe code works correctly and prints 'Clicked!' when clicking inside the axes.
Attempts:
2 left
💡 Hint

Check if the event handler is connected and if the condition matches clicks inside the axes.

🚀 Application
expert
3:00remaining
How to implement a draggable vertical line cursor in matplotlib?

You want to add a vertical line cursor to a matplotlib plot that the user can drag horizontally with the mouse. Which approach below correctly implements this behavior?

AUse <code>axvline</code> to draw the line, connect <code>motion_notify_event</code> only, and update the line's x-position without checking mouse button state.
BUse <code>axhline</code> to draw the line, connect only <code>button_press_event</code> to update the line's y-position, and call <code>plt.show()</code> inside the event handler.
CUse <code>axvline</code> to draw the line, connect <code>button_press_event</code>, <code>motion_notify_event</code>, and <code>button_release_event</code> to update the line's x-position while dragging, and call <code>canvas.draw_idle()</code> after updates.
DUse <code>plot</code> to draw a vertical line, connect <code>key_press_event</code> to move the line horizontally with arrow keys, and call <code>canvas.flush_events()</code> after updates.
Attempts:
2 left
💡 Hint

Think about which events are needed to track dragging and how to update the line position smoothly.