Movatterモバイル変換


[0]ホーム

URL:


You are reading an old version of the documentation (v2.0.0). For the latest version seehttps://matplotlib.org/stable/api/widgets_api.html
matplotlib

Navigation


Travis-CI:

Table Of Contents

Related Topics

This Page

Quick search

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 amatplotlib.axes.Axesinstance and pass that as the first arg. 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)

Bases:matplotlib.widgets.Widget

Widget that is connected to a singleAxes.

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

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)

Connect callback with an event.

This should be used in lieu offigure.canvas.mpl_connect since thisfunction stores callback ids for later clean up.

disconnect_events()

Disconnect all events created by this widget.

classmatplotlib.widgets.Button(ax,label,image=None,color='0.85',hovercolor='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
Thematplotlib.axes.Axes the button renders into.
label
Amatplotlib.text.Text instance.
color
The color of the button when not hovering.
hovercolor
The color of the button when hovering.

Callon_clicked() to connect to the button

Parameters:

ax : matplotlib.axes.Axes

Thematplotlib.axes.Axes instance the buttonwill be placed into.

label : str

The button text. Accepts string.

image : array, mpl image, Pillow Image

The image to place in the button, if notNone.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)

remove the observer with connection idcid

on_clicked(func)

When the button is clicked, call thisfunc with event.

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

classmatplotlib.widgets.CheckButtons(ax,labels,actives)

Bases:matplotlib.widgets.AxesWidget

A GUI neutral radio button.

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

The following attributes are exposed

ax
Thematplotlib.axes.Axes instance the buttons arelocated in
labels
List ofmatplotlib.text.Text instances
lines
List of (line1, line2) tuples for the x’s in the check boxes.These lines exist for each box, but haveset_visible(False)when its box is not checked.
rectangles
List ofmatplotlib.patches.Rectangle instances

Connect to the CheckButtons with theon_clicked() method

Add check buttons tomatplotlib.axes.Axes instanceax

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 idcid

on_clicked(func)

When the button is clicked, callfunc with button label

A connection id is returned which can be used to disconnect

set_active(index)

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 ifindex is invalid.

Callbacks will be triggered ifeventson is True.

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

Bases:matplotlib.widgets.AxesWidget

A horizontal and vertical line that spans the axes and moves withthe pointer. You can turn off the hline or vline respectively withthe 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 thevisible attribute.

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

Add a cursor toax. Ifuseblit=True, use the backend-dependent blitting features for faster updates (GTKAggonly for now).lineprops is a dictionary of line properties.

(Source code,png,pdf)

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

clear the cursor

onmove(event)

on mouse motion draw the cursor if visible

classmatplotlib.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)

Bases:matplotlib.widgets.RectangleSelector

Select an elliptical region of an axes.

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

Example usage:

frommatplotlib.widgetsimportEllipseSelectorfrompylabimport*defonselect(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)deftoggle_selector(event):print(' Key pressed.')ifevent.keyin['Q','q']andtoggle_selector.ES.active:print(' EllipseSelector deactivated.')toggle_selector.RS.set_active(False)ifevent.keyin['A','a']andnottoggle_selector.ES.active:print(' EllipseSelector activated.')toggle_selector.ES.set_active(True)x=arange(100)/(99.0)y=sin(x)fig=figureax=subplot(111)ax.plot(x,y)toggle_selector.ES=EllipseSelector(ax,onselect,drawtype='line')connect('key_press_event',toggle_selector)show()

Create a selector inax. When a selection is made, clearthe span and call onselect with:

onselect(pos_1,pos_2)

and clear the drawn box/line. Thepos_1 andpos_2 arearrays of length 2 containing the x- and y-coordinate.

Ifminspanx is notNone then events smaller thanminspanxin x direction are ignored (it’s the same for y).

The rectangle is drawn withrectprops; default:

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

The line is drawn withlineprops; default:

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

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

drawtype='line',drawtype='box' ordrawtype='none'.

spancoords is one of ‘data’ or ‘pixels’. If ‘data’,minspanxandminspanx will be interpreted in the same coordinates asthe x and y axis. If ‘pixels’, they are in pixels.

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

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

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

