widgets

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 a matplotlib.axes.Axes instance and pass that as the first arg. matplotlib doesn't try to be too smart with respect to layout -- you will have to figure out how wide and tall you want your Axes to be to accommodate your widget.

class matplotlib.widgets.AxesWidget(ax) [source]

Bases: matplotlib.widgets.Widget

Widget that is 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 registry maintains only weak-refs to the functions, which are member functions of the widget. If there are no references to the widget object it may be garbage collected which will disconnect the callbacks.

Attributes:

ax : Axes
The parent axes for the widget
canvas : FigureCanvasBase subclass
The parent figure canvas for the widget.
active : bool
If False, the widget does not respond to events.
connect_event(event, callback) [source]

Connect callback with an event.

This should be used in lieu of figure.canvas.mpl_connect since this function stores callback ids for later clean up.

disconnect_events() [source]

Disconnect all events created by this widget.

class matplotlib.widgets.Button(ax, label, image=None, color='0.85', hovercolor='0.95') [source]

Bases: matplotlib.widgets.AxesWidget

A GUI neutral button.

For the button to remain responsive you must keep a reference to it. Call on_clicked() to connect to the button.

Attributes:
ax :

The matplotlib.axes.Axes the button renders into.

label :

A matplotlib.text.Text instance.

color :

The color of the button when not hovering.

hovercolor :

The color of the button when hovering.

Parameters:
ax : matplotlib.axes.Axes

The matplotlib.axes.Axes instance the button will be placed into.

label : str

The button text. Accepts string.

image : array, mpl image, Pillow Image

The image to place in the button, if not None. Can be any legal arg to imshow (numpy array, matplotlib Image instance, or Pillow Image).

color : color

The color of the button when not activated

hovercolor : color

The color of the button when the mouse is over it

disconnect(cid) [source]

remove the observer with connection id cid

on_clicked(func) [source]

When the button is clicked, call this func with event.

A connection id is returned. It can be used to disconnect the button from its callback.

class matplotlib.widgets.CheckButtons(ax, labels, actives=None) [source]

Bases: matplotlib.widgets.AxesWidget

A GUI neutral set of check buttons.

For the check buttons to remain responsive you must keep a reference to this object.

The following attributes are exposed

ax
The matplotlib.axes.Axes instance the buttons are located in
labels
List of matplotlib.text.Text instances
lines
List of (line1, line2) tuples for the x's in the check boxes. These lines exist for each box, but have set_visible(False) when its box is not checked.
rectangles
List of matplotlib.patches.Rectangle instances

Connect to the CheckButtons with the on_clicked() method

Add check buttons to matplotlib.axes.Axes instance ax

Parameters:
ax : Axes

The parent axes for the widget.

labels : List[str]

The labels of the check buttons.

actives : List[bool], optional

The initial check states of the buttons. The list must have the same length as labels. If not given, all buttons are unchecked.

disconnect(cid) [source]

remove the observer with connection id cid

get_status() [source]

returns a tuple of the status (True/False) of all of the check buttons

on_clicked(func) [source]

When the button is clicked, call func with button label

A connection id is returned which can be used to disconnect

set_active(index) [source]

Directly (de)activate a check button by index.

index is an index into the original label list
that this object was constructed with. Raises ValueError if index is invalid.

Callbacks will be triggered if eventson is True.

class matplotlib.widgets.Cursor(ax, horizOn=True, vertOn=True, useblit=False, **lineprops) [source]

Bases: matplotlib.widgets.AxesWidget

A horizontal and vertical line that spans the axes and moves with the pointer. You can turn off the hline or vline respectively with the following attributes:

horizOn
Controls the visibility of the horizontal line
vertOn
Controls the visibility of the horizontal line

and the visibility of the cursor itself with the visible attribute.

For the cursor to remain responsive you must keep a reference to it.

Add a cursor to ax. If useblit=True, use the backend-dependent blitting features for faster updates. lineprops is a dictionary of line properties.

clear(event) [source]

clear the cursor

onmove(event) [source]

on mouse motion draw the cursor if visible

class matplotlib.widgets.EllipseSelector(ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None) [source]

Bases: matplotlib.widgets.RectangleSelector

Select an elliptical region of an axes.

For the cursor to remain responsive you must keep a reference to it.

Example usage:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import EllipseSelector

def onselect(eclick, erelease):
    "eclick and erelease are matplotlib events at press and release."
    print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
    print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
    print('used button  : ', eclick.button)

