0
0
Matplotlibdata~30 mins

Cursor and event handling in Matplotlib - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use button_press_event to detect clicks and print coordinates.