matplotlib / 3.7 / figure_api.html

matplotlib.figure

matplotlib.figure implements the following classes:

Figure

Top level Artist, which holds all plot elements. Many methods are implemented in FigureBase.

SubFigure

A logical figure inside a figure, usually added to a figure (or parent SubFigure) with Figure.add_subfigure or Figure.subfigures methods (provisional API v3.4).

SubplotParams

Control the default spacing between subplots.

Figures are typically created using pyplot methods figure, subplots, and subplot_mosaic.

fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
                       layout='constrained')
fig.suptitle('Figure')
ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')

(Source code, png)

../_images/figure_api-1.png

Some situations call for directly instantiating a Figure class, usually inside an application of some sort (see Embedding Matplotlib in graphical user interfaces for a list of examples) . More information about Figures can be found at Creating, viewing, and saving Matplotlib Figures.

classmatplotlib.figure.Figure(figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs)[source]

The top level container for all the plot elements.

Attributes:
patch

The Rectangle instance representing the figure background patch.

suppressComposite

For multiple 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)

Whether to use the tight layout mechanism. See set_tight_layout.

Discouraged

The use of this parameter is discouraged. Please use layout='tight' instead for the common case of tight_layout=True and use set_tight_layout otherwise.

constrained_layoutbool, default: rcParams["figure.constrained_layout.use"] (default: False)

This is equal to layout='constrained'.

Discouraged

The use of this parameter is discouraged. Please use layout='constrained' instead.

layout{'constrained', 'compressed', 'tight', 'none', LayoutEngine, None}, default: None

The layout mechanism for positioning of plot elements to avoid overlapping Axes decorations (labels, ticks, etc). Note that layout managers can have significant performance penalties.

  • 'constrained': The constrained layout solver adjusts axes sizes to avoid overlapping axes decorations. Can handle complex plot layouts and colorbars, and is thus recommended.

    See Constrained Layout Guide for examples.

  • 'compressed': uses the same algorithm as 'constrained', but removes extra space between fixed-aspect-ratio Axes. Best for simple grids of axes.
  • 'tight': Use the tight layout mechanism. This is a relatively simple algorithm that adjusts the subplot parameters so that decorations do not overlap. See Figure.set_tight_layout for further details.
  • 'none': Do not use a layout engine.
  • A LayoutEngine instance. Builtin layout classes are ConstrainedLayoutEngine and TightLayoutEngine, more easily accessible by 'constrained' and 'tight'. Passing an instance allows third parties to provide their own layout engine.

If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults rcParams["figure.autolayout"] (default: False) and rcParams["figure.constrained_layout.use"] (default: False).

Other Parameters:
**kwargsFigure properties, optional

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 and two offsets from the bottom left corner of the image

alpha

scalar or None

animated

bool

canvas

FigureCanvas

clip_box

Bbox

clip_on

bool

clip_path

Patch or (Path, Transform) or None

constrained_layout

unknown

constrained_layout_pads

unknown

dpi

float

edgecolor

color

facecolor

color

figheight

float

figure

Figure

figwidth

float

frameon

bool

gid

str

in_layout

bool

label

object

layout_engine

unknown

linewidth

number

mouseover

bool

path_effects

AbstractPathEffect

picker

None or bool or float or callable

rasterized

bool

size_inches

(float, float) or float

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

tight_layout

unknown

transform

Transform

url

str

visible

bool

zorder

float

add_artist(artist, clip=False)[source]

Add an Artist to the figure.

Usually artists are added to Axes objects using Axes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead.

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

clipbool, default: False

Whether the added artist should be clipped by the figure patch.

Returns:
Artist

The added artist.

add_axes(*args, **kwargs)[source]

Add an Axes to the figure.

Call signatures:

add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
Parameters:
recttuple (left, bottom, width, height)

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.

polarbool, default: False

If True, equivalent to projection='polar'.

axes_classsubclass type of Axes, optional

The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.

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:
Axes, or a subclass of Axes

The returned axes class depends on the projection used. It is Axes if rectilinear projection is used and projections.polar.PolarAxes if polar projection is 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 and two offsets from the bottom left corner of the image

alpha

scalar or None

anchor

(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}

animated

bool

aspect

{'auto', 'equal'} or float

autoscale_on

bool

autoscalex_on

unknown

autoscaley_on

unknown

axes_locator

Callable[[Axes, Renderer], Bbox]

axisbelow

bool or 'line'

box_aspect

float or None

clip_box

Bbox