def toggle_selector(event):
    print(' Key pressed.')
    if event.key in ['Q', 'q'] and toggle_selector.ES.active:
        print('EllipseSelector deactivated.')
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.ES.active:
        print('EllipseSelector activated.')
        toggle_selector.ES.set_active(True)

x = np.arange(100.) / 99
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line')
fig.canvas.connect('key_press_event', toggle_selector)
plt.show()

Create a selector in ax. When a selection is made, clear the span and call onselect with:

onselect(pos_1, pos_2)

and clear the drawn box/line. The pos_1 and pos_2 are arrays of length 2 containing the x- and y-coordinate.

If minspanx is not None then events smaller than minspanx in x direction are ignored (it's the same for y).

The rectangle is drawn with rectprops; default:

rectprops = dict(facecolor='red', edgecolor = 'black',
                 alpha=0.2, fill=True)

The line is drawn with lineprops; default:

lineprops = dict(color='black', linestyle='-',
                 linewidth = 2, alpha=0.5)

Use drawtype if you want the mouse to draw a line, a box or nothing between click and actual position by setting

drawtype = 'line', drawtype='box' or drawtype = 'none'. Drawing a line would result in a line from vertex A to vertex C in a rectangle ABCD.

spancoords is one of 'data' or 'pixels'. If 'data', minspanx and minspanx will be interpreted in the same coordinates as the x and y axis. If 'pixels', they are in pixels.

button is a list of integers indicating which mouse buttons should be used for rectangle selection. You can also specify a single integer if only a single button is desired. Default is None, which does not limit which button can be used.

Note, typically:
1 = left mouse button 2 = center mouse button (scroll wheel) 3 = right mouse button

interactive will draw a set of handles and allow you interact with the widget after it is drawn.

state_modifier_keys are keyboard modifiers that affect the behavior of the widget.

The defaults are: dict(move=' ', clear='escape', square='shift', center='ctrl')

Keyboard modifiers, which: 'move': Move the existing shape. 'clear': Clear the current shape. 'square': Makes the shape square. 'center': Make the initial point the center of the shape. 'square' and 'center' can be combined.

draw_shape(extents) [source]
class matplotlib.widgets.Lasso(ax, xy, callback=None, useblit=True) [source]

Bases: matplotlib.widgets.AxesWidget

Selection curve of an arbitrary shape.

The selected path can be used in conjunction with contains_point() to select data points from an image.

Unlike LassoSelector, this must be initialized with a starting point xy, and the Lasso events are destroyed upon release.

Parameters:
ax : Axes

The parent axes for the widget.

xy : array

Coordinates of the start of the lasso.

callback : callable

Whenever the lasso is released, the callback function is called and passed the vertices of the selected path.

onmove(event) [source]
onrelease(event) [source]
class matplotlib.widgets.LassoSelector(ax, onselect=None, useblit=True, lineprops=None, button=None) [source]

Bases: matplotlib.widgets._SelectorWidget

Selection 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_point to select data points from an image.

In contrast to Lasso, LassoSelector is written with an interface similar to RectangleSelector and SpanSelector, and will continue to interact with the axes until disconnected.

Example usage:

ax = subplot(111)
ax.plot(x,y)

def onselect(verts):
    print(verts)
lasso = LassoSelector(ax, onselect)
Parameters:
ax : Axes

The parent axes for the widget.

onselect : function

Whenever the lasso is released, the onselect function is called and passed the vertices of the selected path.

button : List[Int], optional

A list of integers indicating which mouse buttons should be used for rectangle selection. You can also specify a single integer if only a single button is desired. Default is None, which does not limit which button can be used.

Note, typically:

  • 1 = left mouse button
  • 2 = center mouse button (scroll wheel)
  • 3 = right mouse button
onpress(event) [source]
onrelease(event) [source]
class matplotlib.widgets.LockDraw [source]

Bases: object

Some widgets, like the cursor, draw onto the canvas, and this is not desirable under all circumstances, like when the toolbar is in zoom-to-rect mode and drawing a rectangle. To avoid this, a widget can acquire a canvas' lock with canvas.widgetlock(widget) before drawing on the canvas; this will prevent other widgets from doing so at the same time (if they also try to acquire the lock first).

available(o) [source]

Return whether drawing is available to o.

isowner(o) [source]

Return whether o owns this lock.

locked() [source]

Return whether the lock is currently held by an owner.

release(o) [source]

Release the lock from o.

class matplotlib.widgets.MultiCursor(canvas, axes, useblit=True, horizOn=False, vertOn=True, **lineprops) [source]

Bases: matplotlib.widgets.Widget

Provide a vertical (default) and/or horizontal line cursor shared between multiple axes.

For the cursor to remain responsive you must keep a reference to it.

Example usage:

from matplotlib.widgets import MultiCursor
import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
t = np.arange(0.0, 2.0, 0.01)
ax1.plot(t, np.sin(2*np.pi*t))
ax2.plot(t, np.sin(4*np.pi*t))

multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
                    horizOn=False, vertOn=True)