state_modifier_keys are keyboard modifiers that affect the behaviorof 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)
classmatplotlib.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 withcontains_point() to select data pointsfrom an image.

UnlikeLassoSelector, this must be initialized with a startingpointxy, and theLasso 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, thecallback function is called andpassed the vertices of the selected path.
onmove(event)
onrelease(event)
classmatplotlib.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 must keep a reference toit.

The selected path can be used in conjunction withcontains_point() to selectdata points from an image.

In contrast toLasso,LassoSelector is written with an interfacesimilar toRectangleSelector andSpanSelector and willcontinue to interact with the axes until disconnected.

Parameters:

ax:Axes
The parent axes for the widget.
onselect:function
Whenever the lasso is released, theonselect function is called andpassed the vertices of the selected path.

Example usage:

ax=subplot(111)ax.plot(x,y)defonselect(verts):print(verts)lasso=LassoSelector(ax,onselect)*button*isalistofintegersindicatingwhichmousebuttonsshouldbeusedforrectangleselection.Youcanalsospecifyasingleintegerifonlyasinglebuttonisdesired.Defaultis*None*,whichdoesnotlimitwhichbuttoncanbeused.Note,typically:1=leftmousebutton2=centermousebutton(scrollwheel)3=rightmousebutton
onpress(event)
onrelease(event)
classmatplotlib.widgets.LockDraw

Bases:object

Some widgets, like the cursor, draw onto the canvas, and this is notdesirable under all circumstances, like when the toolbar is inzoom-to-rect mode and drawing a rectangle. The module level “lock”allows someone to grab the lock and prevent other widgets fromdrawing. Usematplotlib.widgets.lock(someobj) to preventother widgets from drawing while you’re interacting with the canvas.

available(o)

drawing is available too

isowner(o)

Return True ifo owns this lock

locked()

Return True if the lock is currently held by an owner

release(o)

release the lock

classmatplotlib.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 betweenmultiple axes.

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

Example usage:

frommatplotlib.widgetsimportMultiCursorfrompylabimportfigure,show,npt=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)
classmatplotlib.widgets.RadioButtons(ax,labels,active=0,activecolor='blue')

Bases:matplotlib.widgets.AxesWidget

A GUI neutral radio button.

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

The following attributes are exposed:

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

Connect to the RadioButtons with theon_clicked() method

Add radio buttons tomatplotlib.axes.Axes instanceax

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 idcid

on_clicked(func)

When the button is clicked, callfunc with button label

A connection id is returned which can be used to disconnect

set_active(index)

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 ifeventson is True.

classmatplotlib.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)

Bases:matplotlib.widgets._SelectorWidget

Select a rectangular region of an axes.

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

Example usage:

frommatplotlib.widgetsimportRectangleSelectorfrompylabimport*defonselect(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)deftoggle_selector(event):print(' Key pressed.')ifevent.keyin['Q','q']andtoggle_selector.RS.active:print(' RectangleSelector deactivated.')toggle_selector.RS.set_active(False)ifevent.keyin['A','a']andnottoggle_selector.RS.active:print(' RectangleSelector activated.')toggle_selector.RS.set_active(True)x=arange(100)/(99.0)y=sin(x)fig=figureax=subplot(111)ax.plot(x,y)toggle_selector.RS=RectangleSelector(ax,onselect,drawtype='line')connect('key_press_event',toggle_selector)show()

Create a selector inax. When a selection is made, clearthe span and call onselect with:

onselect(pos_1,pos_2)

and clear the drawn box/line. Thepos_1 andpos_2 arearrays of length 2 containing the x- and y-coordinate.

Ifminspanx is notNone then events smaller thanminspanxin x direction are ignored (it’s the same for y).

The rectangle is drawn withrectprops; default:

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

The line is drawn withlineprops; default:

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

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

drawtype='line',drawtype='box' ordrawtype='none'.

spancoords is one of ‘data’ or ‘pixels’. If ‘data’,minspanxandminspanx will be interpreted in the same coordinates asthe x and y axis. If ‘pixels’, they are in pixels.

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

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

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

state_modifier_keys are keyboard modifiers that affect the behaviorof 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)
edge_centers

Midpoint of rectangle edges from left, moving clockwise.

extents

Return (xmin, xmax, ymin, ymax).

geometry
classmatplotlib.widgets.Slider(ax,label,valmin,valmax,valinit=0.5,valfmt='%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 areference to it.

The following attributes are defined

ax : the slidermatplotlib.axes.Axes instance

val : the current slider value

vline:amatplotlib.lines.Line2D instance
representing the initial value of the slider
poly:Amatplotlib.patches.Polygon instance
which is the slider knob

valfmt : the format string for formatting the slider text

label:amatplotlib.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 notNone, this slider must be
greater thanslidermin
slidermax:another slider - if notNone, this slider must be
less thanslidermax

dragging : allow for mouse dragging on slider

Callon_changed() to connect to the slider event

Create a slider fromvalmin tovalmax in axesax.

Additional kwargs are passed on toself.poly which is thematplotlib.patches.Rectangle that draws the sliderknob. See thematplotlib.patches.Rectangle documentation forvalid 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 thanslidermin

slidermax : Slider or None

Do not allow the current slider to have a value greater thanslidermax

dragging : bool

if the slider can be dragged by the mouse

disconnect(cid)

remove the observer with connection idcid

on_changed(func)

When the slider value is changed, callfunc with the newslider 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)
classmatplotlib.widgets.SpanSelector(ax,onselect,direction,minspan=None,useblit=False,rectprops=None,onmove_callback=None,span_stays=False,button=None)

Bases:matplotlib.widgets._SelectorWidget

Visually 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 toit.

In order to turn off the SpanSelector, setspan_selector.active=False. Toturn it back on, setspan_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 thanminspan, do not callonselect

useblit : bool, default is False

If True, use the backend-dependent blitting features for fastercanvas updates. Only available for GTKAgg right now.

rectprops : dict, default is None

Dictionary ofmatplotlib.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

>>>importmatplotlib.pyplotasplt>>>importmatplotlib.widgetsasmwidgets>>>fig,ax=plt.subplots()>>>ax.plot([1,2,3],[10,50,100])>>>defonselect(vmin,vmax):        print(vmin, vmax)>>>rectprops=dict(facecolor='blue',alpha=0.5)>>>span=mwidgets.SpanSelector(ax,onselect,'horizontal',                                 rectprops=rectprops)>>>fig.show()

See also:widgets example code: span_selector.py

ignore(event)

returnTrue ifevent should be ignored

new_axes(ax)

Set SpanSelector to operate on a new Axes

classmatplotlib.widgets.SubplotTool(targetfig,toolfig)

Bases:matplotlib.widgets.Widget

A tool to adjust the subplot params of amatplotlib.figure.Figure.

targetfig
The figure instance to adjust.
toolfig
The figure instance to embed the subplot tool into. IfNone, a default figure will be created. If you are usingthis from the GUI
funcbottom(val)
funchspace(val)
funcleft(val)
funcright(val)
functop(val)
funcwspace(val)
classmatplotlib.widgets.ToolHandles(ax,x,y,marker='o',marker_props=None,useblit=True)

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. Seematplotlib.pyplot.plot.

marker_props : dict

Additional marker properties. Seematplotlib.lines.Line2D.

closest(x,y)

Return index and pixel distance to closest index.

set_animated(val)
set_data(pts,y=None)

Set x and y positions of handles

set_visible(val)
x
y
classmatplotlib.widgets.Widget

Bases:object

Abstract base class for GUI neutral widgets

active

Is the widget active?

drawon = True
eventson = True
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 beginningof any event callback.

set_active(active)

Set whether the widget is active.

© Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the Matplotlib development team; 2012 - 2016 The Matplotlib development team. Last updated on Feb 20, 2017. Created usingSphinx 1.5.2.

[8]ページ先頭

©2009-2025 Movatter.jp