Tuesday, March 8, 2011

A Python Recipe to Interactively Identify Elements in Matplotlib

Problem Statement

You need to interactively identify a point in a Matplotlib plot.



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()

# 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)


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)


Testing Conditions

This work is licensed under a Creative Commons Attribution By license.

No comments:

Post a Comment