plt.show()
clear(event) [source]

clear the cursor

connect() [source]

connect events

disconnect() [source]

disconnect events

onmove(event) [source]
class matplotlib.widgets.PolygonSelector(ax, onselect, useblit=False, lineprops=None, markerprops=None, vertex_select_radius=15) [source]

Bases: matplotlib.widgets._SelectorWidget

Select a polygon region of an axes.

Place vertices with each mouse click, and make the selection by completing the polygon (clicking on the first vertex). Hold the ctrl key and click and drag a vertex to reposition it (the ctrl key is not necessary if the polygon has already been completed). Hold the shift key and click and drag anywhere in the axes to move all vertices. Press the esc 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.

onselect : function

When a polygon is completed or modified after completion, the onselect function is called and passed a list of the vertices as (xdata, ydata) tuples.

useblit : bool, optional
lineprops : dict, optional

The line for the sides of the polygon is drawn with the properties given by lineprops. The default is dict(color='k', linestyle='-', linewidth=2, alpha=0.5).

markerprops : dict, optional

The markers for the vertices of the polygon are drawn with the properties given by markerprops. The default is dict(marker='o', markersize=7, mec='k', mfc='k', alpha=0.5).

vertex_select_radius : float, optional

A vertex is selected (to complete the polygon or to move a vertex) if the mouse click is within vertex_select_radius pixels of the vertex. The default radius is 15 pixels.

Examples

Polygon Selector Demo

onmove(event) [source]

Cursor move event handler and validator

verts

Get the polygon vertices.

Returns:
list

A list of the vertices of the polygon as (xdata, ydata) tuples.

class matplotlib.widgets.RadioButtons(ax, labels, active=0, activecolor='blue') [source]

Bases: matplotlib.widgets.AxesWidget

A GUI neutral radio button.

For the buttons to remain responsive you must keep a reference to this object.

The following attributes are exposed:

ax
The matplotlib.axes.Axes instance the buttons are in
activecolor
The color of the button when clicked
labels
A list of matplotlib.text.Text instances
circles
A list of matplotlib.patches.Circle instances
value_selected
A string listing the current value selected

Connect to the RadioButtons with the on_clicked() method

Add radio buttons to matplotlib.axes.Axes instance ax

labels
A len(buttons) list of labels as strings
active
The index into labels for the button that is active
activecolor
The color of the button when clicked
disconnect(cid) [source]

remove the observer with connection id cid

on_clicked(func) [source]

When the button is clicked, call func with button label

A connection id is returned which can be used to disconnect

set_active(index) [source]

Trigger which radio button to make active.

index is an index into the original label list
that this object was constructed with. Raise ValueError if the index is invalid.

Callbacks will be triggered if eventson is True.

class matplotlib.widgets.RectangleSelector(ax, onselect, drawtype='box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords='data', button=None, maxdist=10, marker_props=None, interactive=False, state_modifier_keys=None) [source]

Bases: matplotlib.widgets._SelectorWidget

Select a rectangular region of an axes.

For the cursor to remain responsive you must keep a reference to it.

Example usage:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RectangleSelector

def onselect(eclick, erelease):
    "eclick and erelease are matplotlib events at press and release."
    print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
    print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
    print('used button  : ', eclick.button)

def toggle_selector(event):
    print('Key pressed.')
    if event.key in ['Q', 'q'] and toggle_selector.RS.active:
        print('RectangleSelector deactivated.')
        toggle_selector.RS.set_active(False)
    if event.key in ['A', 'a'] and not toggle_selector.RS.active:
        print('RectangleSelector activated.')
        toggle_selector.RS.set_active(True)

x = np.arange(100.) / 99
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)

toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
fig.canvas.connect('key_press_event', toggle_selector)
plt.show()

Create a selector in ax. When a selection is made, clear the span and call onselect with:

