Store mouse click event coordinates with matplotlib Store mouse click event coordinates with matplotlib python python

Store mouse click event coordinates with matplotlib


mpl_connect needs to be called just once to connect the event to event handler. It will start listening to click event until you disconnect. And you can use

fig.canvas.mpl_disconnect(cid)

to disconnect the event hook.

What you want to do is something like:

import numpy as npimport matplotlib.pyplot as pltx = np.arange(-10,10)y = x**2fig = plt.figure()ax = fig.add_subplot(111)ax.plot(x,y)coords = []def onclick(event):    global ix, iy    ix, iy = event.xdata, event.ydata    print 'x = %d, y = %d'%(        ix, iy)    global coords    coords.append((ix, iy))    if len(coords) == 2:        fig.canvas.mpl_disconnect(cid)    return coordscid = fig.canvas.mpl_connect('button_press_event', onclick)


Thanks to otterb for providing the answer! I've added in a little function taken from here...Find nearest value in numpy array

In all this code will plot, wait for selection of x points and then return the indices of the x array needed for any integration, summations etc.

Ta,

import numpy as npimport matplotlib.pyplot as pltfrom scipy.integrate import trapzdef find_nearest(array,value):    idx = (np.abs(array-value)).argmin()    return array[idx]# Simple mouse click function to store coordinatesdef onclick(event):    global ix, iy    ix, iy = event.xdata, event.ydata    # print 'x = %d, y = %d'%(    #     ix, iy)    # assign global variable to access outside of function    global coords    coords.append((ix, iy))    # Disconnect after 2 clicks    if len(coords) == 2:        fig.canvas.mpl_disconnect(cid)        plt.close(1)    returnx = np.arange(-10,10)y = x**2fig = plt.figure(1)ax = fig.add_subplot(111)ax.plot(x,y)coords = []# Call click funccid = fig.canvas.mpl_connect('button_press_event', onclick)plt.show(1)# limits for integrationch1 = np.where(x == (find_nearest(x, coords[0][0])))ch2 = np.where(x == (find_nearest(x, coords[1][0])))# Calculate integraly_int = trapz(y[ch1[0][0]:ch2[0][0]], x = x[ch1[0][0]:ch2[0][0]])print ''print 'Integral between '+str(coords[0][0])+ ' & ' +str(coords[1][0])print y_int