Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect relative mouse position on matplotlib canvas

Tags:

matplotlib

I wish create a custom hover action in matplotlib using the onmove function below. What is the best way of converting existing datapoint values in x and event.x to another coordinate system such as points so that I can detect when event.x is within p points of any data point? I am aware of the picker event, but do not want to use this, as it is based on a click, not a hover.

fig = figure()
ax1 = subplot(111)
x = linspace(0,10,11)
y = x**2
ax1.plot(x,y)
fig.canvas.mpl_connect('motion_notify_event', onmove)
p = 5

def onmove(event):
    if event.inaxes:
    #Detect if mouse was moved within p points of any value in x
like image 874
mr_js Avatar asked Nov 28 '11 15:11

mr_js


1 Answers

I answered a related question the other day.

Your "points" (or device) coordinate conversion depends on the original coordinate system of x and y. If (x, y) is data values on an axes, ax, then you can convert them with ax.transData.transform_point([x, y]). If (x, y) are in axes coordinates (0-1) then ax.transAxes is what you are after.

The events that onmove receive will have attributes of x and y which will be the (x, y) in device (pixel) coordinates

The relevant documentation for this information can be found: http://matplotlib.sourceforge.net/users/transforms_tutorial.html and http://matplotlib.sourceforge.net/users/event_handling.html

Additionally artists (lines, patches etc.) have a contains method which might be of interest to you: http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.artist.Artist.contains.

like image 191
pelson Avatar answered Oct 26 '22 06:10

pelson