matplotlib.widgets#
GUI neutral widgets#
Widgets that are designed to work for any of the GUI backends.All of these widgets require you to predefine anAxesinstance and pass that as the first parameter. Matplotlib doesn't try tobe too smart with respect to layout -- you will have to figure out howwide and tall you want your Axes to be to accommodate your widget.
- classmatplotlib.widgets.AxesWidget(ax)[source]#
Bases:
WidgetWidget connected to a single
Axes.To guarantee that the widget remains responsive and not garbage-collected,a reference to the object should be maintained by the user.
This is necessary because the callback registrymaintains only weak-refs to the functions, which are memberfunctions of the widget. If there are no references to the widgetobject it may be garbage collected which will disconnect the callbacks.
- Attributes:
- ax
Axes The parent Axes for the widget.
- canvas
FigureCanvasBase The parent figure canvas for the widget.
activeboolIs the widget active?
- ax
- propertycanvas#
- classmatplotlib.widgets.Button(ax,label,image=None,color='0.85',hovercolor='0.95',*,useblit=True)[source]#
Bases:
AxesWidgetA GUI neutral button.
For the button to remain responsive you must keep a reference to it.Call
on_clickedto connect to the button.- Attributes:
- Parameters:
- ax
Axes The
Axesinstance the button will be placed into.- labelstr
The button text.
- imagearray-like or PIL Image
The image to place in the button, if notNone. The parameter isdirectly forwarded to
imshow.- colorcolor
The color of the button when not activated.
- hovercolorcolor
The color of the button when the mouse is over it.
- useblitbool, default: True
Use blitting for faster drawing if supported by the backend.See the tutorialFaster rendering by using blitting for details.
Added in version 3.7.
- ax
- classmatplotlib.widgets.CheckButtons(ax,labels,actives=None,*,useblit=True,label_props=None,frame_props=None,check_props=None)[source]#
Bases:
AxesWidgetA GUI neutral set of check buttons.
For the check buttons to remain responsive you must keep areference to this object.
Connect to the CheckButtons with the
on_clickedmethod.- Attributes:
Add check buttons to
Axesinstanceax.- Parameters:
- ax
Axes The parent Axes for the widget.
- labelslist of str
The labels of the check buttons.
- activeslist of bool, optional
The initial check states of the buttons. The list must have thesame length aslabels. If not given, all buttons are unchecked.
- useblitbool, default: True
Use blitting for faster drawing if supported by the backend.See the tutorialFaster rendering by using blitting for details.
Added in version 3.7.
- label_propsdict of lists, optional
Dictionary of
Textproperties to be used for the labels. Eachdictionary value should be a list of at least a single element. Ifthe list is of length M, its values are cycled such that the Nthlabel gets the (N mod M) property.Added in version 3.7.
- frame_propsdict, optional
Dictionary of scatter
Collectionproperties to be used for thecheck button frame. Defaults (label font size / 2)**2 size, blackedgecolor, no facecolor, and 1.0 linewidth.Added in version 3.7.
- check_propsdict, optional
Dictionary of scatter
Collectionproperties to be used for thecheck button check. Defaults to (label font size / 2)**2 size,black color, and 1.0 linewidth.Added in version 3.7.
- ax
- on_clicked(func)[source]#
Connect the callback functionfunc to button click events.
- Parameters:
- funccallable
When the button is clicked, callfunc with button label.When all buttons are cleared, callfunc with None.The callback func must have the signature:
deffunc(label:str|None)->Any
Return values may exist, but are ignored.
- Returns:
- A connection id, which can be used to disconnect the callback.
- set_active(index,state=None)[source]#
Modify the state of a check button by index.
Callbacks will be triggered if
eventsonis True.- Parameters:
- indexint
Index of the check button to toggle.
- statebool, optional
If a boolean value, set the state explicitly. If no value isprovided, the state is toggled.
- Raises:
- ValueError
Ifindex is invalid.
- TypeError
Ifstate is not boolean.
- set_check_props(props)[source]#
Set properties of the check button checks.
Added in version 3.7.
- Parameters:
- propsdict
Dictionary of
Collectionproperties to be used for the checkbutton check.
- set_frame_props(props)[source]#
Set properties of the check button frames.
Added in version 3.7.
- Parameters:
- propsdict
Dictionary of
Collectionproperties to be used for the checkbutton frames.
- set_label_props(props)[source]#
Set properties of the
Textlabels.Added in version 3.7.
- Parameters:
- propsdict
Dictionary of
Textproperties to be used for the labels. Sameformat as label_props argument ofCheckButtons.
- classmatplotlib.widgets.Cursor(ax,*,horizOn=True,vertOn=True,useblit=False,**lineprops)[source]#
Bases:
AxesWidgetA crosshair cursor that spans the Axes and moves with mouse cursor.
For the cursor to remain responsive you must keep a reference to it.
- Parameters:
- ax
Axes The
Axesto attach the cursor to.- horizOnbool, default: True
Whether to draw the horizontal line.
- vertOnbool, default: True
Whether to draw the vertical line.
- useblitbool, default: False
Use blitting for faster drawing if supported by the backend.See the tutorialFaster rendering by using blitting for details.
- ax
- Other Parameters:
Examples
SeeCursor.
- classmatplotlib.widgets.EllipseSelector(ax,onselect=None,*,minspanx=0,minspany=0,useblit=False,props=None,spancoords='data',button=None,grab_range=10,handle_props=None,interactive=False,state_modifier_keys=None,drag_from_anywhere=False,ignore_event_outside=False,use_data_coordinates=False)[source]#
Bases:
RectangleSelectorSelect an elliptical region of an Axes.
For the cursor to remain responsive you must keep a reference to it.
Press and release events triggered at the same coordinates outside theselection will clear the selector, except when
ignore_event_outside=True.- Parameters:
- ax
Axes The parent Axes for the widget.
- onselectfunction, optional
A callback function that is called after a release event and theselection is created, changed or removed.It must have the signature:
defonselect(eclick:MouseEvent,erelease:MouseEvent)
whereeclick anderelease are the mouse click and release
MouseEvents that start and complete the selection.- minspanxfloat, default: 0
Selections with an x-span less than or equal tominspanx are removed(when already existing) or cancelled.
- minspanyfloat, default: 0
Selections with an y-span less than or equal tominspanx are removed(when already existing) or cancelled.
- useblitbool, default: False
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- propsdict, optional
Properties with which the ellipse is drawn. See
Patchfor valid properties.Default:dict(facecolor='red',edgecolor='black',alpha=0.2,fill=True)- spancoords{"data", "pixels"}, default: "data"
Whether to interpretminspanx andminspany in data or in pixelcoordinates.
- button
MouseButton, list ofMouseButton, default: all buttons Button(s) that trigger rectangle selection.
- grab_rangefloat, default: 10
Distance in pixels within which the interactive tool handles can beactivated.
- handle_propsdict, optional
Properties with which the interactive handles (marker artists) aredrawn. See the marker arguments in
Line2Dfor validproperties. Default values are defined inmpl.rcParamsexcept forthe default value ofmarkeredgecolorwhich will be the same as theedgecolorproperty inprops.- interactivebool, default: False
Whether to draw a set of handles that allow interaction with thewidget after it is drawn.
- state_modifier_keysdict, optional
Keyboard modifiers which affect the widget's behavior. Valuesamend the defaults, which are:
"move": Move the existing shape, default: no modifier.
"clear": Clear the current shape, default: "escape".
"square": Make the shape square, default: "shift".
"center": change the shape around its center, default: "ctrl".
"rotate": Rotate the shape around its center between -45° and 45°,default: "r".
"square" and "center" can be combined. The square shape can be definedin data or display coordinates as determined by the
use_data_coordinatesargument specified when creating the selector.- drag_from_anywherebool, default: False
If
True, the widget can be moved by clicking anywhere withinits bounds.- ignore_event_outsidebool, default: False
If
True, the event triggered outside the span selector will beignored.- use_data_coordinatesbool, default: False
If
True, the "square" shape of the selector is defined indata coordinates instead of display coordinates.
- ax
Examples
- classmatplotlib.widgets.Lasso(ax,xy,callback,*,useblit=True,props=None)[source]#
Bases:
AxesWidgetSelection curve of an arbitrary shape.
The selected path can be used in conjunction with
contains_pointto select data points from an image.Unlike
LassoSelector, this must be initialized with a startingpointxy, and theLassoevents are destroyed upon release.- Parameters:
- ax
Axes The parent Axes for the widget.
- xy(float, float)
Coordinates of the start of the lasso.
- callbackcallable
Whenever the lasso is released, thecallback function is called andpassed the vertices of the selected path.
- useblitbool, default: True
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- props: dict, optional
Lasso line properties. See
Line2Dfor valid properties.Defaultprops are:{'linestyle':'-','color':'black','lw':2}
Added in version 3.9.
- ax
- classmatplotlib.widgets.LassoSelector(ax,onselect=None,*,useblit=True,props=None,button=None)[source]#
Bases:
_SelectorWidgetSelection curve of an arbitrary shape.
For the selector to remain responsive you must keep a reference to it.
The selected path can be used in conjunction with
contains_pointto select data points from an image.In contrast to
Lasso,LassoSelectoris written with an interfacesimilar toRectangleSelectorandSpanSelector, and will continue tointeract with the Axes until disconnected.Example usage:
ax=plt.subplot()ax.plot(x,y)defonselect(verts):print(verts)lasso=LassoSelector(ax,onselect)
- Parameters:
- ax
Axes The parent Axes for the widget.
- onselectfunction, optional
Whenever the lasso is released, theonselect function is called andpassed the vertices of the selected path.
- useblitbool, default: True
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- propsdict, optional
Properties with which the line is drawn, see
Line2Dfor valid properties. Default values are defined inmpl.rcParams.- button
MouseButtonor list ofMouseButton, optional The mouse buttons used for rectangle selection. Default is
None,which corresponds to all buttons.
- ax
- classmatplotlib.widgets.LockDraw[source]#
Bases:
objectSome widgets, like the cursor, draw onto the canvas, and this is notdesirable under all circumstances, like when the toolbar is in zoom-to-rectmode and drawing a rectangle. To avoid this, a widget can acquire acanvas' lock with
canvas.widgetlock(widget)before drawing on thecanvas; this will prevent other widgets from doing so at the same time (ifthey also try to acquire the lock first).
- classmatplotlib.widgets.MultiCursor(canvas,axes,*,useblit=True,horizOn=False,vertOn=True,**lineprops)[source]#
Bases:
WidgetProvide a vertical (default) and/or horizontal line cursor shared betweenmultiple Axes.
For the cursor to remain responsive you must keep a reference to it.
- Parameters:
- canvasobject
This parameter is entirely unused and only kept for back-compatibility.
- axeslist of
Axes The
Axesto attach the cursor to.- useblitbool, default: True
Use blitting for faster drawing if supported by the backend.See the tutorialFaster rendering by using blittingfor details.
- horizOnbool, default: False
Whether to draw the horizontal line.
- vertOnbool, default: True
Whether to draw the vertical line.
- Other Parameters:
Examples
SeeMulticursor.
- classmatplotlib.widgets.PolygonSelector(ax,onselect=None,*,useblit=False,props=None,handle_props=None,grab_range=10,draw_bounding_box=False,box_handle_props=None,box_props=None)[source]#
Bases:
_SelectorWidgetSelect a polygon region of an Axes.
Place vertices with each mouse click, and make the selection by completingthe polygon (clicking on the first vertex). Once drawn individual verticescan be moved by clicking and dragging with the left mouse button, orremoved by clicking the right mouse button.
In addition, the following modifier keys can be used:
Holdctrl and click and drag a vertex to reposition it before thepolygon has been completed.
Hold theshift key and click and drag anywhere in the Axes to moveall vertices.
Press theesc key to start a new polygon.
For the selector to remain responsive you must keep a reference to it.
- Parameters:
- ax
Axes The parent Axes for the widget.
- onselectfunction, optional
When a polygon is completed or modified after completion,theonselect function is called and passed a list of the vertices as
(xdata,ydata)tuples.- useblitbool, default: False
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- propsdict, optional
Properties with which the line is drawn, see
Line2Dfor valid properties.Default:dict(color='k',linestyle='-',linewidth=2,alpha=0.5)
- handle_propsdict, optional
Artist properties for the markers drawn at the vertices of the polygon.See the marker arguments in
Line2Dfor validproperties. Default values are defined inmpl.rcParamsexcept forthe default value ofmarkeredgecolorwhich will be the same as thecolorproperty inprops.- grab_rangefloat, default: 10
A vertex is selected (to complete the polygon or to move a vertex) ifthe mouse click is withingrab_range pixels of the vertex.
- draw_bounding_boxbool, optional
If
True, a bounding box will be drawn around the polygon selectoronce it is complete. This box can be used to move and resize theselector.- box_handle_propsdict, optional
Properties to set for the box handles. See the documentation for thehandle_props argument to
RectangleSelectorfor more info.- box_propsdict, optional
Properties to set for the box. See the documentation for thepropsargument to
RectangleSelectorfor more info.
- ax
Notes
If only one point remains after removing points, the selector reverts to anincomplete state and you can start drawing a new polygon from the existingpoint.
Examples
Polygon SelectorSelect indices from a collection using polygon selector
- propertyverts#
The polygon vertices, as a list of
(x,y)pairs.
- classmatplotlib.widgets.RadioButtons(ax,labels,active=0,activecolor=None,*,useblit=True,label_props=None,radio_props=None)[source]#
Bases:
AxesWidgetA GUI neutral radio button.
For the buttons to remain responsive you must keep a reference to thisobject.
Connect to the RadioButtons with the
on_clickedmethod.- Attributes:
Add radio buttons to an
Axes.- Parameters:
- ax
Axes The Axes to add the buttons to.
- labelslist of str
The button labels.
- activeint
The index of the initially selected button.
- activecolorcolor
The color of the selected button. The default is
'blue'if notspecified here or inradio_props.- useblitbool, default: True
Use blitting for faster drawing if supported by the backend.See the tutorialFaster rendering by using blitting for details.
Added in version 3.7.
- label_propsdict of lists, optional
Dictionary of
Textproperties to be used for the labels. Eachdictionary value should be a list of at least a single element. Ifthe list is of length M, its values are cycled such that the Nthlabel gets the (N mod M) property.Added in version 3.7.
- radio_propsdict, optional
Dictionary of scatter
Collectionproperties to be used for theradio buttons. Defaults to (label font size / 2)**2 size, blackedgecolor, andactivecolor facecolor (when active).Note
If a facecolor is supplied inradio_props, it will overrideactivecolor. This may be used to provide an active color perbutton.
Added in version 3.7.
- ax
- propertyactivecolor#
- on_clicked(func)[source]#
Connect the callback functionfunc to button click events.
- Parameters:
- funccallable
When the button is clicked, callfunc with button label.When all buttons are cleared, callfunc with None.The callback func must have the signature:
deffunc(label:str|None)->Any
Return values may exist, but are ignored.
- Returns:
- A connection id, which can be used to disconnect the callback.
- set_active(index)[source]#
Select button with numberindex.
Callbacks will be triggered if
eventsonis True.- Parameters:
- indexint
The index of the button to activate.
- Raises:
- ValueError
If the index is invalid.
- set_label_props(props)[source]#
Set properties of the
Textlabels.Added in version 3.7.
- Parameters:
- propsdict
Dictionary of
Textproperties to be used for the labels. Sameformat as label_props argument ofRadioButtons.
- set_radio_props(props)[source]#
Set properties of the
Textlabels.Added in version 3.7.
- Parameters:
- propsdict
Dictionary of
Collectionproperties to be used for the radiobuttons.
- classmatplotlib.widgets.RangeSlider(ax,label,valmin,valmax,*,valinit=None,valfmt=None,closedmin=True,closedmax=True,dragging=True,valstep=None,orientation='horizontal',track_color='lightgrey',handle_style=None,**kwargs)[source]#
Bases:
SliderBaseA slider representing a range of floating point values. Defines the min andmax of the range via theval attribute as a tuple of (min, max).
Create a slider that defines a range contained within [valmin,valmax]in Axesax. For the slider to remain responsive you must maintain areference to it. Call
on_changed()to connect to the slider event.- Attributes:
- valtuple of float
Slider value.
- Parameters:
- axAxes
The Axes to put the slider in.
- labelstr
Slider label.
- valminfloat
The minimum value of the slider.
- valmaxfloat
The maximum value of the slider.
- valinittuple of float or None, default: None
The initial positions of the slider. If None the initial positionswill be at the 25th and 75th percentiles of the range.
- valfmtstr, default: None
%-format string used to format the slider values. If None, a
ScalarFormatteris used instead.- closedminbool, default: True
Whether the slider interval is closed on the bottom.
- closedmaxbool, default: True
Whether the slider interval is closed on the top.
- draggingbool, default: True
If True the slider can be dragged by the mouse.
- valstepfloat, default: None
If given, the slider will snap to multiples ofvalstep.
- orientation{'horizontal', 'vertical'}, default: 'horizontal'
The orientation of the slider.
- track_colorcolor, default: 'lightgrey'
The color of the background track. The track is accessible forfurther styling via thetrack attribute.
- handle_styledict
Properties of the slider handles. Default values are
Key
Value
Default
Description
facecolor
color
'white'
The facecolor of the slider handles.
edgecolor
color
'.75'
The edgecolor of the slider handles.
size
int
10
The size of the slider handles in points.
Other values will be transformed as marker{foo} and passed to the
Line2Dconstructor. e.g.handle_style={'style'='x'}willresult inmarkerstyle='x'.
Notes
Additional kwargs are passed on to
self.polywhich is thePolygonthat draws the slider knob. See thePolygondocumentation for valid property names (facecolor,edgecolor,alpha, etc.).
- classmatplotlib.widgets.RectangleSelector(ax,onselect=None,*,minspanx=0,minspany=0,useblit=False,props=None,spancoords='data',button=None,grab_range=10,handle_props=None,interactive=False,state_modifier_keys=None,drag_from_anywhere=False,ignore_event_outside=False,use_data_coordinates=False)[source]#
Bases:
_SelectorWidgetSelect a rectangular region of an Axes.
For the cursor to remain responsive you must keep a reference to it.
Press and release events triggered at the same coordinates outside theselection will clear the selector, except when
ignore_event_outside=True.- Parameters:
- ax
Axes The parent Axes for the widget.
- onselectfunction, optional
A callback function that is called after a release event and theselection is created, changed or removed.It must have the signature:
defonselect(eclick:MouseEvent,erelease:MouseEvent)
whereeclick anderelease are the mouse click and release
MouseEvents that start and complete the selection.- minspanxfloat, default: 0
Selections with an x-span less than or equal tominspanx are removed(when already existing) or cancelled.
- minspanyfloat, default: 0
Selections with an y-span less than or equal tominspanx are removed(when already existing) or cancelled.
- useblitbool, default: False
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- propsdict, optional
Properties with which the rectangle is drawn. See
Patchfor valid properties.Default:dict(facecolor='red',edgecolor='black',alpha=0.2,fill=True)- spancoords{"data", "pixels"}, default: "data"
Whether to interpretminspanx andminspany in data or in pixelcoordinates.
- button
MouseButton, list ofMouseButton, default: all buttons Button(s) that trigger rectangle selection.
- grab_rangefloat, default: 10
Distance in pixels within which the interactive tool handles can beactivated.
- handle_propsdict, optional
Properties with which the interactive handles (marker artists) aredrawn. See the marker arguments in
Line2Dfor validproperties. Default values are defined inmpl.rcParamsexcept forthe default value ofmarkeredgecolorwhich will be the same as theedgecolorproperty inprops.- interactivebool, default: False
Whether to draw a set of handles that allow interaction with thewidget after it is drawn.
- state_modifier_keysdict, optional
Keyboard modifiers which affect the widget's behavior. Valuesamend the defaults, which are:
"move": Move the existing shape, default: no modifier.
"clear": Clear the current shape, default: "escape".
"square": Make the shape square, default: "shift".
"center": change the shape around its center, default: "ctrl".
"rotate": Rotate the shape around its center between -45° and 45°,default: "r".
"square" and "center" can be combined. The square shape can be definedin data or display coordinates as determined by the
use_data_coordinatesargument specified when creating the selector.- drag_from_anywherebool, default: False
If
True, the widget can be moved by clicking anywhere withinits bounds.- ignore_event_outsidebool, default: False
If
True, the event triggered outside the span selector will beignored.- use_data_coordinatesbool, default: False
If
True, the "square" shape of the selector is defined indata coordinates instead of display coordinates.
- ax
Examples
>>>importmatplotlib.pyplotasplt>>>importmatplotlib.widgetsasmwidgets>>>fig,ax=plt.subplots()>>>ax.plot([1,2,3],[10,50,100])>>>defonselect(eclick,erelease):...print(eclick.xdata,eclick.ydata)...print(erelease.xdata,erelease.ydata)>>>props=dict(facecolor='blue',alpha=0.5)>>>rect=mwidgets.RectangleSelector(ax,onselect,interactive=True,...props=props)>>>fig.show()>>>rect.add_state('square')
See also:Rectangle and ellipse selectors
- propertycenter#
Center of rectangle in data coordinates.
- propertycorners#
Corners of rectangle in data coordinates from lower left,moving clockwise.
- propertyedge_centers#
Midpoint of rectangle edges in data coordinates from left,moving anti-clockwise.
- propertyextents#
Return (xmin, xmax, ymin, ymax) in data coordinates as defined by thebounding box before rotation.
- propertygeometry#
Return an array of shape (2, 5) containing thex (
RectangleSelector.geometry[1,:]) andy (RectangleSelector.geometry[0,:]) data coordinates of the fourcorners of the rectangle starting and ending in the top left corner.
- propertyrotation#
Rotation in degree in interval [-45°, 45°]. The rotation is limited inrange to keep the implementation simple.
- classmatplotlib.widgets.Slider(ax,label,valmin,valmax,*,valinit=0.5,valfmt=None,closedmin=True,closedmax=True,slidermin=None,slidermax=None,dragging=True,valstep=None,orientation='horizontal',initcolor='r',track_color='lightgrey',handle_style=None,**kwargs)[source]#
Bases:
SliderBaseA slider representing a floating point range.
Create a slider fromvalmin tovalmax in Axesax. For the slider toremain responsive you must maintain a reference to it. Call
on_changed()to connect to the slider event.- Attributes:
- valfloat
Slider value.
- Parameters:
- axAxes
The Axes to put the slider in.
- labelstr
Slider label.
- valminfloat
The minimum value of the slider.
- valmaxfloat
The maximum value of the slider.
- valinitfloat, default: 0.5
The slider initial position.
- valfmtstr, default: None
%-format string used to format the slider value. If None, a
ScalarFormatteris used instead.- closedminbool, default: True
Whether the slider interval is closed on the bottom.
- closedmaxbool, default: True
Whether the slider interval is closed on the top.
- sliderminSlider, default: None
Do not allow the current slider to have a value less thanthe value of the Sliderslidermin.
- slidermaxSlider, default: None
Do not allow the current slider to have a value greater thanthe value of the Sliderslidermax.
- draggingbool, default: True
If True the slider can be dragged by the mouse.
- valstepfloat or array-like, default: None
If a float, the slider will snap to multiples ofvalstep.If an array the slider will snap to the values in the array.
- orientation{'horizontal', 'vertical'}, default: 'horizontal'
The orientation of the slider.
- initcolorcolor, default: 'r'
The color of the line at thevalinit position. Set to
'none'for no line.- track_colorcolor, default: 'lightgrey'
The color of the background track. The track is accessible forfurther styling via thetrack attribute.
- handle_styledict
Properties of the slider handle. Default values are
Key
Value
Default
Description
facecolor
color
'white'
The facecolor of the slider handle.
edgecolor
color
'.75'
The edgecolor of the slider handle.
size
int
10
The size of the slider handle in points.
Other values will be transformed as marker{foo} and passed to the
Line2Dconstructor. e.g.handle_style={'style'='x'}willresult inmarkerstyle='x'.
Notes
Additional kwargs are passed on to
self.polywhich is theRectanglethat draws the slider knob. See theRectangledocumentation for valid property names (facecolor,edgecolor,alpha, etc.).
- classmatplotlib.widgets.SliderBase(ax,orientation,closedmin,closedmax,valmin,valmax,valfmt,dragging,valstep)[source]#
Bases:
AxesWidgetThe base class for constructing Slider widgets. Not intended for directusage.
For the slider to remain responsive you must maintain a reference to it.
- classmatplotlib.widgets.SpanSelector(ax,onselect,direction,*,minspan=0,useblit=False,props=None,onmove_callback=None,interactive=False,button=None,handle_props=None,grab_range=10,state_modifier_keys=None,drag_from_anywhere=False,ignore_event_outside=False,snap_values=None)[source]#
Bases:
_SelectorWidgetVisually select a min/max range on a single axis and call a function withthose values.
To guarantee that the selector remains responsive, keep a reference to it.
In order to turn off the SpanSelector, set
span_selector.activetoFalse. To turn it back on, set it to True.Press and release events triggered at the same coordinates outside theselection will clear the selector, except when
ignore_event_outside=True.- Parameters:
- ax
Axes - onselectcallable with signature
func(min:float,max:float) A callback function that is called after a release event and theselection is created, changed or removed.
- direction{"horizontal", "vertical"}
The direction along which to draw the span selector.
- minspanfloat, default: 0
If selection is less than or equal tominspan, the selection isremoved (when already existing) or cancelled.
- useblitbool, default: False
If True, use the backend-dependent blitting features for fastercanvas updates. See the tutorialFaster rendering by using blitting for details.
- propsdict, default: {'facecolor': 'red', 'alpha': 0.5}
Dictionary of
Patchproperties.- onmove_callbackcallable with signature
func(min:float,max:float), optional Called on mouse move while the span is being selected.
- interactivebool, default: False
Whether to draw a set of handles that allow interaction with thewidget after it is drawn.
- button
MouseButtonor list ofMouseButton, default: all buttons The mouse buttons which activate the span selector.
- handle_propsdict, default: None
Properties of the handle lines at the edges of the span. Only usedwheninteractive is True. See
Line2Dfor valid properties.- grab_rangefloat, default: 10
Distance in pixels within which the interactive tool handles can be activated.
- state_modifier_keysdict, optional
Keyboard modifiers which affect the widget's behavior. Valuesamend the defaults, which are:
"clear": Clear the current shape, default: "escape".
- drag_from_anywherebool, default: False
If
True, the widget can be moved by clicking anywhere within its bounds.- ignore_event_outsidebool, default: False
If
True, the event triggered outside the span selector will be ignored.- snap_values1D array-like, optional
Snap the selector edges to the given values.
- ax
Examples
>>>importmatplotlib.pyplotasplt>>>importmatplotlib.widgetsasmwidgets>>>fig,ax=plt.subplots()>>>ax.plot([1,2,3],[10,50,100])>>>defonselect(vmin,vmax):...print(vmin,vmax)>>>span=mwidgets.SpanSelector(ax,onselect,'horizontal',...props=dict(facecolor='blue',alpha=0.5))>>>fig.show()
See also:Span Selector
- propertydirection#
Direction of the span selector: 'vertical' or 'horizontal'.
- propertyextents#
- (float, float)
The values, in data coordinates, for the start and end points of the currentselection. If there is no selection then the start and end values will bethe same.
- classmatplotlib.widgets.SubplotTool(targetfig,toolfig)[source]#
Bases:
WidgetA tool to adjust the subplot params of a
Figure.
- classmatplotlib.widgets.TextBox(ax,label,initial='',*,color='.95',hovercolor='1',label_pad=0.01,textalignment='left')[source]#
Bases:
AxesWidgetA GUI neutral text input box.
For the text box to remain responsive you must keep a reference to it.
Call
on_text_changeto be updated whenever the text changes.Call
on_submitto be updated whenever the user hits enter orleaves the text entry field.- Attributes:
- Parameters:
- ax
Axes The
Axesinstance the button will be placed into.- labelstr
Label for this text box.
- initialstr
Initial value in the text box.
- colorcolor
The color of the box.
- hovercolorcolor
The color of the box when the mouse is over it.
- label_padfloat
The distance between the label and the right side of the textbox.
- textalignment{'left', 'center', 'right'}
The horizontal location of the text.
- ax
- on_submit(func)[source]#
When the user hits enter or leaves the submission box, call thisfunc with event.
A connection id is returned which can be used to disconnect.
- on_text_change(func)[source]#
When the text changes, call thisfunc with event.
A connection id is returned which can be used to disconnect.
- propertytext#
- classmatplotlib.widgets.ToolHandles(ax,x,y,*,marker='o',marker_props=None,useblit=True)[source]#
Bases:
objectControl handles for canvas tools.
- Parameters:
- ax
Axes Matplotlib Axes where tool handles are displayed.
- x, y1D arrays
Coordinates of control handles.
- markerstr, default: 'o'
Shape of marker used to display handle. See
plot.- marker_propsdict, optional
Additional marker properties. See
Line2D.- useblitbool, default: True
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- ax
- propertyartists#
- propertyx#
- propertyy#
- classmatplotlib.widgets.ToolLineHandles(ax,positions,direction,*,line_props=None,useblit=True)[source]#
Bases:
objectControl handles for canvas tools.
- Parameters:
- ax
Axes Matplotlib Axes where tool handles are displayed.
- positions1D array
Positions of handles in data coordinates.
- direction{"horizontal", "vertical"}
Direction of handles, either 'vertical' or 'horizontal'
- line_propsdict, optional
Additional line properties. See
Line2D.- useblitbool, default: True
Whether to use blitting for faster drawing (if supported by thebackend). See the tutorialFaster rendering by using blittingfor details.
- ax
- propertyartists#
- closest(x,y)[source]#
Return index and pixel distance to closest handle.
- Parameters:
- x, yfloat
x, y position from which the distance will be calculated todeterminate the closest handle
- Returns:
- index, distanceindex of the handle and its distance from
position x, y
- propertydirection#
Direction of the handle: 'vertical' or 'horizontal'.
- propertypositions#
Positions of the handle in data coordinates.