matplotlib.figure.Figure

class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None) [source]

Bases: matplotlib.artist.Artist

The top level container for all the plot elements.

The Figure instance supports callbacks through a callbacks attribute which is a CallbackRegistry instance. The events you can connect to are 'dpi_changed', and the callback will be called with func(fig) where fig is the Figure instance.

Attributes:
patch

The Rectangle instance representing the figure background patch.

suppressComposite

For multiple figure images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is a boolean, this will override the renderer.

Parameters:
figsize2-tuple of floats, default: rcParams["figure.figsize"] (default: [6.4, 4.8])

Figure dimension (width, height) in inches.

dpifloat, default: rcParams["figure.dpi"] (default: 100.0)

Dots per inch.

facecolordefault: rcParams["figure.facecolor"] (default: 'white')

The figure patch facecolor.

edgecolordefault: rcParams["figure.edgecolor"] (default: 'white')

The figure patch edge color.

linewidthfloat

The linewidth of the frame (i.e. the edge linewidth of the figure patch).

frameonbool, default: rcParams["figure.frameon"] (default: True)

If False, suppress drawing the figure background patch.

subplotparsSubplotParams

Subplot parameters. If not given, the default subplot parameters rcParams["figure.subplot.*"] are used.

tight_layoutbool or dict, default: rcParams["figure.autolayout"] (default: False)

If False use subplotpars. If True adjust subplot parameters using tight_layout with default padding. When providing a dict containing the keys pad, w_pad, h_pad, and rect, the default tight_layout paddings will be overridden.

constrained_layoutbool

If True use constrained layout to adjust positioning of plot elements. Like tight_layout, but designed to be more flexible. See Constrained Layout Guide for examples. (Note: does not work with subplot() or subplot2grid().) Defaults to rcParams["figure.constrained_layout.use"] (default: False).

add_artist(self, artist, clip=False) [source]

Add any Artist to the figure.

Usually artists are added to axes objects using matplotlib.axes.Axes.add_artist(), but use this method in the rare cases that adding directly to the figure is necessary.

Parameters:
artistArtist

The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to figure.transFigure.

clipbool, optional, default False

An optional parameter clip determines whether the added artist should be clipped by the figure patch. Default is False, i.e. no clipping.

Returns:
artistThe added Artist
add_axes(self, *args, **kwargs) [source]

Add an axes to the figure.

Call signatures:

add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters:
rectsequence of float

The dimensions [left, bottom, width, height] of the new axes. All quantities are in fractions of figure width and height.

projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional

The projection type of the Axes. str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.

polarboolean, optional

If True, equivalent to projection='polar'.

sharex, shareyAxes, optional

Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.

labelstr

A label for the returned axes.

Returns:
axesAxes (or a subclass of Axes)

The returned axes class depends on the projection used. It is Axes if rectilinear projection are used and projections.polar.PolarAxes if polar projection are used.

Other Parameters:
**kwargs

This method also takes the keyword arguments for the returned axes class. The keyword arguments for the rectilinear axes class Axes can be found in the following table but there might also be other keyword arguments if another projection is used, see the actual axes class.

Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
anchor 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
animated bool
aspect {'auto', 'equal'} or num
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
contains callable
facecolor color
fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...}
xticklabels List[str]
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...}
yticklabels List[str]
yticks unknown
zorder float

Notes

If the figure already has an axes with key (args, kwargs) then it will simply make that axes current and return it. This behavior is deprecated. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new axes), you must use a unique set of args and kwargs. The axes label attribute has been exposed for this purpose: if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels.

In rare circumstances, add_axes may be called with a single argument, a axes instance already created in the present figure but not in the figure's list of axes.

Examples

Some simple examples:

rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect, label=label1)
fig.add_axes(rect, label=label2)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
add_axobserver(self, func) [source]

Whenever the axes state change, func(self) will be called.

add_gridspec(self, nrows, ncols, **kwargs) [source]

Return a GridSpec that has this figure as a parent. This allows complex layout of axes in the figure.

Parameters:
nrowsint

Number of rows in grid.

ncolsint

Number or columns in grid.

Returns:
gridspecGridSpec
Other Parameters:
**kwargs

Keyword arguments are passed to GridSpec.

Examples

Adding a subplot that spans two rows:

fig = plt.figure()
gs = fig.add_gridspec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0])
# spans two rows:
ax3 = fig.add_subplot(gs[:, 1])
add_subplot(self, *args, **kwargs) [source]

Add an Axes to the figure as part of a subplot arrangement.

Call signatures:

add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
Parameters:
*args

Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows rows and ncols columns. index starts at 1 in the upper left corner and increases to the right.

pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.

If no positional arguments are passed, defaults to (1, 1, 1).

In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.

projection{None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional

The projection type of the subplot (Axes). str is the name of a custom projection, see projections. The default None results in a 'rectilinear' projection.

polarboolean, optional

If True, equivalent to projection='polar'.

sharex, shareyAxes, optional

Share the x or y axis with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.

labelstr

A label for the returned axes.

Returns:
axesaxes.SubplotBase, or another subclass of Axes

The axes of the subplot. The returned axes base class depends on the projection used. It is Axes if rectilinear projection are used and projections.polar.PolarAxes if polar projection are used. The returned axes is then a subplot subclass of the base class.

Other Parameters:
**kwargs

This method also takes the keyword arguments for the returned axes base class; except for the figure argument. The keyword arguments for the rectilinear base class Axes can be found in the following table but there might also be other keyword arguments if another projection is used.

Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
anchor 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
animated bool
aspect {'auto', 'equal'} or num
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
contains callable
facecolor color
fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...}
xticklabels List[str]
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...}
yticklabels List[str]
yticks unknown
zorder float

Notes

If the figure already has a subplot with key (args, kwargs) then it will simply make that subplot current and return it. This behavior is deprecated. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new subplot), you must use a unique set of args and kwargs. The axes label attribute has been exposed for this purpose: if you want two subplots that are otherwise identical to be added to the figure, make sure you give them unique labels.

Examples

fig = plt.figure()
fig.add_subplot(221)

# equivalent but more general
ax1 = fig.add_subplot(2, 2, 1)

# add a subplot with no frame
ax2 = fig.add_subplot(222, frameon=False)

# add a polar subplot
fig.add_subplot(223, projection='polar')

# add a red subplot that share the x-axis with ax1
fig.add_subplot(224, sharex=ax1, facecolor='red')

#delete x2 from the figure
fig.delaxes(ax2)

#add x2 to the figure again
fig.add_subplot(ax2)
align_labels(self, axs=None) [source]

Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

Parameters:
axslist of Axes

Optional list (or ndarray) of Axes to align the labels. Default is to align all axes on the figure.

align_xlabels(self, axs=None) [source]

Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

If a label is on the bottom, it is aligned with labels on axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on axes with the same top-most row.

Parameters:
axslist of Axes

Optional list of (or ndarray) Axes to align the xlabels. Default is to align all axes on the figure.

Notes

This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions.

Examples

Example with rotated xtick labels:

fig, axs = plt.subplots(1, 2)
for tick in axs[0].get_xticklabels():
    tick.set_rotation(55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
align_ylabels(self, axs=None) [source]

Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).

Alignment persists for draw events after this is called.

If a label is on the left, it is aligned with labels on axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on axes with the same right-most column.

Parameters:
axslist of Axes

Optional list (or ndarray) of Axes to align the ylabels. Default is to align all axes on the figure.

Notes

This assumes that axs are from the same GridSpec, so that their SubplotSpec positions correspond to figure positions.

Examples

Example with large yticks labels:

fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
autofmt_xdate(self, bottom=0.2, rotation=30, ha='right', which=None) [source]

Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.

Parameters:
bottomscalar

The bottom of the subplots for subplots_adjust().

rotationangle in degrees

The rotation of the xtick labels.

hastr

The horizontal alignment of the xticklabels.

which{None, 'major', 'minor', 'both'}

Selects which ticklabels to rotate. Default is None which works the same as major.

property axes

List of axes in the Figure. You can access the axes in the Figure through this list. Do not modify the list itself. Instead, use add_axes, subplot or delaxes to add or remove an axes.

clear(self, keep_observers=False) [source]

Clear the figure -- synonym for clf().

clf(self, keep_observers=False) [source]

Clear the figure.

Set keep_observers to True if, for example, a gui widget is tracking the axes in the figure.

colorbar(self, mappable, cax=None, ax=None, use_gridspec=True, **kw) [source]

Create a colorbar for a ScalarMappable instance, mappable.

Documentation for the pyplot thin wrapper:

Add a colorbar to a plot.

Function signatures for the pyplot interface; all but the first are also method signatures for the colorbar() method:

colorbar(**kwargs)
colorbar(mappable, **kwargs)
colorbar(mappable, cax=cax, **kwargs)
colorbar(mappable, ax=ax, **kwargs)
Parameters:
mappable

The matplotlib.cm.ScalarMappable (i.e., Image, ContourSet, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar method but optional for the pyplot.colorbar function, which sets the default to the current image.

Note that one can create a ScalarMappable "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.

fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
caxAxes object, optional

Axes into which the colorbar will be drawn.

axAxes, list of Axes, optional

Parent axes from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.

use_gridspecbool, optional

If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the gridspec module.

Returns:
colorbarColorbar

See also its base class, ColorbarBase.

Notes

Additional keyword arguments are of two kinds:

axes properties:

Property Description
orientation vertical or horizontal
fraction 0.15; fraction of original axes to use for colorbar
pad 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes
shrink 1.0; fraction by which to multiply the size of the colorbar
aspect 20; ratio of long to short dimensions
anchor (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal; the anchor point of the colorbar axes
panchor (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal; the anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged

colorbar properties:

Property Description
extend {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods.
extendfrac {None, 'auto', length, lengths} If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional'). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
extendrect bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
spacing {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval.
ticks None or list of ticks or Locator If None, ticks are determined automatically from the input.
format None or str or Formatter If None, the ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter object may be given instead.
drawedges bool Whether to draw lines at color boundaries.
label str The label on the colorbar's long axis.

The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.

Property Description
boundaries None or a sequence
values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used.

If mappable is a ContourSet, its extend kwarg is included automatically.

The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored.

For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs.

It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:

cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()

However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).

contains(self, mouseevent) [source]

Test whether the mouse event occurred on the figure.

Returns:
bool, {}
delaxes(self, ax) [source]

Remove the Axes ax from the figure and update the current axes.

property dpi

The resolution in dots per inch.

draw(self, renderer) [source]

Render the figure using matplotlib.backend_bases.RendererBase instance renderer.

draw_artist(self, a) [source]

Draw matplotlib.artist.Artist instance a only. This is available only after the figure is drawn.

execute_constrained_layout(self, renderer=None) [source]

Use layoutbox to determine pos positions within axes.

See also set_constrained_layout_pads.

figimage(self, X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs) [source]

Add a non-resampled image to the figure.

The image is attached to the lower or upper left corner depending on origin.

Parameters:
X

The image data. This is an array of one of the following shapes:

  • MxN: luminance (grayscale) values
  • MxNx3: RGB values
  • MxNx4: RGBA values
xo, yoint

The x/y image offset in pixels.

alphaNone or float

The alpha blending value.

normmatplotlib.colors.Normalize

A Normalize instance to map the luminance to the interval [0, 1].

cmapstr or matplotlib.colors.Colormap

The colormap to use. Default: rcParams["image.cmap"] (default: 'viridis').

vmin, vmaxscalar

If norm is not given, these values set the data limits for the colormap.

origin{'upper', 'lower'}

Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes. Defaults to rcParams["image.origin"] (default: 'upper').

resizebool

If True, resize the figure to match the given image size.

Returns:
matplotlib.image.FigureImage
Other Parameters:
**kwargs

Additional kwargs are Artist kwargs passed on to FigureImage.

Notes

figimage complements the axes image (imshow()) which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define an Axes with extent [0, 0, 1, 1].

Examples:

f = plt.figure()
nx = int(f.get_figwidth() * f.dpi)
ny = int(f.get_figheight() * f.dpi)
data = np.random.random((ny, nx))
f.figimage(data)
plt.show()
property frameon

Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().

gca(self, **kwargs) [source]

Get the current axes, creating one if necessary.

The following kwargs are supported for ensuring the returned axes adheres to the given projection etc., and for axes creation if the active axes does not exist:

Property Description
adjustable {'box', 'datalim'}
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
anchor 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...}
animated bool
aspect {'auto', 'equal'} or num
autoscale_on bool
autoscalex_on bool
autoscaley_on bool
axes_locator Callable[[Axes, Renderer], Bbox]
axisbelow bool or 'line'
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
contains callable
facecolor color
fc color
figure Figure
frame_on bool
gid str
in_layout bool
label object
navigate bool
navigate_mode unknown
path_effects AbstractPathEffect
picker None or bool or float or callable
position [left, bottom, width, height] or Bbox
prop_cycle unknown
rasterization_zorder float or None
rasterized bool or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
title str
transform Transform
url str
visible bool
xbound unknown
xlabel str
xlim (bottom: float, top: float)
xmargin float greater than -0.5
xscale {"linear", "log", "symlog", "logit", ...}
xticklabels List[str]
xticks unknown
ybound unknown
ylabel str
ylim (bottom: float, top: float)
ymargin float greater than -0.5
yscale {"linear", "log", "symlog", "logit", ...}
yticklabels List[str]
yticks unknown
zorder float
get_axes(self) [source]

Return a list of axes in the Figure. You can access and modify the axes in the Figure through this list.

Do not modify the list itself. Instead, use add_axes, subplot or delaxes to add or remove an axes.

Note: This is equivalent to the property axes.

get_children(self) [source]

Get a list of artists contained in the figure.

get_constrained_layout(self) [source]

Return a boolean: True means constrained layout is being used.

See Constrained Layout Guide.

get_constrained_layout_pads(self, relative=False) [source]

Get padding for constrained_layout.

Returns a list of w_pad, h_pad in inches and wspace and hspace as fractions of the subplot.

See Constrained Layout Guide.

Parameters:
relativeboolean

If True, then convert from inches to figure relative.

get_default_bbox_extra_artists(self) [source]
get_dpi(self) [source]

Return the resolution in dots per inch as a float.

get_edgecolor(self) [source]

Get the edge color of the Figure rectangle.

get_facecolor(self) [source]

Get the face color of the Figure rectangle.

get_figheight(self) [source]

Return the figure height as a float.

get_figwidth(self) [source]

Return the figure width as a float.

get_frameon(self) [source]

Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible().

get_size_inches(self) [source]

Returns the current size of the figure in inches.

Returns:
sizendarray

The size (width, height) of the figure in inches.

See also

matplotlib.Figure.set_size_inches
get_tight_layout(self) [source]

Return whether tight_layout is called when drawing.

get_tightbbox(self, renderer, bbox_extra_artists=None) [source]

Return a (tight) bounding box of the figure in inches.

Artists that have artist.set_in_layout(False) are not included in the bbox.

Parameters:
rendererRendererBase instance

renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer())

bbox_extra_artistslist of Artist or None

List of artists to include in the tight bounding box. If None (default), then all artist children of each axes are included in the tight bounding box.

Returns:
bboxBboxBase

containing the bounding box (in figure inches).

get_window_extent(self, *args, **kwargs) [source]

Return the figure bounding box in display space. Arguments are ignored.

ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2) [source]

Blocking call to interact with a figure.

Wait until the user clicks n times on the figure, and return the coordinates of each click in a list.

There are three possible interactions:

  • Add a point.
  • Remove the most recently added point.
  • Stop the interaction and return the points added so far.

The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop. Mouse buttons are defined by the numbers:

  • 1: left mouse button
  • 2: middle mouse button
  • 3: right mouse button
  • None: no mouse button
Parameters:
nint, optional, default: 1

Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.

timeoutscalar, optional, default: 30

Number of seconds to wait before timing out. If zero or negative will never timeout.

show_clicksbool, optional, default: True

If True, show a red cross at the location of each click.

mouse_add{1, 2, 3, None}, optional, default: 1 (left click)

Mouse button used to add points.

mouse_pop{1, 2, 3, None}, optional, default: 3 (right click)

Mouse button used to remove the most recently added point.

mouse_stop{1, 2, 3, None}, optional, default: 2 (middle click)

Mouse button used to stop input.

Returns:
pointslist of tuples

A list of the clicked (x, y) coordinates.

Notes

The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.

init_layoutbox(self) [source]

Initialize the layoutbox for use in constrained_layout.

legend(self, *args, **kwargs) [source]

Place a legend on the figure.

To make a legend from existing artists on every axes:

legend()

To make a legend for a list of lines and labels:

legend(
    (line1, line2, line3),
    ('label1', 'label2', 'label3'),
    loc='upper right')

These can also be specified by keyword:

legend(
    handles=(line1, line2, line3),
    labels=('label1', 'label2', 'label3'),
    loc='upper right')
Parameters:
handleslist of Artist, optional

A list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.

labelslist of str, optional

A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.

Returns:
matplotlib.legend.Legend instance
Other Parameters:
locstr or pair of floats, default: rcParams["legend.loc"] (default: 'best') ('best' for axes, 'upper right' for figures)

The location of the legend.

The strings 'upper left', 'upper right', 'lower left', 'lower right' place the legend at the corresponding corner of the axes/figure.

The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure.

The string 'center' places the legend at the center of the axes/figure.

The string 'best' places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

For back-compatibility, 'center right' (but no other location) can also be spelled 'right', and each "string" locations can also be given as a numeric value:

Location String Location Code
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats

Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox (if called as a method to Axes.legend) or figure.bbox (if Figure.legend). This argument allows arbitrary placement of the legend.

Bbox coordinates are interpreted in the coordinate system given by bbox_transform, with the default transform Axes or Figure coordinates, depending on which legend is called.

If a 4-tuple or BboxBase is given, then it specifies the bbox (x, y, width, height) that the legend is placed in. To put the legend in the best location in the bottom right quadrant of the axes (or figure):

loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)

