matplotlib.backend_bases
Abstract base classes define the primitives that renderers and
graphics contexts must implement to serve as a matplotlib backend
- RendererBase
- An abstract base class to handle drawing/rendering operations.
- FigureCanvasBase
- The abstraction layer that separates the
matplotlib.figure.Figure from the backend specific
details like a user interface drawing area
- GraphicsContextBase
- An abstract base class that provides color, line styles, etc...
- Event
- The base class for all of the matplotlib event
handling. Derived classes suh as KeyEvent and
MouseEvent store the meta data like keys and buttons
pressed, x and y locations in pixel and
Axes coordinates.
-
class matplotlib.backend_bases.Cursors
-
class matplotlib.backend_bases.DrawEvent(name, canvas, renderer)
Bases: matplotlib.backend_bases.Event
An event triggered by a draw operation on the canvas
In addition to the Event attributes, the following event attributes are defined:
- renderer
- the RendererBase instance for the draw event
-
class matplotlib.backend_bases.Event(name, canvas, guiEvent=None)
A matplotlib event. Attach additional attributes as defined in
FigureCanvasBase.mpl_connect(). The following attributes
are defined and shown with their default values
- name
- the event name
- canvas
- the FigureCanvas instance generating the event
- guiEvent
- the GUI event that triggered the matplotlib event
-
class matplotlib.backend_bases.FigureCanvasBase(figure)
The canvas the figure renders into.
Public attributes
- figure
- A matplotlib.figure.Figure instance
-
blit(bbox=None)
- blit the canvas in bbox (default entire canvas)
-
button_press_event(x, y, button, guiEvent=None)
Backend derived classes should call this function on any mouse
button press. x,y are the canvas coords: 0,0 is lower, left.
button and key are as defined in MouseEvent.
This method will be call all functions connected to the
‘button_press_event’ with a MouseEvent instance.
-
button_release_event(x, y, button, guiEvent=None)
Backend derived classes should call this function on any mouse
button release.
- x
- the canvas coordinates where 0=left
- y
- the canvas coordinates where 0=bottom
- guiEvent
- the native UI event that generated the mpl event
This method will be call all functions connected to the
‘button_release_event’ with a MouseEvent instance.
-
draw(*args, **kwargs)
- Render the Figure
-
draw_cursor(event)
- Draw a cursor in the event.axes if inaxes is not None. Use
native GUI drawing for efficiency if possible
-
draw_event(renderer)
- This method will be call all functions connected to the
‘draw_event’ with a DrawEvent
-
draw_idle(*args, **kwargs)
- draw() only if idle; defaults to draw but backends can overrride
-
enter_notify_event(guiEvent=None)
Backend derived classes should call this function when entering
canvas
- guiEvent
- the native UI event that generated the mpl event
-
flush_events()
- Flush the GUI events for the figure. Implemented only for
backends with GUIs.
-
get_default_filetype()
-
get_supported_filetypes()
-
get_supported_filetypes_grouped()
-
get_width_height()
- return the figure width and height in points or pixels
(depending on the backend), truncated to integers
-
idle_event(guiEvent=None)
- call when GUI is idle
-
key_press_event(key, guiEvent=None)
- This method will be call all functions connected to the
‘key_press_event’ with a KeyEvent
-
key_release_event(key, guiEvent=None)
- This method will be call all functions connected to the
‘key_release_event’ with a KeyEvent
-
leave_notify_event(guiEvent=None)
Backend derived classes should call this function when leaving
canvas
- guiEvent
- the native UI event that generated the mpl event
-
motion_notify_event(x, y, guiEvent=None)
Backend derived classes should call this function on any
motion-notify-event.
- x
- the canvas coordinates where 0=left
- y
- the canvas coordinates where 0=bottom
- guiEvent
- the native UI event that generated the mpl event
This method will be call all functions connected to the
‘motion_notify_event’ with a MouseEvent instance.
-
mpl_connect(s, func)
Connect event with string s to func. The signature of func is:
where event is a matplotlib.backend_bases.Event. The
following events are recognized
- ‘button_press_event’
- ‘button_release_event’
- ‘draw_event’
- ‘key_press_event’
- ‘key_release_event’
- ‘motion_notify_event’
- ‘pick_event’
- ‘resize_event’
- ‘scroll_event’
- ‘figure_enter_event’,
- ‘figure_leave_event’,
- ‘axes_enter_event’,
- ‘axes_leave_event’
For the location events (button and key press/release), if the
mouse is over the axes, the variable event.inaxes will be
set to the Axes the event occurs is
over, and additionally, the variables event.xdata and
event.ydata will be defined. This is the mouse location
in data coords. See
KeyEvent and
MouseEvent for more info.
Return value is a connection id that can be used with
mpl_disconnect().
Example usage:
def on_press(event):
print 'you pressed', event.button, event.xdata, event.ydata
cid = canvas.mpl_connect('button_press_event', on_press)
-
mpl_disconnect(cid)
disconnect callback id cid
Example usage:
cid = canvas.mpl_connect('button_press_event', on_press)
#...later
canvas.mpl_disconnect(cid)
-
onHilite(ev)
Mouse event processor which highlights the artists
under the cursor. Connect this to the ‘motion_notify_event’
using:
canvas.mpl_connect('motion_notify_event',canvas.onHilite)
-
onRemove(ev)
Mouse event processor which removes the top artist
under the cursor. Connect this to the ‘mouse_press_event’
using:
canvas.mpl_connect('mouse_press_event',canvas.onRemove)
-
pick(mouseevent)
-
pick_event(mouseevent, artist, **kwargs)
- This method will be called by artists who are picked and will
fire off PickEvent callbacks registered listeners
-
print_bmp(*args, **kwargs)
-
print_emf(*args, **kwargs)
-
print_eps(*args, **kwargs)
-
print_figure(filename, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', format=None, **kwargs)
Render the figure to hardcopy. Set the figure patch face and edge
colors. This is useful because some of the GUIs have a gray figure
face color background and you’ll probably want to override this on
hardcopy.
Arguments are:
- filename
- can also be a file object on image backends
- orientation
- only currently applies to PostScript printing.
- dpi
- the dots per inch to save the figure in; if None, use savefig.dpi
- facecolor
- the facecolor of the figure
- edgecolor
- the edgecolor of the figure
- orientation ‘
- landscape’ | ‘portrait’ (not supported on all backends)
- format
- when set, forcibly set the file format to save to
-
print_pdf(*args, **kwargs)
-
print_png(*args, **kwargs)
-
print_ps(*args, **kwargs)
-
print_raw(*args, **kwargs)
-
print_rgb(*args, **kwargs)
-
print_svg(*args, **kwargs)
-
print_svgz(*args, **kwargs)
-
resize(w, h)
- set the canvas size in pixels
-
resize_event()
- This method will be call all functions connected to the
‘resize_event’ with a ResizeEvent
-
scroll_event(x, y, step, guiEvent=None)
Backend derived classes should call this function on any
scroll wheel event. x,y are the canvas coords: 0,0 is lower,
left. button and key are as defined in MouseEvent.
This method will be call all functions connected to the
‘scroll_event’ with a MouseEvent instance.
-
set_window_title(title)
- Set the title text of the window containing the figure. Note that
this has no effect if there is no window (eg, a PS backend).
-
start_event_loop(timeout)
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
This is implemented only for backends with GUIs.
-
start_event_loop_default(timeout=0)
Start an event loop. This is used to start a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events. This should not be
confused with the main GUI event loop, which is always running
and has nothing to do with this.
This function provides default event loop functionality based
on time.sleep that is meant to be used until event loop
functions for each of the GUI backends can be written. As
such, it throws a deprecated warning.
Call signature:
start_event_loop_default(self,timeout=0)
This call blocks until a callback function triggers
stop_event_loop() or timeout is reached. If timeout is
<=0, never timeout.
-
stop_event_loop()
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
This is implemented only for backends with GUIs.
-
stop_event_loop_default()
Stop an event loop. This is used to stop a blocking event
loop so that interactive functions, such as ginput and
waitforbuttonpress, can wait for events.
Call signature:
stop_event_loop_default(self)
-
switch_backends(FigureCanvasClass)
instantiate an instance of FigureCanvasClass
This is used for backend switching, eg, to instantiate a
FigureCanvasPS from a FigureCanvasGTK. Note, deep copying is
not done, so any changes to one of the instances (eg, setting
figure size or line props), will be reflected in the other
-
class matplotlib.backend_bases.FigureManagerBase(canvas, num)
Helper class for matlab mode, wraps everything up into a neat bundle
Public attibutes:
- canvas
- A FigureCanvasBase instance
- num
- The figure nuamber
-
destroy()
-
full_screen_toggle()
-
key_press(event)
-
resize(w, h)
- For gui backends: resize window in pixels
-
set_window_title(title)
- Set the title text of the window containing the figure. Note that
this has no effect if there is no window (eg, a PS backend).
- Display message in a popup – GUI only
-
class matplotlib.backend_bases.GraphicsContextBase
An abstract base class that provides color, line styles, etc...
-
copy_properties(gc)
- Copy properties from gc to self
-
get_alpha()
- Return the alpha value used for blending - not supported on
all backends
-
get_antialiased()
- Return true if the object should try to do antialiased rendering
-
get_capstyle()
- Return the capstyle as a string in (‘butt’, ‘round’, ‘projecting’)
-
get_clip_path()
- Return the clip path in the form (path, transform), where path
is a Path instance, and transform is
an affine transform to apply to the path before clipping.
-
get_clip_rectangle()
- Return the clip rectangle as a Bbox instance
-
get_dashes()
Return the dash information as an offset dashlist tuple.
The dash list is a even size list that gives the ink on, ink
off in pixels.
See p107 of to PostScript BLUEBOOK
for more info.
Default value is None
-
get_hatch()
- Gets the current hatch style
-
get_hatch_path(density=6.0)
- Returns a Path for the current hatch.
-
get_joinstyle()
- Return the line join style as one of (‘miter’, ‘round’, ‘bevel’)
-
get_linestyle(style)
- Return the linestyle: one of (‘solid’, ‘dashed’, ‘dashdot’,
‘dotted’).
-
get_linewidth()
- Return the line width in points as a scalar
-
get_rgb()
- returns a tuple of three floats from 0-1. color can be a
matlab format string, a html hex color string, or a rgb tuple
-
get_snap()
returns the snap setting which may be:
- True: snap vertices to the nearest pixel center
- False: leave vertices as-is
- None: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center
-
get_url()
- returns a url if one is set, None otherwise
-
restore()
- Restore the graphics context from the stack - needed only
for backends that save graphics contexts on a stack
-
set_alpha(alpha)
- Set the alpha value used for blending - not supported on
all backends
-
set_antialiased(b)
- True if object should be drawn with antialiased rendering
-
set_capstyle(cs)
- Set the capstyle as a string in (‘butt’, ‘round’, ‘projecting’)
-
set_clip_path(path)
- Set the clip path and transformation. Path should be a
TransformedPath instance.
-
set_clip_rectangle(rectangle)
- Set the clip rectangle with sequence (left, bottom, width, height)
-
set_dashes(dash_offset, dash_list)
Set the dash style for the gc.
- dash_offset
- is the offset (usually 0).
- dash_list
- specifies the on-off sequence as points. (None, None) specifies a solid line
-
set_foreground(fg, isRGB=False)
Set the foreground color. fg can be a matlab format string, a
html hex color string, an rgb unit tuple, or a float between 0
and 1. In the latter case, grayscale is used.
The GraphicsContextBase converts colors to rgb
internally. If you know the color is rgb already, you can set
isRGB=True to avoid the performace hit of the conversion
-
set_graylevel(frac)
- Set the foreground color to be a gray level with frac
-
set_hatch(hatch)
- Sets the hatch style for filling
-
set_joinstyle(js)
- Set the join style to be one of (‘miter’, ‘round’, ‘bevel’)
-
set_linestyle(style)
- Set the linestyle to be one of (‘solid’, ‘dashed’, ‘dashdot’,
‘dotted’).
-
set_linewidth(w)
- Set the linewidth in points
-
set_snap(snap)
Sets the snap setting which may be:
- True: snap vertices to the nearest pixel center
- False: leave vertices as-is
- None: (auto) If the path contains only rectilinear line
segments, round to the nearest pixel center
-
set_url(url)
- Sets the url for links in compatible backends
-
class matplotlib.backend_bases.IdleEvent(name, canvas, guiEvent=None)
Bases: matplotlib.backend_bases.Event
An event triggered by the GUI backend when it is idle – useful
for passive animation
-
class matplotlib.backend_bases.KeyEvent(name, canvas, key, x=0, y=0, guiEvent=None)
Bases: matplotlib.backend_bases.LocationEvent
A key event (key press, key release).
Attach additional attributes as defined in
FigureCanvasBase.mpl_connect().
In addition to the Event and LocationEvent
attributes, the following attributes are defined:
- key
- the key pressed: None, chr(range(255), shift, win, or control
This interface may change slightly when better support for
modifier keys is included.
Example usage:
def on_key(event):
print 'you pressed', event.key, event.xdata, event.ydata
cid = fig.canvas.mpl_connect('key_press_event', on_key)
-
class matplotlib.backend_bases.LocationEvent(name, canvas, x, y, guiEvent=None)
Bases: matplotlib.backend_bases.Event
A event that has a screen location
The following additional attributes are defined and shown with
their default values
In addition to the Event attributes, the following event attributes are defined:
- x
- x position - pixels from left of canvas
- y
- y position - pixels from bottom of canvas
- inaxes
- the Axes instance if mouse is over axes
- xdata
- x coord of mouse in data coords
- ydata
- y coord of mouse in data coords
x, y in figure coords, 0,0 = bottom, left
-
class matplotlib.backend_bases.MouseEvent(name, canvas, x, y, button=None, key=None, step=0, guiEvent=None)
Bases: matplotlib.backend_bases.LocationEvent
A mouse event (‘button_press_event’, ‘button_release_event’, ‘scroll_event’,
‘motion_notify_event’).
In addition to the Event and LocationEvent
attributes, the following attributes are defined:
- button
- button pressed None, 1, 2, 3, ‘up’, ‘down’ (up and down are used for scroll events)
- key
- the key pressed: None, chr(range(255), ‘shift’, ‘win’, or ‘control’
- step
- number of scroll steps (positive for ‘up’, negative for ‘down’)
Example usage:
def on_press(event):
print 'you pressed', event.button, event.xdata, event.ydata
cid = fig.canvas.mpl_connect('button_press_event', on_press)
x, y in figure coords, 0,0 = bottom, left
button pressed None, 1, 2, 3, ‘up’, ‘down’
-
class matplotlib.backend_bases.NavigationToolbar2(canvas)
Base class for the navigation cursor, version 2
backends must implement a canvas that handles connections for
‘button_press_event’ and ‘button_release_event’. See
FigureCanvasBase.mpl_connect() for more information
They must also define
- save_figure()
- save the current figure
- set_cursor()
- if you want the pointer icon to change
- _init_toolbar()
- create your toolbar widget
- draw_rubberband() (optional)
- draw the zoom to rect “rubberband” rectangle
- press() (optional)
- whenever a mouse button is pressed, you’ll be notified with
the event
- release() (optional)
- whenever a mouse button is released, you’ll be notified with
the event
- dynamic_update() (optional)
- dynamically update the window while navigating
- set_message() (optional)
- display message
- set_history_buttons() (optional)
- you can change the history back / forward buttons to
indicate disabled / enabled state.
That’s it, we’ll do the rest!
-
back(*args)
- move back up the view lim stack
-
drag_pan(event)
- the drag callback in pan/zoom mode
-
draw()
- redraw the canvases, update the locators
-
draw_rubberband(event, x0, y0, x1, y1)
- draw a rectangle rubberband to indicate zoom limits
-
dynamic_update()
-
forward(*args)
- move forward in the view lim stack
-
home(*args)
- restore the original view
-
mouse_move(event)
-
pan(*args)
- Activate the pan/zoom tool. pan with left button, zoom with right
-
press(event)
- this will be called whenver a mouse button is pressed
-
press_pan(event)
- the press mouse button in pan/zoom mode callback
-
press_zoom(event)
- the press mouse button in zoom to rect mode callback
-
push_current()
- push the current view limits and position onto the stack
-
release(event)
- this will be called whenever mouse button is released
-
release_pan(event)
- the release mouse button callback in pan/zoom mode
-
release_zoom(event)
- the release mouse button callback in zoom to rect mode
-
save_figure(*args)
- save the current figure
-
set_cursor(cursor)
- Set the current cursor to one of the Cursors
enums values
-
set_history_buttons()
- enable or disable back/forward button
-
set_message(s)
- display a message on toolbar or in status bar
-
update()
- reset the axes stack
-
zoom(*args)
- activate zoom to rect mode
-
class matplotlib.backend_bases.PickEvent(name, canvas, mouseevent, artist, guiEvent=None, **kwargs)
Bases: matplotlib.backend_bases.Event
a pick event, fired when the user picks a location on the canvas
sufficiently close to an artist.
Attrs: all the Event attributes plus
- mouseevent
- the MouseEvent that generated the pick
- artist
- the Artist picked
- other
- extra class dependent attrs – eg a
Line2D pick may define different
extra attributes than a
PatchCollection pick event
Example usage:
line, = ax.plot(rand(100), 'o', picker=5) # 5 points tolerance
def on_pick(event):
thisline = event.artist
xdata, ydata = thisline.get_data()
ind = event.ind
print 'on pick line:', zip(xdata[ind], ydata[ind])
cid = fig.canvas.mpl_connect('pick_event', on_pick)
-
class matplotlib.backend_bases.RendererBase
An abstract base class to handle drawing/rendering operations.
The following methods must be implemented in the backend:
The following methods should be implemented in the backend for
optimization reasons:
-
close_group(s)
- Close a grouping element with label s
Is only currently used by backend_svg
-
draw_image(x, y, im, bbox, clippath=None, clippath_trans=None)
Draw the image instance into the current axes;
- x
- is the distance in pixels from the left hand side of the canvas.
- y
- the distance from the origin. That is, if origin is
upper, y is the distance from top. If origin is lower, y
is the distance from bottom
- im
- the matplotlib._image.Image instance
- bbox
- a matplotlib.transforms.Bbox instance for clipping, or
None
-
draw_markers(gc, marker_path, marker_trans, path, trans, rgbFace=None)
Draws a marker at each of the vertices in path. This includes
all vertices, including control points on curves. To avoid
that behavior, those vertices should be removed before calling
this function.
- gc
- the GraphicsContextBase instance
- marker_trans
- is an affine transform applied to the marker.
- trans
- is an affine transform applied to the path.
This provides a fallback implementation of draw_markers that
makes multiple calls to draw_path(). Some backends may
want to override this method in order to draw the marker only
once and reuse it multiple times.
-
draw_path(gc, path, transform, rgbFace=None)
- Draws a Path instance using the
given affine transform.
-
draw_path_collection(master_transform, cliprect, clippath, clippath_trans, paths, all_transforms, offsets, offsetTrans, facecolors, edgecolors, linewidths, linestyles, antialiaseds, urls)
Draws a collection of paths, selecting drawing properties from
the lists facecolors, edgecolors, linewidths,
linestyles and antialiaseds. offsets is a list of
offsets to apply to each of the paths. The offsets in
offsets are first transformed by offsetTrans before
being applied.
This provides a fallback implementation of
draw_path_collection() that makes multiple calls to
draw_path. Some backends may want to override this in order
to render each set of path data only once, and then reference
that path multiple times with the different offsets, colors,
styles etc. The generator methods
_iter_collection_raw_paths() and
_iter_collection() are provided to help with (and
standardize) the implementation across backends. It is highly
recommended to use those generators, so that changes to the
behavior of draw_path_collection() can be made globally.
-
draw_quad_mesh(master_transform, cliprect, clippath, clippath_trans, meshWidth, meshHeight, coordinates, offsets, offsetTrans, facecolors, antialiased, showedges)
- This provides a fallback implementation of
draw_quad_mesh() that generates paths and then calls
draw_path_collection().
-
draw_tex(gc, x, y, s, prop, angle, ismath='TeX!')
-
draw_text(gc, x, y, s, prop, angle, ismath=False)
Draw the text instance
- gc
- the GraphicsContextBase instance
- x
- the x location of the text in display coords
- y
- the y location of the text in display coords
- s
- a matplotlib.text.Text instance
- prop
- a matplotlib.font_manager.FontProperties instance
- angle
- the rotation angle in degrees
backend implementers note
When you are trying to determine if you have gotten your bounding box
right (which is what enables the text layout/alignment to work
properly), it helps to change the line in text.py:
if 0: bbox_artist(self, renderer)
to if 1, and then the actual bounding box will be blotted along with
your text.
-
flipy()
- Return true if y small numbers are top for renderer Is used
for drawing text (matplotlib.text) and images
(matplotlib.image) only
-
get_canvas_width_height()
- return the canvas width and height in display coords
-
get_image_magnification()
- Get the factor by which to magnify images passed to draw_image().
Allows a backend to have images at a different resolution to other
artists.
-
get_texmanager()
- return the matplotlib.texmanager.TexManager instance
-
get_text_width_height_descent(s, prop, ismath)
- get the width and height, and the offset from the bottom to the
baseline (descent), in display coords of the string s with
FontProperties prop
-
new_gc()
- Return an instance of a GraphicsContextBase
-
open_group(s, gid=None)
- Open a grouping element with label s. If gid is given, use
gid as the id of the group. Is only currently used by
backend_svg.
-
option_image_nocomposite()
- overwrite this method for renderers that do not necessarily
want to rescale and composite raster images. (like SVG)
-
points_to_pixels(points)
Convert points to display units
- points
- a float or a numpy array of float
return points converted to pixels
You need to override this function (unless your backend
doesn’t have a dpi, eg, postscript or svg). Some imaging
systems assume some value for pixels per inch:
points to pixels = points * pixels_per_inch/72.0 * dpi/72.0
-
start_rasterizing()
-
stop_rasterizing()
-
strip_math(s)
-
class matplotlib.backend_bases.ResizeEvent(name, canvas)
Bases: matplotlib.backend_bases.Event
An event triggered by a canvas resize
In addition to the Event attributes, the following event attributes are defined:
- width
- width of the canvas in pixels
- height
- height of the canvas in pixels