Reputation: 7564
Given a figure with multiple plots, is there a way to determine which of them was clicked with a mouse button?
E.g.
fig = plt.figure()
ax = fig.add_subplot(121)
ax.imshow(imsp0)
ax = fig.add_subplot(122)
ax.imshow(imsp1)
fig.canvas.mpl_connect("button_press_event",onclick_select)
def onclick_select(event):
... do something depending on the clicked subplot
Upvotes: 6
Views: 4027
Reputation: 339122
If you retain a handle to both axes, you may just query the axes in which the click has happened; e.g. if event.inaxes == ax:
import matplotlib.pyplot as plt
import numpy as np
imsp0 = np.random.rand(10,10)
imsp1 = np.random.rand(10,10)
fig = plt.figure()
ax = fig.add_subplot(121)
ax.imshow(imsp0)
ax2 = fig.add_subplot(122)
ax2.imshow(imsp1)
def onclick_select(event):
if event.inaxes == ax:
print ("event in ax")
elif event.inaxes == ax2:
print ("event in ax2")
fig.canvas.mpl_connect("button_press_event",onclick_select)
plt.show()
Upvotes: 7
Reputation: 23490
It is possible at least by applying the following steps:
the onclick event has attributes x
and y
carrying the pixel coordinates from the corner of the figure
these coordinates can be converted into figure coordinates by using fig.transFigure.inverted().transform((x,y))
you can get the bounding box of each subplot by bb=ax.get_position()
iterate through all subplots (axes) of the image
you can test whether the click is within the area of this bounding box by bb.contains(fx,fy)
, where fx
and fy
are the button click coordinates transformed into image position
For more info on the onclick event: http://matplotlib.org/users/event_handling.html For more info on the coordinate transformations: http://matplotlib.org/users/transforms_tutorial.html
Upvotes: 2