A 2-tuple (x, y) places the corner of the legend specified by loc at x, y. For example, to put the legend's upper right-hand corner in the center of the axes (or figure) the following keywords can be used:

loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncolinteger

The number of columns that the legend has. Default is 1.

propNone or matplotlib.font_manager.FontProperties or dict

The font properties of the legend. If None (default), the current matplotlib.rcParams will be used.

fontsizeint or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}

The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.

numpointsNone or int

The number of marker points in the legend when creating a legend entry for a Line2D (line). Default is None, which means using rcParams["legend.numpoints"] (default: 1).

scatterpointsNone or int

The number of marker points in the legend when creating a legend entry for a PathCollection (scatter plot). Default is None, which means using rcParams["legend.scatterpoints"] (default: 1).

scatteryoffsetsiterable of floats

The vertical offset (relative to the font size) for the markers created for a scatter plot legend entry. 0.0 is at the base the legend text, and 1.0 is at the top. To draw all markers at the same height, set to [0.5]. Default is [0.375, 0.5, 0.3125].

markerscaleNone or int or float

The relative size of legend markers compared with the originally drawn ones. Default is None, which means using rcParams["legend.markerscale"] (default: 1.0).

markerfirstbool

If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label. Default is True.

frameonNone or bool

Whether the legend should be drawn on a patch (frame). Default is None, which means using rcParams["legend.frameon"] (default: True).

fancyboxNone or bool

Whether round edges should be enabled around the FancyBboxPatch which makes up the legend's background. Default is None, which means using rcParams["legend.fancybox"] (default: True).

shadowNone or bool

Whether to draw a shadow behind the legend. Default is None, which means using rcParams["legend.shadow"] (default: False).

framealphaNone or float

The alpha transparency of the legend's background. Default is None, which means using rcParams["legend.framealpha"] (default: 0.8). If shadow is activated and framealpha is None, the default value is ignored.

facecolorNone or "inherit" or color

The legend's background color. Default is None, which means using rcParams["legend.facecolor"] (default: 'inherit'). If "inherit", use rcParams["axes.facecolor"] (default: 'white').

edgecolorNone or "inherit" or color

The legend's background patch edge color. Default is None, which means using rcParams["legend.edgecolor"] (default: '0.8'). If "inherit", use take rcParams["axes.edgecolor"] (default: 'black').

mode{"expand", None}

If mode is set to "expand" the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor if defines the legend's size).

bbox_transformNone or matplotlib.transforms.Transform

The transform for the bounding box (bbox_to_anchor). For a value of None (default) the Axes' transAxes transform will be used.

titlestr or None

The legend's title. Default is no title (None).

title_fontsize: str or None

The fontsize of the legend's title. Default is the default fontsize.

borderpadfloat or None

