Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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
like image 705
memecs Avatar asked Jul 30 '14 22:07

memecs


1 Answers

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()
like image 158
ImportanceOfBeingErnest Avatar answered Sep 30 '22 17:09

ImportanceOfBeingErnest