Navid777
Navid777

Reputation: 3681

Get the indices of the clicked point relative to a subplot

I have a plot in matplotlib that has 2 subplots:

plt.subplot(211), plt.imshow(img1)
plt.subplot(212, plt.imshow(img2)

An I've set a click handler to handle mouse click events:

fig = plt.figure()
def onclick(event):
    print plot.x, plot.y

cid = fig.canvas.mpl_connect('button_press_event', onclick)

The problem is that event.x returns the indices of the clicked point relative to the whole plot, what I want is the indices relative to the second subplot. How can I get the indices relative to a subplot?

Upvotes: 1

Views: 1127

Answers (1)

bnaecker
bnaecker

Reputation: 6430

You need to do two things for this to work. First, your callback function must check if the click is inside the axes of interest. Second, the mouse event position is given in display coordinates, which must be transformed into the axes coordinates. The first requirement can be done by using Axes.in_axes(). The second can be achieved with the Axes.transAxes transform. (This transform converts from axes to display coordinates, so it must be inverted to go from display to axes coordinates.)

A small example might be:

import matplotlib.pyplot as plt
import functools

def handler(fig, ax, event):
    # Verify click is within the axes of interest
    if ax.in_axes(event):
        # Transform the event from display to axes coordinates
        ax_pos = ax.transAxes.inverted().transform((event.x, event.y))
        print(ax_pos)

if __name__ == '__main__':
    fig, axes = plt.subplots(2, 1)
    # Handle click events only in the bottom of the two axes
    handler_wrapper = functools.partial(handler, fig, axes[1])
    fig.canvas.mpl_connect('button_press_event', handler_wrapper)
    plt.show()

Upvotes: 1

Related Questions