The fractional whitespace inside the legend border, in font-size units. Default is None, which means using rcParams["legend.borderpad"] (default: 0.4).

labelspacingfloat or None

The vertical space between the legend entries, in font-size units. Default is None, which means using rcParams["legend.labelspacing"] (default: 0.5).

handlelengthfloat or None

The length of the legend handles, in font-size units. Default is None, which means using rcParams["legend.handlelength"] (default: 2.0).

handletextpadfloat or None

The pad between the legend handle and text, in font-size units. Default is None, which means using rcParams["legend.handletextpad"] (default: 0.8).

borderaxespadfloat or None

The pad between the axes and legend border, in font-size units. Default is None, which means using rcParams["legend.borderaxespad"] (default: 0.5).

columnspacingfloat or None

The spacing between columns, in font-size units. Default is None, which means using rcParams["legend.columnspacing"] (default: 2.0).

handler_mapdict or None

The custom dictionary mapping instances or types to a legend handler. This handler_map updates the default handler map found at matplotlib.legend.Legend.get_legend_handler_map().

Notes

Not all kinds of artist are supported by the legend command. See Legend guide for details.

savefig(self, fname, *, transparent=None, **kwargs) [source]

Save the current figure.

Call signature:

savefig(fname, dpi=None, facecolor='w', edgecolor='w',
        orientation='portrait', papertype=None, format=None,
        transparent=False, bbox_inches=None, pad_inches=0.1,
        frameon=None, metadata=None)

The output formats available depend on the backend being used.

Parameters:
fnamestr or PathLike or file-like object

A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages.

If format is not set, then the output format is inferred from the extension of fname, if any, and from rcParams["savefig.format"] (default: 'png') otherwise. If format is set, it determines the output format.

Hence, if fname is not a path or has no extension, remember to specify format to ensure that the correct backend is used.

Other Parameters:
dpi[ None | scalar > 0 | 'figure' ]

The resolution in dots per inch. If None, defaults to rcParams["savefig.dpi"] (default: 'figure'). If 'figure', uses the figure's dpi value.

quality[ None | 1 <= scalar <= 100 ]

The image quality, on a scale from 1 (worst) to 95 (best). Applicable only if format is jpg or jpeg, ignored otherwise. If None, defaults to rcParams["savefig.jpeg_quality"] (default: 95). Values above 95 should be avoided; 100 completely disables the JPEG quantization stage.

optimizebool

If True, indicates that the JPEG encoder should make an extra pass over the image in order to select optimal encoder settings. Applicable only if format is jpg or jpeg, ignored otherwise. Is False by default.

progressivebool

If True, indicates that this image should be stored as a progressive JPEG file. Applicable only if format is jpg or jpeg, ignored otherwise. Is False by default.

facecolorcolor or None, optional

The facecolor of the figure; if None, defaults to rcParams["savefig.facecolor"] (default: 'white').

edgecolorcolor or None, optional

The edgecolor of the figure; if None, defaults to rcParams["savefig.edgecolor"] (default: 'white')

orientation{'landscape', 'portrait'}

Currently only supported by the postscript backend.

papertypestr

One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.

formatstr

The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.

transparentbool

If True, the axes patches will all be transparent; the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.

bbox_inchesstr or Bbox, optional

Bbox in inches. Only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. If None, use savefig.bbox

pad_inchesscalar, optional

Amount of padding around the figure when bbox_inches is 'tight'. If None, use savefig.pad_inches

bbox_extra_artistslist of Artist, optional

A list of extra artists that will be considered when the tight bbox is calculated.

metadatadict, optional

Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:

  • 'png' with Agg backend: See the parameter metadata of print_png.
  • 'pdf' with pdf backend: See the parameter metadata of PdfPages.
  • 'eps' and 'ps' with PS backend: Only 'Creator' is supported.
pil_kwargsdict, optional

Additional keyword arguments that are passed to PIL.Image.save when saving the figure. Only applicable for formats that are saved using Pillow, i.e. JPEG, TIFF, and (if the keyword is set to a non-None value) PNG.

sca(self, a) [source]

Set the current axes to be a and return a.

set_canvas(self, canvas) [source]

Set the canvas that contains the figure

Parameters:
canvasFigureCanvas
set_constrained_layout(self, constrained) [source]

Set whether constrained_layout is used upon drawing. If None, the rcParams['figure.constrained_layout.use'] value will be used.

When providing a dict containing the keys w_pad, h_pad the default constrained_layout paddings will be overridden. These pads are in inches and default to 3.0/72.0. w_pad is the width padding and h_pad is the height padding.

See Constrained Layout Guide.

Parameters:
constrainedbool or dict or None
set_constrained_layout_pads(self, **kwargs) [source]

Set padding for constrained_layout. Note the kwargs can be passed as a dictionary fig.set_constrained_layout(**paddict).

See Constrained Layout Guide.

Parameters:
w_padscalar

Width padding in inches. This is the pad around axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches

h_padscalar

Height padding in inches. Defaults to 3 pts.

wspacescalar

Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace.

hspacescalar

Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace.

set_dpi(self, val) [source]

Set the resolution of the figure in dots-per-inch.

Parameters:
valfloat
set_edgecolor(self, color) [source]

Set the edge color of the Figure rectangle.

Parameters:
colorcolor
set_facecolor(self, color) [source]

Set the face color of the Figure rectangle.

Parameters:
colorcolor
set_figheight(self, val, forward=True) [source]

Set the height of the figure in inches.

Parameters:
valfloat
forwardbool
set_figwidth(self, val, forward=True) [source]

Set the width of the figure in inches.

Parameters:
valfloat
forwardbool
set_frameon(self, b) [source]

Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible().

Parameters:
bbool
set_size_inches(self, w, h=None, forward=True) [source]

Set the figure size in inches.

Call signatures:

fig.set_size_inches(w, h)  # OR
fig.set_size_inches((w, h))
Parameters:
w(float, float) or float

Width and height in inches (if height not specified as a separate argument) or width.

hfloat

Height in inches.

forwardbool, default: True

If True, the canvas size is automatically updated, e.g., you can resize the figure window from the shell.

See also

matplotlib.Figure.get_size_inches
set_tight_layout(self, tight) [source]

Set whether and how tight_layout is called when drawing.

Parameters:
tightbool or dict with keys "pad", "w_pad", "h_pad", "rect" or None

If a bool, sets whether to call tight_layout upon drawing. If None, use the figure.autolayout rcparam instead. If a dict, pass it as kwargs to tight_layout, overriding the default paddings.

show(self, warn=True) [source]

If using a GUI backend with pyplot, display the figure window.

If the figure was not created using figure(), it will lack a FigureManagerBase, and will raise an AttributeError.

Warning

This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop.

Proper use cases for Figure.show include running this from a GUI application or an IPython shell.

If you're running a pure python shell or executing a non-GUI python script, you should use matplotlib.pyplot.show instead, which takes care of managing the event loop for you.

Parameters:
warnbool

If True and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend.

subplots(self, nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None) [source]

Add a set of subplots to this figure.

