How can I derive axis index from mouse click event?

This Python 3.11 script displays two graphs (axes):

import numpy as np, matplotlib.pyplot as plt

def onclick(event):
  print(event.inaxes)

fig, axs = plt.subplots(ncols=2, nrows=1, figsize=(3.5, 2.5), layout="constrained")
axs[0].plot(np.random.rand(10))
axs[1].plot(np.random.rand(10))
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

Clicking first on the left graph, then on the right one, produces:

Axes(0.102541,0.111557;0.385554x0.871775)
Axes(0.602541,0.111557;0.385554x0.871775)

I see the first of Axes properties changing depending on the graph I clicked on: 0.102541 for the left one and 0.602541 for the right one. What is this property’s name? Is there a simple way to derive an index of axs, which was clicked on from the event?

This is a repost of python - How can I derive axis index from mouse click event? - Stack Overflow, which didn’t get any traction so far. Hope it’s okay to repost here.

I think you want this:

def onclick(event):
    if ax := event.inaxes:
        print(ax.figure.axes.index(ax), ax._position.bounds, sep='\n')
1 Like

Perfect! If you care to earn some stackoverflow points, post it there and I will accept it as the best answer.