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]