This utility wrapper makes it convenient to create common layouts of subplots in a single call.

Parameters:
nrows, ncolsint, optional, default: 1

Number of rows/columns of the subplot grid.

sharex, shareybool or {'none', 'all', 'row', 'col'}, default: False

Controls sharing of properties among x (sharex) or y (sharey) axes:

  • True or 'all': x- or y-axis will be shared among all subplots.
  • False or 'none': each subplot x- or y-axis will be independent.
  • 'row': each subplot row will share an x- or y-axis.
  • 'col': each subplot column will share an x- or y-axis.

When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use tick_params.

squeezebool, optional, default: True
  • If True, extra dimensions are squeezed out from the returned array of Axes:
    • if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
    • for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.
    • for NxM, subplots with N>1 and M>1 are returned as a 2D array.
  • If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
subplot_kwdict, optional

Dict with keywords passed to the add_subplot() call used to create each subplot.

gridspec_kwdict, optional

Dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.

Returns:
axAxes object or array of Axes objects.

ax can be either a single Axes object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

Examples

# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Create a figure
plt.figure()

# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)

# Create four polar axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(polar=True))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)

# Share a X axis with each column of subplots
fig.subplots(2, 2, sharex='col')

# Share a Y axis with each row of subplots
fig.subplots(2, 2, sharey='row')

# Share both X and Y axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')

# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None) [source]

Update the SubplotParams with kwargs (defaulting to rc when None) and update the subplot locations.

suptitle(self, t, **kwargs) [source]

Add a centered title to the figure.

Parameters:
tstr

The title text.

xfloat, default 0.5

The x location of the text in figure coordinates.

yfloat, default 0.98

The y location of the text in figure coordinates.

horizontalalignment, ha{'center', 'left', right'}, default: 'center'

The horizontal alignment of the text relative to (x, y).

verticalalignment, va{'top', 'center', 'bottom', 'baseline'}, default: 'top'

The vertical alignment of the text relative to (x, y).

fontsize, sizedefault: rcParams["figure.titlesize"] (default: 'large')

The font size of the text. See Text.set_size for possible values.

fontweight, weightdefault: rcParams["figure.titleweight"] (default: 'normal')

The font weight of the text. See Text.set_weight for possible values.

Returns:
text

The Text instance of the title.

Other Parameters:
fontpropertiesNone or dict, optional

A dict of font properties. If fontproperties is given the default values for font size and weight are taken from the FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and rcParams["figure.titleweight"] (default: 'normal') are ignored in this case.

**kwargs

Additional kwargs are matplotlib.text.Text properties.

Examples

>>> fig.suptitle('This is the figure title', fontsize=12)
text(self, x, y, s, fontdict=None, withdash=<deprecated parameter>, **kwargs) [source]

Add text to figure.

Parameters:
x, yfloat

The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.

sstr

The text string.

fontdictdictionary, optional, default: None

A dictionary to override the default text properties. If fontdict is None, the defaults are determined by your rc parameters. A property in kwargs override the same property in fontdict.

withdashboolean, optional, default: False

Creates a TextWithDash instance instead of a Text instance.

Returns:
textText
Other Parameters:
**kwargsText properties

Other miscellaneous text parameters.

Property Description
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
animated bool
backgroundcolor color
bbox dict with properties for patches.FancyBboxPatch
clip_box Bbox
clip_on bool
clip_path Patch or (Path, Transform) or None
color or c color
contains callable
figure Figure
fontfamily or family {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}
fontproperties or font_properties font_manager.FontProperties
fontsize or size {size in points, 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}
fontstretch or stretch {a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}
fontstyle or style {'normal', 'italic', 'oblique'}
fontvariant or variant {'normal', 'small-caps'}
fontweight or weight {a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'}
gid str
horizontalalignment or ha {'center', 'right', 'left'}
in_layout bool
label object
linespacing float (multiple of font size)
multialignment or ma {'left', 'right', 'center'}
path_effects AbstractPathEffect
picker None or bool or float or callable
position (float, float)
rasterized bool or None
rotation {angle in degrees, 'vertical', 'horizontal'}
rotation_mode {None, 'default', 'anchor'}
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
text object
transform Transform
url str
usetex bool or None
verticalalignment or va {'center', 'top', 'bottom', 'baseline', 'center_baseline'}
visible bool
wrap bool
x float
y float
zorder float
tight_layout(self, renderer=<deprecated parameter>, pad=1.08, h_pad=None, w_pad=None, rect=None) [source]

Automatically adjust subplot parameters to give specified padding.

To exclude an artist on the axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), then set a.set_in_layout(False) for that artist.

Parameters:
renderersubclass of RendererBase, optional

Defaults to the renderer for the figure. Deprecated.

padfloat, optional

Padding between the figure edge and the edges of subplots, as a fraction of the font size.

h_pad, w_padfloat, optional

Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. Defaults to pad.

recttuple (left, bottom, right, top), optional

A rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1).

waitforbuttonpress(self, timeout=- 1) [source]

Blocking call to interact with the figure.

This will return True is a key was pressed, False if a mouse button was pressed and None if timeout was reached without either being pressed.

If timeout is negative, does not timeout.

Examples using matplotlib.figure.Figure

Stacked bar chart

Stacked bar chart

Grouped bar chart with labels

Grouped bar chart with labels

Horizontal bar chart

Horizontal bar chart

Broken Barh

Broken Barh

Plotting categorical variables

Plotting categorical variables

Plotting the coherence of two signals

Plotting the coherence of two signals

CSD Demo

CSD Demo

Errorbar limit selection

Errorbar limit selection

Errorbar Subsample

Errorbar Subsample

EventCollection Demo

EventCollection Demo

Eventplot Demo

Eventplot Demo

Filled polygon

Filled polygon

Filling the area between lines

Filling the area between lines

Fill Betweenx Demo

Fill Betweenx Demo

Hatch-filled histograms

Hatch-filled histograms

Bar chart with gradients

Bar chart with gradients

Join styles and cap styles

Join styles and cap styles

Customizing dashed line styles

Customizing dashed line styles

Linestyles

Linestyles

Marker filling-styles

Marker filling-styles

Marker Reference

Marker Reference

Markevery Demo

Markevery Demo

prop_cycle property markevery in rcParams

prop_cycle property markevery in rcParams

Multicolored lines

Multicolored lines

Psd Demo

Psd Demo

Scatter Custom Symbol

Scatter Custom Symbol

Scatter Demo2

Scatter Demo2

Scatter plot with histograms

Scatter plot with histograms

Scatter plot with pie chart markers

Scatter plot with pie chart markers

Scatter plots with a legend

Scatter plots with a legend

Simple Plot

Simple Plot

Using span_where

Using span_where

Spectrum Representations

Spectrum Representations

Stackplot Demo

Stackplot Demo

Creating a timeline with lines, dates, and text

Creating a timeline with lines, dates, and text

hlines and vlines

hlines and vlines

Cross- and Auto-Correlation Demo

Cross- and Auto-Correlation Demo

Affine transform of an image