clip_on

bool

clip_path

Patch or (Path, Transform) or None

facecolor or fc

color

figure

Figure

frame_on

bool

gid

str

in_layout

bool

label

object

mouseover

bool

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

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

subplotspec

unknown

title

str

transform

Transform

url

str

visible

bool

xbound

unknown

xlabel

str

xlim

(bottom: float, top: float)

xmargin

float greater than -0.5

xscale

unknown

xticklabels

unknown

xticks

unknown

ybound

unknown

ylabel

str

ylim

(bottom: float, top: float)

ymargin

float greater than -0.5

yscale

unknown

yticklabels

unknown

yticks

unknown

zorder

float

Notes

In rare circumstances, add_axes may be called with a single argument, an 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)
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(func)[source]

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

add_callback(func)[source]

Add a callback function that will be called whenever one of the Artist's properties changes.

Parameters:
funccallable

The callback function. It must have the signature:

def func(artist: Artist) -> Any

where artist is the calling Artist. Return values may exist but are ignored.

Returns:
int

The observer id associated with the callback. This id can be used for removing the callback with remove_callback later.

See also

remove_callback
add_gridspec(nrows=1, ncols=1, **kwargs)[source]

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

Parameters:
nrowsint, default: 1

Number of rows in grid.

ncolsint, default: 1

Number of columns in grid.

Returns:
GridSpec
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_subfigure(subplotspec, **kwargs)[source]

Add a SubFigure to the figure as part of a subplot arrangement.

Parameters:
subplotspecgridspec.SubplotSpec

Defines the region in a parent gridspec where the subfigure will be placed.

Returns:
SubFigure
Other Parameters:
**kwargs

Are passed to the SubFigure object.

add_subplot(*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:
*argsint, (int, int, index), or SubplotSpec, default: (1, 1, 1)

The position of the subplot described by one of

  • Three integers (nrows, ncols, index). 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. index can also be a two-tuple specifying the (first, last) indices (1-based, and including last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2)) makes a subplot that spans the upper 2/3 of the figure.
  • A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that this can only be used if there are no more than 9 subplots.
  • A SubplotSpec.

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.

polarbool, default: False

If True, equivalent to projection='polar'.

axes_classsubclass type of Axes, optional

The axes.Axes subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.

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:
Axes

The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as projections.polar.PolarAxes for polar projections.

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 and two offsets from the bottom left corner of the image

alpha

scalar or None

anchor

(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}

animated

bool

aspect

{'auto', 'equal'} or float

autoscale_on

bool

autoscalex_on

unknown

autoscaley_on

unknown

axes_locator

Callable[[Axes, Renderer], Bbox]

axisbelow

bool or 'line'

box_aspect

float or None

clip_box

Bbox

clip_on

bool

clip_path

Patch or (Path, Transform) or None

facecolor or fc

color

figure

Figure

frame_on

bool

gid

str

in_layout

bool

label

object

mouseover

bool

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

sketch_params

(scale: float, length: float, randomness: float)

snap

bool or None

subplotspec

unknown

title

str

transform

Transform

url

str

visible

bool

xbound

unknown

xlabel

str

xlim

(bottom: float, top: float)

xmargin

float greater than -0.5

xscale

unknown

xticklabels

unknown

xticks

unknown

ybound

unknown

ylabel

str

ylim

(bottom: float, top: float)

ymargin

float greater than -0.5

yscale

unknown

yticklabels

unknown

yticks

unknown

zorder

float

Examples

fig = plt.figure()

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

fig.add_subplot(232, frameon=False)  # subplot with no frame
fig.add_subplot(233, projection='polar')  # polar subplot
fig.add_subplot(234, sharex=ax1)  # subplot sharing x-axis with ax1
fig.add_subplot(235, facecolor="red")  # red subplot

