Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Matplotlib – How to show the coordinates of a point upon mouse click?
In Matplotlib, you can capture mouse click coordinates on a plot by connecting an event handler to the figure's canvas. This is useful for interactive data exploration and annotation.
Setting Up Mouse Click Detection
The key is to use mpl_connect() to bind a function to the 'button_press_event' ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
def mouse_event(event):
if event.xdata is not None and event.ydata is not None:
print('x: {:.3f} and y: {:.3f}'.format(event.xdata, event.ydata))
fig = plt.figure()
cid = fig.canvas.mpl_connect('button_press_event', mouse_event)
x = np.linspace(-10, 10, 100)
y = np.sin(x)
plt.plot(x, y, 'b-', linewidth=2)
plt.title('Click on the plot to see coordinates')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.grid(True, alpha=0.3)
plt.show()
When you click on different points of the plot, the coordinates will be printed to the console ?
x: -3.099 and y: -0.014 x: -0.287 and y: -0.207 x: -3.028 and y: -0.184 x: -5.770 and y: 0.424 x: -3.918 and y: 0.684
Enhanced Version with Visual Markers
You can also add visual markers at clicked points and display coordinates on the plot ?
import numpy as np
import matplotlib.pyplot as plt
class ClickPlotter:
def __init__(self):
self.fig, self.ax = plt.subplots(figsize=(8, 5))
self.clicked_points = []
def mouse_event(self, event):
if event.xdata is not None and event.ydata is not None:
x, y = event.xdata, event.ydata
print('Clicked at x: {:.3f}, y: {:.3f}'.format(x, y))
# Add marker at clicked point
self.ax.plot(x, y, 'ro', markersize=8)
# Add text annotation
self.ax.annotate('({:.2f}, {:.2f})'.format(x, y),
(x, y), xytext=(5, 5),
textcoords='offset points',
fontsize=9, color='red')
self.fig.canvas.draw()
self.clicked_points.append((x, y))
# Create plotter instance
plotter = ClickPlotter()
# Connect the event
cid = plotter.fig.canvas.mpl_connect('button_press_event', plotter.mouse_event)
# Create sample data
x = np.linspace(-5, 5, 100)
y = x**2 - 2*x + 1
plotter.ax.plot(x, y, 'b-', linewidth=2, label='y = x² - 2x + 1')
plotter.ax.set_title('Click to Mark Points and Show Coordinates')
plotter.ax.set_xlabel('X values')
plotter.ax.set_ylabel('Y values')
plotter.ax.grid(True, alpha=0.3)
plotter.ax.legend()
plt.show()
How It Works
The event handler receives an event object containing:
- event.xdata: X-coordinate in data units
- event.ydata: Y-coordinate in data units
- event.button: Mouse button pressed (1=left, 2=middle, 3=right)
- event.inaxes: The axes where the click occurred
Key Points
- Always check if
event.xdataandevent.ydataare not None - Use
fig.canvas.draw()to refresh the plot after adding markers - Store the connection ID if you need to disconnect the event later
- Multiple event handlers can be connected to the same figure
Conclusion
Mouse click coordinate detection in Matplotlib enables interactive data exploration. Use mpl_connect() with 'button_press_event' to capture clicks and access coordinates through event.xdata and event.ydata.
