Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Interactive Plot with Cursor and Event Handling
📖 Scenario: You are working with a simple line plot showing sales data over a week. You want to make the plot interactive so that when you move your mouse over the plot, a cursor line follows your mouse, and when you click on the plot, the exact data point coordinates are printed.
🎯 Goal: Create a matplotlib plot with a cursor that moves with the mouse and prints the coordinates of the clicked point.
📋 What You'll Learn
Create a line plot with given sales data.
Add a vertical cursor line that follows the mouse movement.
Print the x and y coordinates when the plot is clicked.
💡 Why This Matters
🌍 Real World
Interactive plots help analysts explore data visually and get exact values by moving the mouse or clicking points.
💼 Career
Data scientists and analysts often create interactive visualizations to communicate insights clearly and allow users to explore data.
Progress0 / 4 steps
1
Create the sales data and plot
Create a list called days with values [1, 2, 3, 4, 5, 6, 7] representing days of the week. Create a list called sales with values [10, 15, 7, 12, 20, 18, 25]. Then, import matplotlib.pyplot as plt and plot sales against days using plt.plot(days, sales). Finally, call plt.show() to display the plot.
Matplotlib
Hint
Remember to import matplotlib.pyplot as plt before plotting.
2
Add a vertical cursor line
After plotting, create a variable called cursor_line that stores a vertical line on the plot using plt.axvline at position x=0 with color 'gray' and linestyle '--'. This line will act as the cursor.
Matplotlib
Hint
Use plt.axvline to add a vertical line at x=0.
3
Add mouse move event to update cursor
Define a function called on_mouse_move that takes an event parameter. Inside the function, check if event.xdata is not None. If so, update the cursor_line position by setting its xdata to [event.xdata, event.xdata] and then call plt.gcf().canvas.draw_idle() to refresh the plot. Connect this function to the figure's motion_notify_event using plt.gcf().canvas.mpl_connect.
Matplotlib
Hint
Use set_xdata on the cursor line and redraw the canvas.
4
Add click event to print coordinates
Define a function called on_click that takes an event parameter. Inside the function, check if event.xdata and event.ydata are not None. If so, print the message Clicked at x={event.xdata:.2f}, y={event.ydata:.2f} using an f-string. Connect this function to the figure's button_press_event using plt.gcf().canvas.mpl_connect. Finally, call plt.show() to display the interactive plot.
Matplotlib
Hint
Use button_press_event to detect clicks and print coordinates.
Practice
(1/5)
1. What is the main purpose of using mpl_connect in matplotlib?
easy
A. To create a new figure window
B. To connect an event like mouse click to a custom function
C. To save the current plot as an image file
D. To change the color of the plot lines
Solution
Step 1: Understand what mpl_connect does
mpl_connect links 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 B
Quick 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
A. fig.connect_event('button_press', on_click)
B. fig.mpl_connect('click', on_click)
C. fig.canvas.mpl_connect('button_press_event', on_click)
D. fig.connect('mouse_click', on_click)
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 as fig.canvas.mpl_connect(event_name, function).
Final Answer:
fig.canvas.mpl_connect('button_press_event', on_click) -> Option C
Quick 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'
A. The function is called immediately; remove parentheses in mpl_connect
B. The event name is wrong; use 'mouse_press' instead
C. event.button does not exist; use event.key instead
D. mpl_connect should be called on ax, not fig
Solution
Step 1: Identify the error in function connection
Using on_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 A
Quick 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
A. Use plt.scatter() with a parameter to automatically print nearest point on click
B. Use 'motion_notify_event' to print coordinates continuously without checking points
C. Connect 'key_press_event' to print data points when any key is pressed
D. Connect 'button_press_event' to a function that calculates distances from click to all points and prints nearest
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 D
Quick Check:
Click event + nearest point logic = A [OK]
Hint: Use click event plus distance check to find nearest point [OK]