Note

Go to the endto download the full example code.

Rectangle and ellipse selectors#

Click somewhere, move the mouse, and release the mouse button.RectangleSelector andEllipseSelector draw a rectangle or an ellipsefrom the initial click position to the current mouse position (within the sameaxes) until the button is released. A connected callback receives the click-and release-events.

importmatplotlib.pyplotaspltimportnumpyasnpfrommatplotlib.widgetsimportEllipseSelector,RectangleSelectordefselect_callback(eclick,erelease):"""    Callback for line selection.    *eclick* and *erelease* are the press and release events.    """x1,y1=eclick.xdata,eclick.ydatax2,y2=erelease.xdata,erelease.ydataprint(f"({x1:3.2f},{y1:3.2f}) --> ({x2:3.2f},{y2:3.2f})")print(f"The buttons you used were:{eclick.button}{erelease.button}")deftoggle_selector(event):print('Key pressed.')ifevent.key=='t':forselectorinselectors:name=type(selector).__name__ifselector.active:print(f'{name} deactivated.')selector.set_active(False)else:print(f'{name} activated.')selector.set_active(True)fig=plt.figure(layout='constrained')axs=fig.subplots(2)N=100000# If N is large one can see improvement by using blitting.x=np.linspace(0,10,N)selectors=[]forax,selector_classinzip(axs,[RectangleSelector,EllipseSelector]):ax.plot(x,np.sin(2*np.pi*x))# plot somethingax.set_title(f"Click and drag to draw a{selector_class.__name__}.")selectors.append(selector_class(ax,select_callback,useblit=True,button=[1,3],# disable middle buttonminspanx=5,minspany=5,spancoords='pixels',interactive=True))fig.canvas.mpl_connect('key_press_event',toggle_selector)axs[0].set_title("Press 't' to toggle the selectors on and off.\n"+axs[0].get_title())plt.show()
Press 't' to toggle the selectors on and off. Click and drag to draw a RectangleSelector., Click and drag to draw a EllipseSelector.

References

The use of the following functions, methods, classes and modules is shownin this example:

Gallery generated by Sphinx-Gallery