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.

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, 2x.png, 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 Introduction to Figures.

Figure#

Figure class#

Figure

The top level container for all the plot elements.

Adding Axes and SubFigures#

Figure.add_axes

Add an Axes to the figure.

Figure.add_subplot

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

Figure.subplots

Add a set of subplots to this figure.

Figure.subplot_mosaic

Build a layout of Axes based on ASCII art or nested lists.

Figure.add_gridspec

Low-level API for creating a GridSpec that has this figure as a parent.

Figure.get_axes

List of Axes in the Figure.

Figure.axes

List of Axes in the Figure.

Figure.delaxes

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

Figure.subfigures

Add a set of subfigures to this figure or subfigure.

Figure.add_subfigure

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

Saving#

Figure.savefig

Save the current figure as an image or vector graphic to a file.

Annotating#

Figure.colorbar

Add a colorbar to a plot.

Figure.legend

Place a legend on the figure.

Figure.text

Add text to figure.

Figure.suptitle

Add a centered super title to the figure.

Figure.get_suptitle

Return the suptitle as string or an empty string if not set.

Figure.supxlabel

Add a centered super xlabel to the figure.

Figure.get_supxlabel

Return the supxlabel as string or an empty string if not set.

Figure.supylabel

Add a centered super ylabel to the figure.

Figure.get_supylabel

Return the supylabel as string or an empty string if not set.

Figure.align_labels

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

Figure.align_xlabels

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

Figure.align_ylabels

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

Figure.align_titles

Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).

Figure.autofmt_xdate

Date ticklabels often overlap, so it is useful to rotate them and right align them.

Figure geometry#

Figure.set_size_inches

Set the figure size in inches.

Figure.get_size_inches

Return the current size of the figure in inches.

Figure.set_figheight

Set the height of the figure in inches.

Figure.get_figheight

Return the figure height in inches.

Figure.set_figwidth

Set the width of the figure in inches.

Figure.get_figwidth

Return the figure width in inches.

Figure.dpi

The resolution in dots per inch.

Figure.set_dpi

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

Figure.get_dpi

Return the resolution in dots per inch as a float.

Subplot layout#

Figure.subplots_adjust

Adjust the subplot layout parameters.

Figure.set_layout_engine

Set the layout engine for this figure.

Figure.get_layout_engine

Discouraged or deprecated#

Figure.tight_layout

Adjust the padding between and around subplots.

Figure.set_tight_layout

[Deprecated] Set whether and how Figure.tight_layout is called when drawing.

Figure.get_tight_layout

Return whether Figure.tight_layout is called when drawing.

Figure.set_constrained_layout

[Deprecated] Set whether constrained_layout is used upon drawing.

Figure.get_constrained_layout

Return whether constrained layout is being used.

Figure.set_constrained_layout_pads

[Deprecated] Set padding for constrained_layout.

Figure.get_constrained_layout_pads

[Deprecated] Get padding for constrained_layout.

Interactive#

Figure.ginput

Blocking call to interact with a figure.

Figure.add_axobserver

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

Figure.waitforbuttonpress

Blocking call to interact with the figure.

Figure.pick

Process a pick event.

Modifying appearance#

Figure.set_frameon

Set the figure's background patch visibility, i.e. whether the figure background will be drawn.

Figure.get_frameon

Return the figure's background patch visibility, i.e. whether the figure background will be drawn.

Figure.set_linewidth

Set the line width of the Figure rectangle.

Figure.get_linewidth

Get the line width of the Figure rectangle.

Figure.set_facecolor

Set the face color of the Figure rectangle.

Figure.get_facecolor

Get the face color of the Figure rectangle.

Figure.set_edgecolor

Set the edge color of the Figure rectangle.

Figure.get_edgecolor

Get the edge color of the Figure rectangle.

Adding and getting Artists#

Figure.add_artist

Add an Artist to the figure.

Figure.get_children

Get a list of artists contained in the figure.

Figure.figimage

Add a non-resampled image to the figure.

Getting and modifying state#

Figure.clear

Clear the figure.