Affine transform of an image

Barb Demo

Barb Demo

Barcode Demo

Barcode Demo

Contour Corner Mask

Contour Corner Mask

Contour Demo

Contour Demo

Contour Image

Contour Image

Contour Label Demo

Contour Label Demo

Contourf Demo

Contourf Demo

Contourf Hatching

Contourf Hatching

Contourf and log color scale

Contourf and log color scale

BboxImage Demo

BboxImage Demo

Figimage Demo

Figimage Demo

Creating annotated heatmaps

Creating annotated heatmaps

Image antialiasing

Image antialiasing

Clipping images with patches

Clipping images with patches

Image Demo

Image Demo

Image Masked

Image Masked

Image Nonuniform

Image Nonuniform

Blend transparency with color in 2-D images

Blend transparency with color in 2-D images

Modifying the coordinate formatter

Modifying the coordinate formatter

Interpolations for imshow

Interpolations for imshow

Contour plot of irregularly spaced data

Contour plot of irregularly spaced data

Layer Images

Layer Images

Multi Image

Multi Image

Pcolor Demo

Pcolor Demo

pcolormesh

pcolormesh

Streamplot

Streamplot

QuadMesh Demo

QuadMesh Demo

Advanced quiver and quiverkey functions

Advanced quiver and quiverkey functions

Quiver Simple Demo

Quiver Simple Demo

Spectrogram Demo

Spectrogram Demo

Spy Demos

Spy Demos

Tricontour Demo

Tricontour Demo

Tricontour Smooth Delaunay

Tricontour Smooth Delaunay

Tricontour Smooth User

Tricontour Smooth User

Trigradient Demo

Trigradient Demo

Triinterp Demo

Triinterp Demo

Tripcolor Demo

Tripcolor Demo

Triplot Demo

Triplot Demo

Watermark image

Watermark image

Aligning Labels

Aligning Labels

Axes Demo

Axes Demo

Controlling view limits using margins and sticky_edges

Controlling view limits using margins and sticky_edges

Axes Props

Axes Props

Axis Equal Demo

Axis Equal Demo

Broken Axis

Broken Axis

Placing Colorbars

Placing Colorbars

Custom Figure subclasses

Custom Figure subclasses

Resizing axes with constrained layout

Resizing axes with constrained layout

Resizing axes with tight layout

Resizing axes with tight layout

Figure Title

Figure Title

Creating adjacent subplots

Creating adjacent subplots

Combining two subplots using subplots and GridSpec

Combining two subplots using subplots and GridSpec

Using Gridspec to make multi-column/row subplot layouts

Using Gridspec to make multi-column/row subplot layouts

Nested Gridspecs

Nested Gridspecs

Invert Axes

Invert Axes

Secondary Axis

Secondary Axis

Basic Subplot Demo

Basic Subplot Demo

Subplot Toolbar

Subplot Toolbar

Creating multiple subplots using ``plt.subplots``

Creating multiple subplots using plt.subplots

Plots with different scales

Plots with different scales

Zoom region inset axes

Zoom region inset axes

Artist customization in box plots

Artist customization in box plots

Box plots with custom fill colors

Box plots with custom fill colors

Boxplots

Boxplots

Box plot vs. violin plot comparison

Box plot vs. violin plot comparison

Boxplot drawer function

Boxplot drawer function

Plot a confidence ellipse of a two-dimensional dataset

Plot a confidence ellipse of a two-dimensional dataset

Violin plot customization

Violin plot customization

Errorbar function

Errorbar function

Different ways of specifying error bars

Different ways of specifying error bars

Including upper and lower limits in error bars

Including upper and lower limits in error bars

Creating boxes from error bars using PatchCollection

Creating boxes from error bars using PatchCollection

Hexbin Demo

Hexbin Demo

Histograms

Histograms

Using histograms to plot a cumulative distribution

Using histograms to plot a cumulative distribution

Demo of the histogram (hist) function with a few features

Demo of the histogram (hist) function with a few features

Demo of the histogram function's different ``histtype`` settings

Demo of the histogram function's different histtype settings

The histogram (hist) function with multiple data sets

The histogram (hist) function with multiple data sets

Producing multiple histograms side by side

Producing multiple histograms side by side

Violin plot basics

Violin plot basics

Basic pie chart

Basic pie chart

Pie Demo2

Pie Demo2

Bar of pie

Bar of pie

Nested pie charts

Nested pie charts

Labeling a pie and a donut

Labeling a pie and a donut

Polar Legend

Polar Legend

Scatter plot on polar axis

Scatter plot on polar axis

Using accented text in matplotlib

Using accented text in matplotlib

Annotating Plots

Annotating Plots

Auto-wrapping text

Auto-wrapping text

Composing Custom Legends

Composing Custom Legends

Dashpoint Label

Dashpoint Label

Date tick labels

Date tick labels

Custom tick formatter for time series

Custom tick formatter for time series

Demo Annotation Box

Demo Annotation Box

Demo Text Path

Demo Text Path

Demo Text Rotation Mode

Demo Text Rotation Mode

The difference between \\dfrac and \\frac

The difference between \dfrac and \frac

Labeling ticks using engineering notation

Labeling ticks using engineering notation

Fancyarrow Demo

Fancyarrow Demo

Figure legend demo

Figure legend demo

Using a ttf font file in Matplotlib

Using a ttf font file in Matplotlib

Legend using pre-defined labels

Legend using pre-defined labels

Legend Demo

Legend Demo

Artist within an artist

Artist within an artist

A mathtext image as numpy array

A mathtext image as numpy array

Mathtext Demo

Mathtext Demo

STIX Fonts Demo

STIX Fonts Demo

Rendering math equation using TeX

Rendering math equation using TeX

Default text rotation demonstration

Default text rotation demonstration

Unicode minus

Unicode minus

Usetex Baseline Test

Usetex Baseline Test

Text watermark

Text watermark

Align y-labels

Align y-labels

Annotate Transform

Annotate Transform

Annotating a plot

Annotating a plot

Annotation Polar

Annotation Polar

Auto Subplots Adjust

Auto Subplots Adjust

Boxplot Demo

Boxplot Demo

Dollar Ticks

Dollar Ticks

Fig Axes Customize Simple

Fig Axes Customize Simple

Simple axes labels

Simple axes labels

Adding lines to figures

Adding lines to figures

Text Commands

Text Commands

Text Layout

Text Layout

Whats New 1 Subplot3d

Whats New 1 Subplot3d

Fill Between

Fill Between

Whats New 0.99 Axes Grid

Whats New 0.99 Axes Grid

Whats New 0.99 Mplot3d

Whats New 0.99 Mplot3d

Whats New 0.99 Spines

Whats New 0.99 Spines

Color Demo

Color Demo

Color by y-value

Color by y-value

Colors in the default property cycle

Colors in the default property cycle

Styling with cycler

Styling with cycler

Colorbar

Colorbar

Creating a colormap from a list of colors

Creating a colormap from a list of colors

Arrow guide

Arrow guide