onselect(pos_1, pos_2)

and clear the drawn box/line. The pos_1 and pos_2 are arrays of length 2 containing the x- and y-coordinate.

If minspanx is not None then events smaller than minspanx in x direction are ignored (it's the same for y).

The rectangle is drawn with rectprops; default:

rectprops = dict(facecolor='red', edgecolor = 'black',
                 alpha=0.2, fill=True)

The line is drawn with lineprops; default:

lineprops = dict(color='black', linestyle='-',
                 linewidth = 2, alpha=0.5)

Use drawtype if you want the mouse to draw a line, a box or nothing between click and actual position by setting

drawtype = 'line', drawtype='box' or drawtype = 'none'. Drawing a line would result in a line from vertex A to vertex C in a rectangle ABCD.

spancoords is one of 'data' or 'pixels'. If 'data', minspanx and minspanx will be interpreted in the same coordinates as the x and y axis. If 'pixels', they are in pixels.

button is a list of integers indicating which mouse buttons should be used for rectangle selection. You can also specify a single integer if only a single button is desired. Default is None, which does not limit which button can be used.

Note, typically:
1 = left mouse button 2 = center mouse button (scroll wheel) 3 = right mouse button

interactive will draw a set of handles and allow you interact with the widget after it is drawn.

state_modifier_keys are keyboard modifiers that affect the behavior of the widget.

The defaults are: dict(move=' ', clear='escape', square='shift', center='ctrl')

Keyboard modifiers, which: 'move': Move the existing shape. 'clear': Clear the current shape. 'square': Makes the shape square. 'center': Make the initial point the center of the shape. 'square' and 'center' can be combined.

center

Center of rectangle

corners

Corners of rectangle from lower left, moving clockwise.

draw_shape(extents) [source]
edge_centers

Midpoint of rectangle edges from left, moving clockwise.

extents

Return (xmin, xmax, ymin, ymax).

geometry

Returns numpy.ndarray of shape (2,5) containing x (RectangleSelector.geometry[1,:]) and y (RectangleSelector.geometry[0,:]) coordinates of the four corners of the rectangle starting and ending in the top left corner.

class matplotlib.widgets.Slider(ax, label, valmin, valmax, valinit=0.5, valfmt='%1.2f', closedmin=True, closedmax=True, slidermin=None, slidermax=None, dragging=True, valstep=None, **kwargs) [source]

Bases: matplotlib.widgets.AxesWidget

A slider representing a floating point range.

Create a slider from valmin to valmax in axes ax. For the slider to remain responsive you must maintain a reference to it. Call on_changed() to connect to the slider event.

Attributes:
val : float

Slider value.

Parameters:
ax : Axes

The Axes to put the slider in.

label : str

Slider label.

valmin : float

The minimum value of the slider.

valmax : float

The maximum value of the slider.

valinit : float, optional, default: 0.5

The slider initial position.

valfmt : str, optional, default: "%1.2f"

Used to format the slider value, fprint format string.

closedmin : bool, optional, default: True

Indicate whether the slider interval is closed on the bottom.

closedmax : bool, optional, default: True

Indicate whether the slider interval is closed on the top.

slidermin : Slider, optional, default: None

Do not allow the current slider to have a value less than the value of the Slider slidermin.

slidermax : Slider, optional, default: None

Do not allow the current slider to have a value greater than the value of the Slider slidermax.

dragging : bool, optional, default: True

If True the slider can be dragged by the mouse.

valstep : float, optional, default: None

If given, the slider will snap to multiples of valstep.

Notes

Additional kwargs are passed on to self.poly which is the Rectangle that draws the slider knob. See the Rectangle documentation for valid property names (e.g., facecolor, edgecolor, alpha).

disconnect(cid) [source]

Remove the observer with connection id cid

Parameters:
cid : int

Connection id of the observer to be removed

on_changed(func) [source]

When the slider value is changed call func with the new slider value

Parameters:
func : callable

Function to call when slider is changed. The function must accept a single float as its arguments.

Returns:
cid : int

Connection id (which can be used to disconnect func)

reset() [source]

Reset the slider to the initial value

set_val(val) [source]

Set slider value to val

Parameters:
val : float
class matplotlib.widgets.SpanSelector(ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None, span_stays=False, button=None) [source]

Bases: matplotlib.widgets._SelectorWidget

Visually select a min/max range on a single axis and call a function with those values.

To guarantee that the selector remains responsive, keep a reference to it.

In order to turn off the SpanSelector, set span_selector.active=False. To turn it back on, set span_selector.active=True.

Parameters:
ax : matplotlib.axes.Axes object
onselect : func(min, max), min/max are floats
direction : "horizontal" or "vertical"

The axis along which to draw the span selector

minspan : float, default is None

If selection is less than minspan, do not call onselect

useblit : bool, default is False

If True, use the backend-dependent blitting features for faster canvas updates.

rectprops : dict, default is None

Dictionary of matplotlib.patches.Patch properties

onmove_callback : func(min, max), min/max are floats, default is None

Called on mouse move while the span is being selected

span_stays : bool, default is False

If True, the span stays visible after the mouse is released

button : int or list of ints
Determines which mouse buttons activate the span selector

1 = left mouse button

2 = center mouse button (scroll wheel)

3 = right mouse button

Examples

>>> import matplotlib.pyplot as plt
>>> import matplotlib.widgets as mwidgets
>>> fig, ax = plt.subplots()
>>> ax.plot([1, 2, 3], [10, 50, 100])
>>> def onselect(vmin, vmax):
...     print(vmin, vmax)
>>> rectprops = dict(facecolor='blue', alpha=0.5)
>>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
...                              rectprops=rectprops)
>>> fig.show()

