2

This script:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def fAccept(_):
  print(f'accepted')

def onclick(event):
  print(f'click  {event.xdata, event.ydata}')

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
fig.canvas.mpl_connect('button_press_event', onclick)
axAccept = fig.add_axes([0.7, 0.05, 0.1, 0.075])
bAccept = Button(axAccept, 'Accept')
bAccept.on_clicked(fAccept)
plt.show()

displays

enter image description here

Clicking on bAccept button calls onclick callback. Is there a way to limit onclick callback to the top axis? Alternatively, is there a way to distinguish event coordinates (0.5, 0.5) at the center of bAccept button (green circle) from (0.5, 0.5) coordinates at the center of the upper axis (red circle)?

1 Answer 1

4

In the onclick callback, you can check if the event occurred in the main axes using:

if event.inaxes == ax:

Here's your modified code:

import matplotlib.pyplot as plt
from matplotlib.widgets import Button

def fAccept(_):
    print('accepted')

def onclick(event):
    if event.inaxes == ax:  # Only respond if click is inside the plot axis
        print(f'click  {event.xdata, event.ydata}')
    else:
        print('Click outside main axis, ignored.')

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)

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

axAccept = fig.add_axes([0.7, 0.05, 0.1, 0.075])
bAccept = Button(axAccept, 'Accept')
bAccept.on_clicked(fAccept)

plt.show()
  • event.inaxes tells you which axes the click occurred in.

  • If it's None, the click was outside all axes.

  • If it's axAccept, the click was on the button area.

  • If it's ax, the click was on the plot — so it’s safe to respond.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.