简体   繁体   中英

Determine button clicked subplot in matplotlib

Given a figure with multiple plots, is there a way to determine which of them was clicked with a mouse button?

Eg

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

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

If you retain a handle to both axes, you may just query the axes in which the click has happened; eg 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM