pick event

I am trying to use pick event. See the simple script
below. I am interested to find the shortest distance between pick
point (mouse coord.) and the line at the discrete points only (points on
the curve from data)

What am I doing wrong ?



import numpy as np

import matplotlib.pyplot as plt

from matplotlib.lines import Line2D

import math as math

create figure and attach axes to it

fig = plt.figure(1)

ax = fig.add_subplot(111)

def getMinDistance(xmouse, ymouse, xList, yList):


find shortest distance between mouse

coordinates and pick point

point pick may be a list of points if

data is clouded


xmouse - x coordinate of mouse (x - pick)

ymouse - y coordinate of mouse (y - pick)

xList  - xData from curve

yList  - yData from curve


dmin  - minimum distance

index - index of data point in the xList

and yList


dmin  = math.sqrt((xList[0] -

xmouse)**2. + (yList[0]-ymouse)**2.)

index = 0

for idx in range(1,len(xList)):

    d =

math.sqrt((xList[idx] - xmouse)**2. + (yList[idx]-ymouse)**2.)

    if(d < dmin):

dmin = d

index = idx

return dmin, index

def showMarker(x, y, color):


draw marker at loction x, y with color


# draw marker

markerOn, = ax.plot(x, y, 'o', color =


def OnPick(event):


pick event


print '****************************'

mouseEvent = event.mouseevent

# get pick coord

xmouse, ymouse = mouseEvent.xdata,


# get the artist

lineObj = event.artist

print lineObj

if not isinstance(lineObj, Line2D):


ind = event.ind

# check if indexes exist of the pick


N = len(ind)

if not N:


# get curve picked data

Xdata, Ydata = lineObj.get_data()

color = lineObj.get_color()

xLi = np.take(Xdata, ind)

yLi = np.take(Ydata, ind)

dmin, index = getMinDistance(xmouse,

ymouse, xLi, yLi)

xP = xLi[index]

yP = yLi[index]

xStr = '%.4g' % xP

yStr = '%.4g' % yP

txt = 'X = ' + xStr + ' ;  ' + 'Y =

’ + yStr

print txt

# show marker

showMarker(xP, yP, color)

# redraw to show marker


connect to pick event


generate data for display

x = np.arange(-4,4,0.1) # x-

y2 = x**2 + 5.0

y coord of first curve

y = 2*x +

y coord of the second curve

create the list of x and y data

xList = [x,

yList = [y, y2]

objList = [] # store draw lines

display 2 curves

for idx in range(len(xList)):

obj, = ax.plot(xList[idx], yList[idx],

picker = 5)


display plot


Arek Kędzior:

I am trying to use pick event.

What am I doing wrong ?

Wrong with WHAT?

What do you expect?

Jerzy Karczmarczuk


Could you provide a little more detail about your issue?


Ben Root


On Saturday, May 12, 2012, Jerzy Karczmarczuk wrote:

Arek Kędzior:

I am trying to use pick event.

What am I doing wrong ?

Wrong with WHAT?

What do you expect?

Jerzy Karczmarczuk