Reference for Matplotlib artists

Reference for Matplotlib artists

Line, Poly and RegularPoly Collection with autoscaling

Line, Poly and RegularPoly Collection with autoscaling

Compound path

Compound path

Dolphins

Dolphins

Mmh Donuts!!!

Mmh Donuts!!!

Ellipse Collection

Ellipse Collection

Ellipse Demo

Ellipse Demo

Drawing fancy boxes

Drawing fancy boxes

Hatch Demo

Hatch Demo

Line Collection

Line Collection

Circles, Wedges and Polygons

Circles, Wedges and Polygons

PathPatch object

PathPatch object

Bezier Curve

Bezier Curve

Bayesian Methods for Hackers style sheet

Bayesian Methods for Hackers style sheet

Dark background style sheet

Dark background style sheet

FiveThirtyEight style sheet

FiveThirtyEight style sheet

ggplot style sheet

ggplot style sheet

Grayscale style sheet

Grayscale style sheet

Style sheets reference

Style sheets reference

Demo Anchored Direction Arrow

Demo Anchored Direction Arrow

Demo Axes Grid

Demo Axes Grid

Demo Axes Grid2

Demo Axes Grid2

Demo Axes Hbox Divider

Demo Axes Hbox Divider

Demo Colorbar of Inset Axes

Demo Colorbar of Inset Axes

Demo Colorbar with Axes Divider

Demo Colorbar with Axes Divider

Controlling the position and size of colorbars with Inset Axes

Controlling the position and size of colorbars with Inset Axes

Demo Edge Colorbar

Demo Edge Colorbar

Demo Imagegrid Aspect

Demo Imagegrid Aspect

Inset Locator Demo

Inset Locator Demo

Inset Locator Demo2

Inset Locator Demo2

Make Room For Ylabel Using Axesgrid

Make Room For Ylabel Using Axesgrid

Parasite Simple2

Parasite Simple2

Scatter Histogram (Locatable Axes)

Scatter Histogram (Locatable Axes)

Simple Axes Divider 1

Simple Axes Divider 1

Simple Axes Divider 2

Simple Axes Divider 2

Simple Axes Divider 3

Simple Axes Divider 3

Simple ImageGrid

Simple ImageGrid

Simple ImageGrid 2

Simple ImageGrid 2

Simple RGB

Simple RGB

Axis Direction Demo Step01

Axis Direction Demo Step01

Axis Direction Demo Step02

Axis Direction Demo Step02

Axis Direction Demo Step03

Axis Direction Demo Step03

Axis Direction Demo Step04

Axis Direction Demo Step04

Demo Axis Direction

Demo Axis Direction

Axis line styles

Axis line styles

Curvilinear grid demo

Curvilinear grid demo

Demo Curvelinear Grid2

Demo Curvelinear Grid2

:mod:`mpl_toolkits.axisartist.floating_axes` features

mpl_toolkits.axisartist.floating_axes features

Demo Floating Axis

Demo Floating Axis

Parasite Axes demo

Parasite Axes demo

Demo Ticklabel Alignment

Demo Ticklabel Alignment

Demo Ticklabel Direction

Demo Ticklabel Direction

Simple Axis Direction01

Simple Axis Direction01

Simple Axis Direction03

Simple Axis Direction03

Simple Axis Pad

Simple Axis Pad

Simple Axisartist1

Simple Axisartist1

Simple Axisline

Simple Axisline

Simple Axisline2

Simple Axisline2

Simple Axisline3

Simple Axisline3

Anatomy of a figure

Anatomy of a figure

Bachelor's degrees by gender

Bachelor's degrees by gender

Firefox

Firefox

Integral as the area under a curve

Integral as the area under a curve

Shaded & power normalized rendering

Shaded & power normalized rendering

XKCD

XKCD

Decay

Decay

Animated histogram

Animated histogram

pyplot animation

pyplot animation

The Bayes update

The Bayes update

Animated image using a precomputed list of images

Animated image using a precomputed list of images

Rain simulation

Rain simulation

Animated 3D random walk

Animated 3D random walk

Animated line plot

Animated line plot

Oscilloscope

Oscilloscope

MATPLOTLIB **UNCHAINED**

MATPLOTLIB UNCHAINED

Close Event

Close Event

Coords demo

Coords demo

Data Browser

Data Browser

Figure Axes Enter Leave

Figure Axes Enter Leave

Image Slices Viewer

Image Slices Viewer

Keypress Demo

Keypress Demo

Legend Picking

Legend Picking

Looking Glass

Looking Glass

Path Editor

Path Editor

Pick Event Demo2

Pick Event Demo2

Poly Editor

Poly Editor

Resampling Data

Resampling Data

Timers

Timers

Viewlims

Viewlims

Zoom Window

Zoom Window

Frontpage 3D example

Frontpage 3D example

Frontpage contour example

Frontpage contour example

Frontpage histogram example

Frontpage histogram example

Frontpage plot example

Frontpage plot example

Agg Buffer To Array

Agg Buffer To Array

Changing colors of lines intersecting a box

Changing colors of lines intersecting a box

Manual Contour

Manual Contour

Coords Report

Coords Report

Demo Agg Filter

Demo Agg Filter

Findobj Demo

Findobj Demo

Building histograms using Rectangles and PolyCollections

Building histograms using Rectangles and PolyCollections

Plotting with keywords

Plotting with keywords

Load converter

Load converter

Multipage PDF

Multipage PDF

Pythonic Matplotlib

Pythonic Matplotlib

Rasterization Demo

Rasterization Demo

SVG Filter Line

SVG Filter Line

SVG Filter Pie

SVG Filter Pie

Transoffset

Transoffset

Zorder Demo

Zorder Demo

Plot 2D data on 3D plot

Plot 2D data on 3D plot

Demo of 3D bar charts

Demo of 3D bar charts

Create 2D bar graphs in different planes

Create 2D bar graphs in different planes

Demonstrates plotting contour (level) curves in 3D

Demonstrates plotting contour (level) curves in 3D

Demonstrates plotting contour (level) curves in 3D using the extend3d option

Demonstrates plotting contour (level) curves in 3D using the extend3d option

Projecting contour profiles onto a graph

Projecting contour profiles onto a graph

Filled contours

Filled contours

Projecting filled contour onto a graph

Projecting filled contour onto a graph

Custom hillshading in a 3D surface plot

Custom hillshading in a 3D surface plot

Create 3D histogram of 2D data

Create 3D histogram of 2D data

Parametric Curve

Parametric Curve

Lorenz Attractor

Lorenz Attractor

2D and 3D *Axes* in same *Figure*

2D and 3D Axes in same Figure

Automatic Text Offsetting

Automatic Text Offsetting

Draw flat objects in 3D plot

Draw flat objects in 3D plot

Generate polygons to fill under 3D line graph

Generate polygons to fill under 3D line graph

3D quiver plot

3D quiver plot

3D scatterplot

3D scatterplot

3D plots as subplots

3D plots as subplots

3D surface (color map)

3D surface (color map)

3D surface (solid color)