Figure.gca

Get the current Axes.

Figure.sca

Set the current Axes to be a and return a.

Figure.get_tightbbox

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

Figure.get_window_extent

Get the artist's bounding box in display space, ignoring clipping.

Figure.show

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

Figure.set_canvas

Set the canvas that contains the figure

Figure.draw

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

Figure.draw_without_rendering

Draw the figure with no output.

Figure.draw_artist

Draw Artist a only.

SubFigure#

Matplotlib has the concept of a SubFigure, which is a logical figure inside a parent Figure. It has many of the same methods as the parent. See Nested Axes layouts.

(Source code, 2x.png, png)

SubFigure class#

SubFigure

Logical figure that can be placed inside a figure.

Adding Axes and SubFigures#

SubFigure.add_axes

Add an Axes to the figure.

SubFigure.add_subplot

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

SubFigure.subplots

Add a set of subplots to this figure.

SubFigure.subplot_mosaic

Build a layout of Axes based on ASCII art or nested lists.

SubFigure.add_gridspec

Low-level API for creating a GridSpec that has this figure as a parent.

SubFigure.delaxes

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

SubFigure.add_subfigure

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

SubFigure.subfigures

Add a set of subfigures to this figure or subfigure.

Annotating#

SubFigure.colorbar

Add a colorbar to a plot.

SubFigure.legend

Place a legend on the figure.

SubFigure.text

Add text to figure.

SubFigure.suptitle

Add a centered super title to the figure.

SubFigure.get_suptitle

Return the suptitle as string or an empty string if not set.

SubFigure.supxlabel

Add a centered super xlabel to the figure.

SubFigure.get_supxlabel

Return the supxlabel as string or an empty string if not set.

SubFigure.supylabel

Add a centered super ylabel to the figure.

SubFigure.get_supylabel

Return the supylabel as string or an empty string if not set.

SubFigure.align_labels

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

SubFigure.align_xlabels

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

SubFigure.align_ylabels

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

SubFigure.align_titles

Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).

Adding and getting Artists#

SubFigure.add_artist

Add an Artist to the figure.

SubFigure.get_children

Get a list of artists contained in the figure.

Modifying appearance#

SubFigure.set_frameon

Set the figure's background patch visibility, i.e. whether the figure background will be drawn.

SubFigure.get_frameon

Return the figure's background patch visibility, i.e. whether the figure background will be drawn.

SubFigure.set_linewidth

Set the line width of the Figure rectangle.

SubFigure.get_linewidth

Get the line width of the Figure rectangle.

SubFigure.set_facecolor

Set the face color of the Figure rectangle.

SubFigure.get_facecolor

Get the face color of the Figure rectangle.

SubFigure.set_edgecolor

Set the edge color of the Figure rectangle.

SubFigure.get_edgecolor

Get the edge color of the Figure rectangle.

Passthroughs#

SubFigure.set_dpi

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

SubFigure.get_dpi

Return the resolution of the parent figure in dots-per-inch as a float.

FigureBase parent class#

class matplotlib.figure.FigureBase(**kwargs)[source]#

Base class for Figure and SubFigure containing the methods that add artists to the figure or subfigure, create Axes, etc.

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

float 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

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

facecolor or fc

color

figure

Figure or SubFigure

forward_navigation_events

bool or "auto"

frame_on

bool

gid

str

in_layout

bool

label

object

mouseover

bool

navigate

bool

navigate_mode

unknown

path_effects

list of AbstractPathEffect

picker

None or bool or float or callable

position

[left, bottom, width, height] or Bbox

prop_cycle

Cycler

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

(lower: float, upper: float)

xinverted

unknown

xlabel

str

xlim

(left: float, right: float)

xmargin

float greater than -0.5

xscale

unknown

xticklabels

unknown

xticks

unknown

ybound

(lower: float, upper: float)

yinverted

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_gridspec(nrows=1, ncols=1, **kwargs)[source]#

Low-level API for creating a GridSpec that has this figure as a parent.

