Problem Statement
You need to interactively identify a point in a Matplotlib plot.
Solution
This solution requires three parts. First, a function is defined which is executed when a plot element is selected. Second, this function is connected to the figure. Finally, when a point is plotted, a picker radius is added which defines how big of an area should react to the pick event. One way to get a unique response from each point is to add an attribute to each point. In this example, a string is added with information about the point location. More complex responses can be created by considering an attribute like this in ‘onpick’ function.
__author__ = 'Ed Tate' __email__ = 'edtate<at>gmail-dot-com' __website__ = 'exnumerus.blogspot.com' __license__ = 'Creative Commons Attribute By - http://creativecommons.org/licenses/by/3.0/us/''' import matplotlib.pylab as p import random # define what should happen when a point is picked def onpick(event): thisline = event.artist name = thisline.name print name # create the figure and add the handler which reacts to a pick event fig = p.figure() fig.canvas.mpl_connect('pick_event',onpick) # create random set of points to plot x_pts = [random.uniform(0,1) for i in range(0,500)] y_pts = [random.uniform(0,1) for i in range(0,500)] for x,y in zip(x_pts,y_pts): pt, = p.plot(x,y,'.b',picker=3) pt.name = 'Point located at (%f,%f)' % (x,y) p.show()
When this script is executed, picking a point results in a message which shows which point was chosen:
Point located at (0.481866,0.661643)
References
Testing Conditions
No comments:
Post a Comment