3D surface (solid color)

3D surface (checkerboard)

3D surface (checkerboard)

3D surface with polar coordinates

3D surface with polar coordinates

Text annotations in 3D

Text annotations in 3D

Triangular 3D contour plot

Triangular 3D contour plot

Triangular 3D filled contour plot

Triangular 3D filled contour plot

Triangular 3D surfaces

Triangular 3D surfaces

More triangular 3D surfaces

More triangular 3D surfaces

3D voxel / volumetric plot

3D voxel / volumetric plot

3D voxel plot of the numpy logo

3D voxel plot of the numpy logo

3D voxel / volumetric plot with rgb colors

3D voxel / volumetric plot with rgb colors

3D voxel / volumetric plot with cylindrical coordinates

3D voxel / volumetric plot with cylindrical coordinates

3D wireframe plot

3D wireframe plot

3D wireframe plots in one direction

3D wireframe plots in one direction

Fixing common date annoyances

Fixing common date annoyances

Easily creating subplots

Easily creating subplots

Fill Between and Alpha

Fill Between and Alpha

Placing text boxes

Placing text boxes

Loglog Aspect

Loglog Aspect

Log Bar

Log Bar

Log Demo

Log Demo

Log Axis

Log Axis

Logit Demo

Logit Demo

Exploring normalizations

Exploring normalizations

Scales

Scales

Anscombe's quartet

Anscombe's quartet

Left ventricle bullseye

Left ventricle bullseye

===

MRI

MRI With EEG

MRI With EEG

Radar chart (aka spider or star chart)

Radar chart (aka spider or star chart)

The Sankey class

The Sankey class

Long chain of connections using Sankey

Long chain of connections using Sankey

Rankine power cycle

Rankine power cycle

SkewT-logP diagram: using transforms and custom projections

SkewT-logP diagram: using transforms and custom projections

Topographic hillshading

Topographic hillshading

Automatically setting tick labels

Automatically setting tick labels

Centering labels between ticks

Centering labels between ticks

Colorbar Tick Labelling Demo

Colorbar Tick Labelling Demo

Custom Ticker1

Custom Ticker1

Formatting date ticks using ConciseDateFormatter

Formatting date ticks using ConciseDateFormatter

Date Demo Convert

Date Demo Convert

Date Demo Rrule

Date Demo Rrule

Date Index Formatter

Date Index Formatter

Major and minor ticks

Major and minor ticks

Multiple Yaxis With Spines

Multiple Yaxis With Spines

The default tick formatter

The default tick formatter

Spine Placement Demo

Spine Placement Demo

Spines

Spines

Custom spine bounds

Custom spine bounds

Dropped spines

Dropped spines

Tick formatters

Tick formatters

Tick locators

Tick locators

Set default y-axis tick labels on the right

Set default y-axis tick labels on the right

Setting tick labels from a list of values

Setting tick labels from a list of values

Set default x-axis tick labels on the top

Set default x-axis tick labels on the top

Annotation with units

Annotation with units

Artist tests

Artist tests

Bar demo with units

Bar demo with units

Group barchart with units

Group barchart with units

Ellipse With Units

Ellipse With Units

Evans test

Evans test

Radian ticks

Radian ticks

Inches and Centimeters

Inches and Centimeters

Unit handling

Unit handling

CanvasAgg demo

CanvasAgg demo

Embedding in GTK3 with a navigation toolbar

Embedding in GTK3 with a navigation toolbar

Embedding in GTK3

Embedding in GTK3

Embedding in Qt

Embedding in Qt

Embedding in Tk

Embedding in Tk

Embedding in wx #2

Embedding in wx #2

Embedding in wx #3

Embedding in wx #3

Embedding in wx #4

Embedding in wx #4

Embedding in wx #5

Embedding in wx #5

Embedding WebAgg

Embedding WebAgg

Fourier Demo WX

Fourier Demo WX

GTK Spreadsheet

GTK Spreadsheet

MathText WX

MathText WX

Matplotlib With Glade 3

Matplotlib With Glade 3

WXcursor Demo

WXcursor Demo

Anchored Box01

Anchored Box01

Anchored Box02

Anchored Box02

Anchored Box03

Anchored Box03

Anchored Box04

Anchored Box04

Annotate Explain

Annotate Explain

Annotate Simple01

Annotate Simple01

Annotate Simple02

Annotate Simple02

Annotate Simple03

Annotate Simple03

Annotate Simple04

Annotate Simple04

Annotate Simple Coord01

Annotate Simple Coord01

Annotate Simple Coord02

Annotate Simple Coord02

Annotate Simple Coord03

Annotate Simple Coord03

Annotate Text Arrow

Annotate Text Arrow

Colormap Normalizations

Colormap Normalizations

Colormap Normalizations Bounds

Colormap Normalizations Bounds

Colormap Normalizations Custom

Colormap Normalizations Custom

TwoSlopeNorm colormap normalization

TwoSlopeNorm colormap normalization

Colormap Normalizations Lognorm

Colormap Normalizations Lognorm

Colormap Normalizations Power

Colormap Normalizations Power

Colormap Normalizations Symlognorm

Colormap Normalizations Symlognorm

Connect Simple01

Connect Simple01

Connectionstyle Demo

Connectionstyle Demo

Custom Boxstyle01

Custom Boxstyle01

Custom Boxstyle02

Custom Boxstyle02

subplot2grid demo

subplot2grid demo

GridSpec demo

GridSpec demo

Nested GridSpecs

Nested GridSpecs

Simple Annotate01

Simple Annotate01

Simple Legend02

Simple Legend02

Buttons

Buttons

Check Buttons

Check Buttons

Cursor

Cursor

Menu

Menu

Multicursor

Multicursor

Polygon Selector Demo

Polygon Selector Demo

Radio Buttons

Radio Buttons

Rectangle Selector

Rectangle Selector

Slider Demo

Slider Demo

Span Selector

Span Selector

Textbox

Textbox

Usage Guide

Usage Guide

Pyplot tutorial

Pyplot tutorial

Sample plots in Matplotlib

Sample plots in Matplotlib

Image tutorial

Image tutorial

The Lifecycle of a Plot

The Lifecycle of a Plot

Artist tutorial

Artist tutorial

Styling with cycler

Styling with cycler

Customizing Figure Layouts Using GridSpec and Other Functions

Customizing Figure Layouts Using GridSpec and Other Functions

Constrained Layout Guide

Constrained Layout Guide

Tight Layout guide

Tight Layout guide

Path Tutorial

Path Tutorial

Path effects guide

Path effects guide

Transformations Tutorial

Transformations Tutorial

Specifying Colors

Specifying Colors

Customized Colorbars Tutorial

Customized Colorbars Tutorial

Colormap Normalization

Colormap Normalization

Choosing Colormaps in Matplotlib

Choosing Colormaps in Matplotlib

Text in Matplotlib Plots

Text in Matplotlib Plots

Text properties and layout

Text properties and layout

© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.2.2/api/_as_gen/matplotlib.figure.Figure.html