Getting the location of a mouse click in Matplotlib using Tkinter
Edit: I jumped into answering without reading your example completely. The problems you're having are due to the order that you've defined things in. Basically, you have:
import matplotlib.pyplot as pltdef callback(event): print event.x, event.yfig, ax = plt.subplots()fig.canvas.callbacks.connect('button_press_event', callback)def callback(event): print event.xdata, event.ydata
When you're connecting the callback, the second function hasn't been defined yet, so it's connecting to the earlier function with the same name. Either move the callback connection after the function is defined, or just move the function definition up and delete the (unused) first callback function.
Regardless, have a look at matplotlib's transforms to understand how you'd transform between display/pixel coordinates and plot coordinates. I'll leave my original answer in the hope it helps someone else who comes across this question.
If I'm understanding you correctly, you want the data coordinates where the mouse click occured?
If so, use event.xdata
and event.ydata
.
As a quick example:
import matplotlib.pyplot as pltdef on_click(event): if event.inaxes is not None: print event.xdata, event.ydata else: print 'Clicked ouside axes bounds but inside plot window'fig, ax = plt.subplots()fig.canvas.callbacks.connect('button_press_event', on_click)plt.show()
In general, though, have a look at matplotlib's transforms for transforming between display, figure, axes, and data coordinates.
For example, the eqivalent of event.xdata
and event.ydata
would be:
x, y = event.inaxes.transData.inverted().transform((event.x, event.y))
It's a bit verbose, but ax.transData
is the transformation between display (pixel) coordinates and data coordinates. We want to go the other way, so we invert the transformation with trans.inverted()
. Transform
s deal with more than just points (usually you use them to plot something in another coordinate system), so to convert a set of points, we need to call the transform
method.
It seems cumbersome at first, but it's actually rather elegant. All plotted artists take a transfom
argument that defines the coordinate system they're drawn in. This is how things like annotate
allow a location defined by an offset in points from another location in data coordinates.