|
| 1 | +""" |
| 2 | +Show how to use a lasso to select a set of points and get the indices |
| 3 | +of the selected points. A callback is used to change the color of the |
| 4 | +selected points |
| 5 | +
|
| 6 | +This is currently a proof-of-concept implementation (though it is |
| 7 | +usable as is). There will be some refinement of the API and the |
| 8 | +inside polygon detection routine. |
| 9 | +""" |
| 10 | +from matplotlib.widgets import Lasso |
| 11 | +from matplotlib.mlab import inside_poly |
| 12 | +from matplotlib.colors import colorConverter |
| 13 | +from matplotlib.collections import RegularPolyCollection |
| 14 | + |
| 15 | +from pylab import figure, show, nx |
| 16 | + |
| 17 | +class Datum: |
| 18 | + colorin = colorConverter.to_rgba('red') |
| 19 | + colorout = colorConverter.to_rgba('green') |
| 20 | + def __init__(self, x, y, include=False): |
| 21 | + self.x = x |
| 22 | + self.y = y |
| 23 | + if include: self.color = self.colorin |
| 24 | + else: self.color = self.colorout |
| 25 | + |
| 26 | + |
| 27 | +class LassoManager: |
| 28 | + def __init__(self, ax, data): |
| 29 | + self.axes = ax |
| 30 | + self.canvas = ax.figure.canvas |
| 31 | + self.data = data |
| 32 | + |
| 33 | + self.Nxy = len(data) |
| 34 | + |
| 35 | + self.facecolors = [d.color for d in data] |
| 36 | + self.xys = [(d.x, d.y) for d in data] |
| 37 | + |
| 38 | + self.collection = RegularPolyCollection( |
| 39 | + fig.dpi, 6, sizes=(100,), |
| 40 | + facecolors=self.facecolors, |
| 41 | + offsets = self.xys, |
| 42 | + transOffset = ax.transData) |
| 43 | + |
| 44 | + ax.add_collection(self.collection) |
| 45 | + |
| 46 | + self.cid = self.canvas.mpl_connect('button_press_event', self.onpress) |
| 47 | + |
| 48 | + def callback(self, verts): |
| 49 | + #print 'all done', verts |
| 50 | + ind = inside_poly(self.xys, verts) |
| 51 | + |
| 52 | + for i in range(self.Nxy): |
| 53 | + if i in ind: |
| 54 | + self.facecolors[i] = Datum.colorin |
| 55 | + else: |
| 56 | + self.facecolors[i] = Datum.colorout |
| 57 | + |
| 58 | + self.canvas.draw_idle() |
| 59 | + |
| 60 | + def onpress(self, event): |
| 61 | + if event.inaxes is None: return |
| 62 | + self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback) |
| 63 | + |
| 64 | +data = [Datum(*xy) for xy in nx.mlab.rand(100, 2)] |
| 65 | + |
| 66 | +fig = figure() |
| 67 | +ax = fig.add_subplot(111, xlim=(0,1), ylim=(0,1), autoscale_on=False) |
| 68 | +lman = LassoManager(ax, data) |
| 69 | + |
| 70 | +show() |
0 commit comments