Note
Go to the endto download the full example code.
Lasso Demo#
Use a lasso to select a set of points and get the indices of the selected points.A callback is used to change the color of the selected points.
Note
This example exercises the interactive capabilities of Matplotlib, and thiswill not appear in the static documentation. Please run this code on yourmachine to see the interactivity.
You can copy and paste individual parts, or download the entire exampleusing the link at the bottom of the page.

importmatplotlib.pyplotaspltimportnumpyasnpfrommatplotlibimportcolorsasmcolorsfrommatplotlibimportpathfrommatplotlib.collectionsimportRegularPolyCollectionfrommatplotlib.widgetsimportLassoclassLassoManager:def__init__(self,ax,data):# The information of whether a point has been selected or not is stored in the# collection's array (0 = out, 1 = in), which then gets colormapped to blue# (out) and red (in).self.collection=RegularPolyCollection(6,sizes=(100,),offset_transform=ax.transData,offsets=data,array=np.zeros(len(data)),clim=(0,1),cmap=mcolors.ListedColormap(["tab:blue","tab:red"]))ax.add_collection(self.collection)canvas=ax.figure.canvascanvas.mpl_connect('button_press_event',self.on_press)canvas.mpl_connect('button_release_event',self.on_release)defcallback(self,verts):data=self.collection.get_offsets()self.collection.set_array(path.Path(verts).contains_points(data))canvas=self.collection.figure.canvascanvas.draw_idle()delself.lassodefon_press(self,event):canvas=self.collection.figure.canvasifevent.inaxesisnotself.collection.axesorcanvas.widgetlock.locked():returnself.lasso=Lasso(event.inaxes,(event.xdata,event.ydata),self.callback)canvas.widgetlock(self.lasso)# acquire a lock on the widget drawingdefon_release(self,event):canvas=self.collection.figure.canvasifhasattr(self,'lasso')andcanvas.widgetlock.isowner(self.lasso):canvas.widgetlock.release(self.lasso)if__name__=='__main__':np.random.seed(19680801)ax=plt.figure().add_subplot(xlim=(0,1),ylim=(0,1),title='Lasso points using left mouse button')manager=LassoManager(ax,np.random.rand(100,2))plt.show()