See also: Span Selector

ignore(event) [source]

return True if event should be ignored

new_axes(ax) [source]

Set SpanSelector to operate on a new Axes

class matplotlib.widgets.SubplotTool(targetfig, toolfig) [source]

Bases: matplotlib.widgets.Widget

A tool to adjust the subplot params of a matplotlib.figure.Figure.

targetfig
The figure instance to adjust.
toolfig
The figure instance to embed the subplot tool into. If None, a default figure will be created. If you are using this from the GUI
funcbottom(val) [source]
funchspace(val) [source]
funcleft(val) [source]
funcright(val) [source]
functop(val) [source]
funcwspace(val) [source]
class matplotlib.widgets.TextBox(ax, label, initial='', color='.95', hovercolor='1', label_pad=0.01) [source]

Bases: matplotlib.widgets.AxesWidget

A GUI neutral text input box.

For the text box to remain responsive you must keep a reference to it.

The following attributes are accessible:

ax
The matplotlib.axes.Axes the button renders into.
label
A matplotlib.text.Text instance.
color
The color of the text box when not hovering.
hovercolor
The color of the text box when hovering.

Call on_text_change() to be updated whenever the text changes.

Call on_submit() to be updated whenever the user hits enter or leaves the text entry field.

Parameters:
ax : matplotlib.axes.Axes

The matplotlib.axes.Axes instance the button will be placed into.

label : str

Label for this text box. Accepts string.

initial : str

Initial value in the text box

color : color

The color of the box

hovercolor : color

The color of the box when the mouse is over it

label_pad : float

the distance between the label and the right side of the textbox

begin_typing(x) [source]
disconnect(cid) [source]

Remove the observer with connection id cid.

on_submit(func) [source]

When the user hits enter or leaves the submission box, call this func with event.

A connection id is returned which can be used to disconnect.

on_text_change(func) [source]

When the text changes, call this func with event.

A connection id is returned which can be used to disconnect.

position_cursor(x) [source]
set_val(val) [source]
stop_typing() [source]
class matplotlib.widgets.ToolHandles(ax, x, y, marker='o', marker_props=None, useblit=True) [source]

Bases: object

Control handles for canvas tools.

Parameters:
ax : matplotlib.axes.Axes

Matplotlib axes where tool handles are displayed.

x, y : 1D arrays

Coordinates of control handles.

marker : str

Shape of marker used to display handle. See matplotlib.pyplot.plot.

marker_props : dict

Additional marker properties. See matplotlib.lines.Line2D.

closest(x, y) [source]

Return index and pixel distance to closest index.

set_animated(val) [source]
set_data(pts, y=None) [source]

Set x and y positions of handles

set_visible(val) [source]
x
y
class matplotlib.widgets.Widget [source]

Bases: object

Abstract base class for GUI neutral widgets

active

Is the widget active?

drawon = True
eventson = True
get_active() [source]

Get whether the widget is active.

ignore(event) [source]

Return True if event should be ignored.

This method (or a version of it) should be called at the beginning of any event callback.

set_active(active) [source]

Set whether the widget is active.

© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.0.0/api/widgets_api.html