This is a low-level API, allowing you to create a gridspec and subsequently add subplots based on the gridspec. Most users do not need that freedom and should use the higher-level methods subplots or subplot_mosaic.

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

float 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

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

facecolor or fc

color

figure

Figure or SubFigure

forward_navigation_events

bool or "auto"

frame_on

bool

gid

str

in_layout

bool

label

object

mouseover

bool

navigate

bool

navigate_mode

unknown

path_effects

list of AbstractPathEffect

picker

None or bool or float or callable

position

[left, bottom, width, height] or Bbox

prop_cycle

Cycler

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

(lower: float, upper: float)

xinverted

unknown

xlabel

str

xlim

(left: float, right: float)

xmargin

float greater than -0.5

xscale

unknown

xticklabels

unknown

xticks

unknown

ybound

(lower: float, upper: float)

yinverted

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.

Notes

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

align_titles(axs=None)[source]#

Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).

Alignment persists for draw events after this is called.

Parameters:
axslist of Axes

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

Notes

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

Examples

Example with titles:

fig, axs = plt.subplots(1, 2)
axs[0].set_aspect('equal')
axs[0].set_title('Title 0')
axs[1].set_title('Title 1')
fig.align_titles()
align_xlabels(axs=None)[source]#

Align the xlabels of subplots in the same subplot row 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 all Axes in 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)
axs[0].tick_params(axis='x', 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 all Axes in 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.

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.colorizer.ColorizingArtist (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 colorizer.ColorizingArtist "on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.

cr = colorizer.Colorizer(norm=norm, cmap=cmap)
fig.colorbar(colorizer.ColorizingArtist(cr), ax=ax)
caxAxes, optional

Axes into which the colorbar will be drawn. If None, then a new Axes is created and the space for it will be stolen from the Axes(s) specified in ax.

axAxes or iterable or numpy.ndarray of Axes, optional

The one or more parent Axes from which space for a new colorbar Axes will be stolen. This parameter is only used if cax is not set.

Defaults to the Axes that contains the mappable used to create the colorbar.

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.

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. The size of each region is determined by the spacing parameter. Normally only useful for indexed colors (i.e. norm=NoNorm()) or other unusual circumstances.

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.

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 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) render 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, {}
delaxes(ax)[source]#

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

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.

property figure#

The root Figure. To get the parent of a SubFigure, use the get_figure method.

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

Get a list of artists contained in the figure.

get_default_bbox_extra_artists()[source]#

Return a list of Artists typically used in Figure.get_tightbbox.

get_edgecolor()[source]#

Get the edge color of the Figure rectangle.

get_facecolor()[source]#

Get the face color of the Figure rectangle.

get_figure(root=None)[source]#

Return the Figure or SubFigure instance the (Sub)Figure belongs to.

Parameters:
rootbool, default=True

If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.

Deprecated since version 3.10: From version 3.12 root will default to False.

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

Get the line width of the Figure rectangle.

get_suptitle()[source]#

Return the suptitle as string or an empty string if not set.

get_supxlabel()[source]#

Return the supxlabel as string or an empty string if not set.

get_supylabel()[source]#

Return the supylabel as string or an empty string if not set.

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_window_extent(renderer=None)[source]#

Get the artist's bounding box in display space, ignoring clipping.

The bounding box's width and height are non-negative.

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

Warning

The extent can change due to any changes in the transform stack, such as changing the Axes limits, the figure size, the canvas used (as is done when saving a figure), or the DPI.

Relying on a once-retrieved window extent can lead to unexpected behavior in various cases such as interactive figures being resized or moved to a screen with different dpi, or figures that look fine on screen render incorrectly when saved to file.

To get accurate results you may need to manually call savefig or draw_without_rendering to have Matplotlib compute the rendered size.

Parameters:
rendererRendererBase, optional

Renderer used to draw the figure (i.e. fig.canvas.get_renderer()).

See also

Artist.get_tightbbox

Get the artist bounding box, taking clipping into account.

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

Place a legend on the figure.

Call signatures:

legend()
legend(handles, labels)
legend(handles=handles)
legend