ax1.remove()  # delete ax1 from the figure
fig.add_subplot(ax1)  # add ax1 back to the figure
align_labels(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(axs=None)[source]

Align the xlabels 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(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(bottom=0.2, rotation=30, ha='right', which='major')[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 x-axis 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:
bottomfloat, default: 0.2

The bottom of the subplots for subplots_adjust.

rotationfloat, default: 30 degrees

The rotation angle of the xtick labels in degrees.

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

The horizontal alignment of the xticklabels.

which{'major', 'minor', 'both'}, default: 'major'

Selects which ticklabels to rotate.

propertyaxes

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, add_subplot or delaxes to add or remove an Axes.

Note: The Figure.axes property and get_axes method are equivalent.

propertycallbacks[source]
clear(keep_observers=False)[source]

Clear the figure.

Parameters:
keep_observersbool, default: False

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

clf(keep_observers=False)[source]

[Discouraged] Alias for the clear() method.

Discouraged

The use of clf() is discouraged. Use clear() instead.

Parameters:
keep_observersbool, default: False

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

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

Add a colorbar to a plot.

Parameters:
mappable

The matplotlib.cm.ScalarMappable (i.e., AxesImage, 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, optional

Axes into which the colorbar will be drawn.

axAxes or iterable or numpy.ndarray of Axes, optional

One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.

use_gridspecbool, optional

If cax is None, a new cax is created as an instance of Axes. If ax is positioned with a subplotspec and use_gridspec is True, then cax is also positioned with a subplotspec.

Returns:
colorbarColorbar
Other Parameters:
locationNone or {'left', 'right', 'top', 'bottom'}

The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.

orientationNone or {'vertical', 'horizontal'}

The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.

fractionfloat, default: 0.15

Fraction of original axes to use for colorbar.

shrinkfloat, default: 1.0

Fraction by which to multiply the size of the colorbar.

aspectfloat, default: 20

Ratio of long to short dimensions.

padfloat, default: 0.05 if vertical, 0.15 if horizontal

Fraction of original axes between colorbar and new image axes.

anchor(float, float), optional

The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.

panchor(float, float), or False, optional

The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.

extend{'neither', 'both', 'min', 'max'}

Make pointed end(s) for out-of-range values (unless 'neither'). 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 will 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.

extendrectbool

If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.

spacing{'uniform', 'proportional'}

For discrete colorbars (BoundaryNorm or contours), 'uniform' gives each color the same space; 'proportional' makes the space proportional to the data interval.

ticksNone or list of ticks or Locator

If None, ticks are determined automatically from the input.

formatNone or str or Formatter

If None, ScalarFormatter is used. Format strings, e.g., "%4.2e" or "{x:.2e}", are supported. An alternative Formatter may be given instead.

drawedgesbool

Whether to draw lines at color boundaries.

labelstr

The label on the colorbar's long axis.

boundaries, valuesNone or a sequence

If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. Normally only useful for indexed colors (i.e. norm=NoNorm()) or other unusual circumstances.

Notes

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(mouseevent)[source]

Test whether the mouse event occurred on the figure.

Returns:
bool, {}
convert_xunits(x)[source]

Convert x using the unit type of the xaxis.

If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.

convert_yunits(y)[source]

Convert y using the unit type of the yaxis.

If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.

delaxes(ax)[source]

Remove the Axes ax from the figure; update the current Axes.

propertydpi

The resolution in dots per inch.

draw(renderer)[source]

Draw the Artist (and its children) using the given renderer.

This has no effect if the artist is not visible (Artist.get_visible returns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

draw_artist(a)[source]

Draw Artist a only.

draw_without_rendering()[source]

Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text).

execute_constrained_layout(renderer=None)[source]

[Deprecated] Use layoutgrid to determine pos positions within Axes.

See also set_constrained_layout_pads.

Returns:
layoutgridprivate debugging object

Notes

Deprecated since version 3.6: Use figure.get_layout_engine().execute() instead.

figimage(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:

  • (M, N): an image with scalar data. Color-mapping is controlled by cmap, norm, vmin, and vmax.
  • (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
  • (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.
xo, yoint

The x/y image offset in pixels.

alphaNone or float

The alpha blending value.

cmapstr or Colormap, default: rcParams["image.cmap"] (default: 'viridis')

The Colormap instance or registered colormap name used to map scalar data to colors.

This parameter is ignored if X is RGB(A).

normstr or Normalize, optional

The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.

If given, this can be one of the following:

This parameter is ignored if X is RGB(A).

vmin, vmaxfloat, optional

When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a str norm name together with vmin/vmax is acceptable).

This parameter is ignored if X is RGB(A).

origin{'upper', 'lower'}, default: rcParams["image.origin"] (default: 'upper')

Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes.

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()
findobj(match=None, include_self=True)[source]

Find artist objects.

Recursively find all Artist instances contained in the artist.

Parameters:
match

A filter criterion for the matches. This can be

  • None: Return all objects contained in artist.
  • A function with signature def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True.
  • A class instance: e.g., Line2D. The result will only contain artists of this class or its subclasses (isinstance check).
include_selfbool

Include self in the list to be checked for a match.

Returns:
list of Artist
format_cursor_data(data)[source]

Return a string representation of data.

Note

This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.

The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter.

See also

get_cursor_data
propertyframeon

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

gca()[source]

Get the current Axes.

If there is currently no Axes on this Figure, a new one is created using Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whether figure.axes is empty. To test whether there is currently a Figure on the pyplot figure stack, check whether pyplot.get_fignums() is empty.)

get_agg_filter()[source]

Return filter function to be used for agg filter.

get_alpha()[source]

Return the alpha value used for blending - not supported on all backends.

get_animated()[source]

Return whether the artist is animated.

get_axes()[source]

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, add_subplot or delaxes to add or remove an Axes.

Note: The Figure.axes property and get_axes method are equivalent.

get_children()[source]

Get a list of artists contained in the figure.

get_clip_box()[source]

Return the clipbox.

get_clip_on()[source]

Return whether the artist uses clipping.

get_clip_path()[source]

Return the clip path.

get_constrained_layout()[source]

Return whether constrained layout is being used.

See Constrained Layout Guide.

get_constrained_layout_pads(relative=False)[source]

[Deprecated] Get padding for constrained_layout.

Returns a list of w_pad, h_pad in inches and wspace and hspace as fractions of the subplot. All values are None if constrained_layout is not used.

See Constrained Layout Guide.

Parameters:
relativebool

If True, then convert from inches to figure relative.

Notes

Deprecated since version 3.6: Use fig.get_layout_engine().get() instead.

get_cursor_data(event)[source]

Return the cursor data for a given event.

Note

This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.

Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.

Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data can convert the data to a string representation.

The only current use case is displaying the z-value of an AxesImage in the status bar of a plot window, while moving the mouse.

Parameters:
eventmatplotlib.backend_bases.MouseEvent
get_default_bbox_extra_artists()[source]
get_dpi()[source]

Return the resolution in dots per inch as a float.

get_edgecolor()[source]

Get the edge color of the Figure rectangle.

get_facecolor()[source]

Get the face color of the Figure rectangle.

get_figheight()[source]

Return the figure height in inches.

get_figure()[source]

Return the Figure instance the artist belongs to.

get_figwidth()[source]

Return the figure width in inches.

get_frameon()[source]

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

get_gid()[source]

Return the group id.

get_in_layout()[source]

Return boolean flag, True if artist is included in layout calculations.

E.g. Constrained Layout Guide, Figure.tight_layout(), and fig.savefig(fname, bbox_inches='tight').

get_label()[source]

Return the label used for this artist in the legend.

get_layout_engine()[source]
get_linewidth()[source]

Get the line width of the Figure rectangle.

get_mouseover()[source]

Return whether this artist is queried for custom context information when the mouse cursor moves over it.

get_path_effects()[source]
get_picker()[source]

Return the picking behavior of the artist.

The possible values are described in set_picker.

See also

set_picker, pickable, pick
get_rasterized()[source]

Return whether the artist is to be rasterized.

get_size_inches()[source]

Return the current size of the figure in inches.

Returns:
ndarray

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

Notes

The size in pixels can be obtained by multiplying with Figure.dpi.

get_sketch_params()[source]

Return the sketch parameters for the artist.

Returns:
tuple or None

A 3-tuple with the following elements:

  • scale: The amplitude of the wiggle perpendicular to the source line.
  • length: The length of the wiggle along the line.
  • randomness: The scale factor by which the length is shrunken or expanded.

Returns None if no sketch parameters were set.

get_snap()[source]

Return the snap setting.

See set_snap for details.

get_tight_layout()[source]

Return whether tight_layout is called when drawing.

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

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

Note that FigureBase differs from all other artists, which return their Bbox in pixels.

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

Parameters:
rendererRendererBase subclass

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:
BboxBase

containing the bounding box (in figure inches).

get_transform()[source]

Return the Transform instance used by this artist.

get_transformed_clip_path_and_affine()[source]

Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.

get_url()[source]

Return the url.

get_visible()[source]

Return the visibility.

get_window_extent(renderer=None, *args, **kwargs)[source]

Get the artist's bounding box in display space.

The bounding box' width and height are nonnegative.

Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0.

Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.

get_zorder()[source]

Return the artist's zorder.

ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)[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.

Parameters:
nint, default: 1

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

timeoutfloat, default: 30 seconds

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

show_clicksbool, default: True

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

mouse_addMouseButton or None, default: MouseButton.LEFT

Mouse button used to add points.

mouse_popMouseButton or None, default: