How to get axes from a user click?

Hi all,

I have defined some shortcuts I often use using pylab.ginput(). I normally do:

fig = pylab.figure()
fig.canvas.mpl_connect(‘key_press_event’, on_key)
with my “on_key” function being (simplified):

def on_key(event):
if (event.key == ‘q’):
sys.exit(0)
elif (event.key == ‘w’):
pylab.close(pylab.gcf())
elif (event.key == ‘d’):
print “Please click two points to get the distance and slope.”
points = pylab.ginput(n=2, show_clicks=True)
[…]
pylab.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], ‘+r’, lw=1.0)
pylab.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], ‘–r’, lw=1.0)
pylab.draw()

I’m plotting two markers where the user clicked and a line between them.

This works fine, except when there is multiple subplots. I can correctly select points and get their position, but the plot commands will put the markers+line in the last subplot. I tried using “pylab.gca().plot()” but gca() always returns the last axes.

My question is, how can I plot on the axes the user clicked on?

Thank you!

N

While this isn’t in the same approach you were going, you could continue to use mpl_connect instead of ginput. If you create connections (and properly disconnect as well) ‘button_press_event’ and ‘button_release_event’, you can then utilize the event.inaxes property of the event object. This has an added advantage of making sure that the mouse click events are inside the axes.

Another approach might be to find out the bbox’s of all the subplot axes and see if a coordinate falls inside any of those.

Ben Root

···

On Tue, Nov 16, 2010 at 12:01 PM, Nicolas Bigaouette <nbigaouette@…287…> wrote:

Hi all,

I have defined some shortcuts I often use using pylab.ginput(). I normally do:

fig = pylab.figure()
fig.canvas.mpl_connect(‘key_press_event’, on_key)
with my “on_key” function being (simplified):

def on_key(event):
if (event.key == ‘q’):
sys.exit(0)
elif (event.key == ‘w’):
pylab.close(pylab.gcf())
elif (event.key == ‘d’):
print “Please click two points to get the distance and slope.”
points = pylab.ginput(n=2, show_clicks=True)
[…]
pylab.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], ‘+r’, lw=1.0)
pylab.plot([points[0][0], points[1][0]], [points[0][1], points[1][1]], ‘–r’, lw=1.0)
pylab.draw()

I’m plotting two markers where the user clicked and a line between them.

This works fine, except when there is multiple subplots. I can correctly select points and get their position, but the plot commands will put the markers+line in the last subplot. I tried using “pylab.gca().plot()” but gca() always returns the last axes.

My question is, how can I plot on the axes the user clicked on?

Thank you!