matplotlib

Table Of Contents

Previous topic

units

Next topic

Matplotlib Examples

This Page

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 an 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)

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.
active

Is the widget active?

connect_event(event, callback)

Connect callback with an event.

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

disconnect_events()

Disconnect all events created by this widget.

get_active()

Get whether the widget is active.

ignore(event)

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)

Set whether the widget is active.

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

Bases: matplotlib.widgets.AxesWidget

A GUI neutral button.

For the button 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 button when not hovering.
hovercolor
The color of the button when hovering.

Call on_clicked() to connect to the button

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, PIL image

The image to place in the button, if not None. Can be any legal arg to imshow (numpy array, matplotlib Image instance, or PIL 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)

remove the observer with connection id cid

on_clicked(func)

When the button is clicked, call this func with event

A connection id is returned which can be used to disconnect

class matplotlib.widgets.CheckButtons(ax, labels, actives)

Bases: matplotlib.widgets.AxesWidget

A GUI neutral radio button.

For the check buttons to remain responsive you much 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

labels
A len(buttons) list of labels as strings
actives
A len(buttons) list of booleans indicating whether
the button is active
disconnect(cid)

remove the observer with connection id cid

on_clicked(func)

When the button is clicked, call func with button label

A connection id is returned which can be used to disconnect

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

Bases: matplotlib.widgets.AxesWidget

A horizontal and vertical line span the axes that and move with the pointer. You can turn off the hline or vline spectively with the 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 much keep a reference to it.

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

(Source code, png)

../_images/cursor.png
clear(event)

clear the cursor

onmove(event)

on mouse motion draw the cursor if visible

class matplotlib.widgets.Lasso(ax, xy, callback=None, useblit=True)

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 : function
Whenever the lasso is released, the callback function is called and passed the vertices of the selected path.
onmove(event)
onrelease(event)
class matplotlib.widgets.LassoSelector(ax, onselect=None, useblit=True, lineprops=None, button=None)

Bases: matplotlib.widgets._SelectorWidget

Selection curve of an arbitrary shape.

For the selector to remain responsive you much 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.

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.

Example usage:

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

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

*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
onmove(event)
onpress(event)
onrelease(event)
press(event)
release(event)
class matplotlib.widgets.LockDraw

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. The module level “lock” allows someone to grab the lock and prevent other widgets from drawing. Use matplotlib.widgets.lock(someobj) to pr

available(o)

drawing is available to o

isowner(o)

Return True if o owns this lock

locked()

Return True if the lock is currently held by an owner

release(o)

release the lock

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

Bases: matplotlib.widgets.Widget

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

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

Example usage:

from matplotlib.widgets import MultiCursor
from pylab import figure, show, np

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
fig = figure()
ax1 = fig.add_subplot(211)
ax1.plot(t, s1)

ax2 = fig.add_subplot(212, sharex=ax1)
ax2.plot(t, s2)

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

clear the cursor

connect()

connect events

disconnect()

disconnect events

onmove(event)
class matplotlib.widgets.RadioButtons(ax, labels, active=0, activecolor=u'blue')

Bases: matplotlib.widgets.AxesWidget

A GUI neutral radio button

For the buttons to remain responsive you much 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)

remove the observer with connection id cid

on_clicked(func)

When the button is clicked, call func with button label

A connection id is returned which can be used to disconnect

class matplotlib.widgets.RectangleSelector(ax, onselect, drawtype=u'box', minspanx=None, minspany=None, useblit=False, lineprops=None, rectprops=None, spancoords=u'data', button=None)

Bases: matplotlib.widgets._SelectorWidget

Select a rectangular region of an axes.

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

Example usage:

from matplotlib.widgets import  RectangleSelector
from pylab import *

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 = arange(100)/(99.0)
y = sin(x)
fig = figure
ax = subplot(111)
ax.plot(x,y)

toggle_selector.RS = RectangleSelector(ax, onselect, drawtype='line')
connect('key_press_event', toggle_selector)
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.5, fill=False)

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'.

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
onmove(event)

on motion notify event if box/line is wanted

press(event)

on button press event

release(event)

on button release event

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

Bases: matplotlib.widgets.AxesWidget

A slider representing a floating point range.

For the slider to remain responsive you must maintain a reference to it.

The following attributes are defined

ax : the slider matplotlib.axes.Axes instance

val : the current slider value

vline : a matplotlib.lines.Line2D instance
representing the initial value of the slider
poly : A matplotlib.patches.Polygon instance
which is the slider knob

valfmt : the format string for formatting the slider text

label : a matplotlib.text.Text instance
for the slider label

closedmin : whether the slider is closed on the minimum

closedmax : whether the slider is closed on the maximum

slidermin : another slider - if not None, this slider must be
greater than slidermin
slidermax : another slider - if not None, this slider must be
less than slidermax

dragging : allow for mouse dragging on slider

Call on_changed() to connect to the slider event

Create a slider from valmin to valmax in axes ax.

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

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

The slider initial position

label : str

The slider label

valfmt : str

Used to format the slider value, fprint format string

closedmin : bool

Indicate whether the slider interval is closed on the bottom

closedmax : bool

Indicate whether the slider interval is closed on the top

slidermin : Slider or None

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

slidermax : Slider or None

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

dragging : bool

if the slider can be dragged by the mouse

disconnect(cid)

remove the observer with connection id cid

on_changed(func)

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

A connection id is returned which can be used to disconnect

reset()

reset the slider to the initial value if needed

set_val(val)
class matplotlib.widgets.SpanSelector(ax, onselect, direction, minspan=None, useblit=False, rectprops=None, onmove_callback=None, span_stays=False, button=None)

Bases: matplotlib.widgets._SelectorWidget

Select a min/max range of the x or y axes for a matplotlib Axes.

For the selector to remain responsive you much keep a reference to it.

Example usage:

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

def onselect(vmin, vmax):
    print vmin, vmax
span = SpanSelector(ax, onselect, 'horizontal')

onmove_callback is an optional callback that is called on mouse move within the span range

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

onselect(vmin, vmax)

and clear the span.

direction must be ‘horizontal’ or ‘vertical’

If minspan is not None, ignore events smaller than minspan

The span rectangle is drawn with rectprops; default:

rectprops = dict(facecolor='red', alpha=0.5)

Set the visible attribute to False if you want to turn off the functionality of the span selector

If span_stays is True, the span stays visble after making a valid selection.

button is a list of integers indicating which mouse buttons should be used for 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
ignore(event)

return True if event should be ignored

new_axes(ax)
onmove(event)

on motion notify event

press(event)

on button press event

release(event)

on button release event

class matplotlib.widgets.SubplotTool(targetfig, toolfig)

Bases: matplotlib.widgets.Widget

A tool to adjust to 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)
funchspace(val)
funcleft(val)
funcright(val)
functop(val)
funcwspace(val)
class matplotlib.widgets.Widget

Bases: object

Abstract base class for GUI neutral widgets

drawon = True
eventson = True