Cursor and event handling lets you interact with plots. You can respond when someone moves the mouse or clicks on the graph.
Cursor and event handling in Matplotlib
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Matplotlib
fig, ax = plt.subplots() # Define an event handler function def on_move(event): if event.inaxes: print(f"Mouse at x={event.xdata:.2f}, y={event.ydata:.2f}") # Connect the event to the handler cid = fig.canvas.mpl_connect('motion_notify_event', on_move) plt.show()
Use mpl_connect to link events like mouse move or click to your function.
The event object gives info like mouse position inside the plot.
Examples
Matplotlib
fig, ax = plt.subplots() # Print mouse position when moved inside plot def on_move(event): if event.inaxes: print(f"Mouse at x={event.xdata:.1f}, y={event.ydata:.1f}") fig.canvas.mpl_connect('motion_notify_event', on_move) plt.show()
Matplotlib
fig, ax = plt.subplots() # Print message when mouse clicked def on_click(event): if event.inaxes: print(f"Clicked at x={event.xdata:.2f}, y={event.ydata:.2f}") fig.canvas.mpl_connect('button_press_event', on_click) plt.show()
Matplotlib
fig, ax = plt.subplots() # Show a crosshair cursor following the mouse cursor = Cursor(ax, useblit=True, color='red', linewidth=1) plt.show()
Sample Program
This program plots points and shows a green crosshair cursor. When you click inside the plot, it prints the clicked coordinates.
Matplotlib
import matplotlib.pyplot as plt from matplotlib.widgets import Cursor fig, ax = plt.subplots() ax.plot([1, 2, 3, 4], [10, 20, 25, 30], marker='o') # Create a cursor that follows the mouse cursor = Cursor(ax, useblit=True, color='green', linewidth=1) # Define event handler for mouse clicks def on_click(event): if event.inaxes == ax: print(f"Clicked at x={event.xdata:.2f}, y={event.ydata:.2f}") # Connect the click event to the handler fig.canvas.mpl_connect('button_press_event', on_click) plt.title('Click on points to see coordinates') plt.show()
Important Notes
Event handlers must check if the event happened inside the plot area using event.inaxes.
The Cursor widget helps show a crosshair cursor easily.
Use mpl_connect to link many event types like mouse move, click, key press.
Summary
Cursor and event handling make plots interactive and responsive to mouse actions.
Use mpl_connect to connect mouse events to your functions.
The Cursor widget shows a crosshair that follows the mouse.
Practice
1. What is the main purpose of using
mpl_connect in matplotlib?easy
Solution
Step 1: Understand what
mpl_connectdoesmpl_connectlinks events such as mouse clicks or key presses to functions you define.Step 2: Identify the correct purpose
It does not save images, create figures, or change colors directly. It connects events to functions.Final Answer:
To connect an event like mouse click to a custom function -> Option BQuick Check:
Event connection = C [OK]
Hint: Remember: mpl_connect links events to your functions [OK]
Common Mistakes:
- Thinking mpl_connect saves or modifies plots directly
- Confusing mpl_connect with figure creation
- Assuming mpl_connect changes plot styles
2. Which of the following is the correct syntax to connect a mouse click event to a function named
on_click using matplotlib?easy
Solution
Step 1: Recall the correct event name for mouse clicks
The correct event name in matplotlib for mouse button press is 'button_press_event'.Step 2: Check the syntax of mpl_connect
The method is called on the figure's canvas asfig.canvas.mpl_connect(event_name, function).Final Answer:
fig.canvas.mpl_connect('button_press_event', on_click) -> Option CQuick Check:
Correct event name and syntax = A [OK]
Hint: Use 'button_press_event' for mouse clicks with mpl_connect [OK]
Common Mistakes:
- Using wrong event names like 'click' or 'mouse_click'
- Using non-existent methods like connect_event
- Mixing up method names and event strings
3. Consider the code below:
What will happen when you move the mouse over the plot area?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
def on_move(event):
print(f"Mouse at: {event.xdata}, {event.ydata}")
cid = fig.canvas.mpl_connect('motion_notify_event', on_move)
plt.show()What will happen when you move the mouse over the plot area?
medium
Solution
Step 1: Understand the event type 'motion_notify_event'
This event triggers whenever the mouse moves over the figure canvas.Step 2: Analyze the function
The function prints the mouse coordinates inside the plot area usingon_moveevent.xdataandevent.ydata.Final Answer:
The coordinates of the mouse pointer inside the plot will be printed continuously -> Option AQuick Check:
Mouse move event prints coords = B [OK]
Hint: motion_notify_event tracks mouse movement over plot [OK]
Common Mistakes:
- Assuming no output because event is not connected
- Thinking event.xdata is always None or undefined
- Expecting plot to close on mouse move
4. The following code is intended to print the mouse button pressed, but it raises an error:
What is the error and how to fix it?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
def on_click(event):
print(f"Button pressed: {event.button}")
fig.canvas.mpl_connect('button_press_event', on_click())
plt.show()What is the error and how to fix it?
medium
Solution
Step 1: Identify the error in function connection
Usingon_click()calls the function immediately instead of passing it as a reference.Step 2: Correct the function reference in mpl_connect
Remove parentheses to pass the function itself:fig.canvas.mpl_connect('button_press_event', on_click).Final Answer:
The function is called immediately; remove parentheses in mpl_connect -> Option AQuick Check:
Pass function, not call it = D [OK]
Hint: Pass function name without () to mpl_connect [OK]
Common Mistakes:
- Calling the function instead of passing it
- Using wrong event names
- Trying to access wrong event attributes
5. You want to create an interactive plot where clicking inside the plot area prints the nearest data point's coordinates from a scatter plot. Which approach correctly combines cursor event handling and data lookup?
hard
Solution
Step 1: Identify the correct event for mouse clicks
Use 'button_press_event' to detect mouse clicks inside the plot.Step 2: Implement logic to find nearest data point
Calculate distances from click position to all scatter points, then print the closest one.Step 3: Verify other options
'motion_notify_event' prints continuously, 'key_press_event' is unrelated, and plt.scatter has no auto-print feature.Final Answer:
Connect 'button_press_event' to a function that calculates distances from click to all points and prints nearest -> Option DQuick Check:
Click event + nearest point logic = A [OK]
Hint: Use click event plus distance check to find nearest point [OK]
Common Mistakes:
- Using motion event instead of click for selection
- Expecting built-in auto-print in scatter
- Confusing key press with mouse click events
