matplotlib.figure#

matplotlib.figure implements the following classes:

Figure

Top levelArtist, which holds all plot elements.Many methods are implemented inFigureBase.

SubFigure

A logical figure inside a figure, usually added to a figure (or parentSubFigure)withFigure.add_subfigure orFigure.subfigures methods.

Figures are typically created using pyplot methodsfigure,subplots, andsubplot_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')

(Sourcecode,2x.png,png)

Some situations call for directly instantiating aFigure class,usually inside an application of some sort (seeEmbedding Matplotlib in graphical user interfaces for alist of examples) . More information about Figures can be found atIntroduction to Figures.

Figure#

Figure class#

Figure

The top level container for all the plot elements.

Adding Axes and SubFigures#

Figure.add_axes

Add anAxes to the figure.

Figure.add_subplot

Add anAxes 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 aGridSpec 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 theAxesax from the figure; update the current Axes.

Figure.subfigures

Add a set of subfigures to this figure or subfigure.

Figure.add_subfigure

Add aSubFigure 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 howFigure.tight_layout is called when drawing.

Figure.get_tight_layout

Return whetherFigure.tight_layout is called when drawing.

Figure.set_constrained_layout

[Deprecated] Set whetherconstrained_layout is used upon drawing.

Figure.get_constrained_layout

Return whether constrained layout is being used.

Figure.set_constrained_layout_pads

[Deprecated] Set padding forconstrained_layout.

Figure.get_constrained_layout_pads

[Deprecated] Get padding forconstrained_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 anArtist 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 bea and returna.

Figure.get_tightbbox

Return a (tight) bounding box of the figurein inches.

Figure.get_window_extent

Get the artist's bounding box in display space.

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

DrawArtista only.

SubFigure#

Matplotlib has the concept of aSubFigure, which is a logical figure insidea parentFigure. It has many of the same methods as the parent. SeeNested Axes layouts.

(Sourcecode,2x.png,png)

SubFigure class#

SubFigure

Logical figure that can be placed inside a figure.

Adding Axes and SubFigures#

SubFigure.add_axes

Add anAxes to the figure.

SubFigure.add_subplot

Add anAxes 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 aGridSpec that has this figure as a parent.

SubFigure.delaxes

Remove theAxesax from the figure; update the current Axes.

SubFigure.add_subfigure

Add aSubFigure 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 anArtist 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#

classmatplotlib.figure.FigureBase(**kwargs)[source]#

Base class forFigure andSubFigure containing the methods that addartists to the figure or subfigure, create Axes, etc.

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

Add anArtist to the figure.

Usually artists are added toAxes objects usingAxes.add_artist; this method can be used in the rare cases whereone needs to add artists directly to the figure instead.

Parameters:
artistArtist

The artist to add to the figure. If the added artist has notransform previously set, its transform will be set tofigure.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 anAxes 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 newAxes. All quantities are in fractions of figure width andheight.

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

The projection type of theAxes.str is the name ofa custom projection, seeprojections. The defaultNone results in a 'rectilinear' projection.

polarbool, default: False

If True, equivalent to projection='polar'.

axes_classsubclass type ofAxes, optional

Theaxes.Axes subclass that is instantiated. This parameteris incompatible withprojection andpolar. Seeaxisartist for examples.

sharex, shareyAxes, optional

Share the x or yaxis with sharex and/or sharey.The axis will have the same limits, ticks, and scale as the axisof the shared Axes.

labelstr

A label for the returned Axes.

Returns:
Axes, or a subclass ofAxes

The returned Axes class depends on the projection used. It isAxes if rectilinear projection is used andprojections.polar.PolarAxes if polar projection is used.

Other Parameters:
**kwargs

This method also takes the keyword arguments forthe returned Axes class. The keyword arguments for therectilinear Axes classAxes can be found inthe following table but there might also be other keywordarguments if another projection is used, see the actual Axesclass.

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 orfc

color

figure

Figure orSubFigure

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 ofAbstractPathEffect

picker

None or bool or float or callable

position

[left, bottom, width, height] orBbox

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 singleargument, an Axes instance already created in the present figure butnot in the figure's list of Axes.

Examples

Some simple examples:

rect=l,b,w,hfig=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 aGridSpec that has this figure as a parent.

This is a low-level API, allowing you to create a gridspec andsubsequently add subplots based on the gridspec. Most users donot need that freedom and should use the higher-level methodssubplots orsubplot_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 toGridSpec.

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 aSubFigure to the figure as part of a subplot arrangement.

Parameters:
subplotspecgridspec.SubplotSpec

Defines the region in a parent gridspec where the subfigure willbe placed.

Returns:
SubFigure
Other Parameters:
**kwargs

Are passed to theSubFigure object.

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

Add anAxes 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), orSubplotSpec, default: (1, 1, 1)

The position of the subplot described by one of

  • Three integers (nrows,ncols,index). The subplot willtake theindex position on a grid withnrows rows andncols columns.index starts at 1 in the upper left cornerand increases to the right.index can also be a two-tuplespecifying the (first,last) indices (1-based, and includinglast) 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 givenseparately as three single-digit integers, i.e.fig.add_subplot(235) is the same asfig.add_subplot(2,3,5). Note that this can only be usedif there are no more than 9 subplots.

  • ASubplotSpec.

In rare circumstances,add_subplot may be called with a singleargument, a subplot Axes instance already created in thepresent 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 thename of a custom projection, seeprojections. Thedefault None results in a 'rectilinear' projection.

polarbool, default: False

If True, equivalent to projection='polar'.

axes_classsubclass type ofAxes, optional

Theaxes.Axes subclass that is instantiated. This parameteris incompatible withprojection andpolar. Seeaxisartist for examples.

sharex, shareyAxes, optional

Share the x or yaxis with sharex and/or sharey.The axis will have the same limits, ticks, and scale as the axisof the shared Axes.

labelstr

A label for the returned Axes.

Returns:
Axes

The Axes of the subplot. The returned Axes can actually be aninstance of a subclass, such asprojections.polar.PolarAxes forpolar projections.

Other Parameters:
**kwargs

This method also takes the keyword arguments for the returned Axesbase class; except for thefigure argument. The keyword argumentsfor the rectilinear base classAxes can be found inthe following table but there might also be other keywordarguments 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 orfc

color

figure

Figure orSubFigure

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 ofAbstractPathEffect

picker

None or bool or float or callable

position

[left, bottom, width, height] orBbox

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 generalfig.add_subplot(232,frameon=False)# subplot with no framefig.add_subplot(233,projection='polar')# polar subplotfig.add_subplot(234,sharex=ax1)# subplot sharing x-axis with ax1fig.add_subplot(235,facecolor="red")# red subplotax1.remove()# delete ax1 from the figurefig.add_subplot(ax1)# add ax1 back to the figure
align_labels(axs=None)[source]#

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

Alignment persists for draw events after this is called.

Parameters:
axslist ofAxes

Optional list (orndarray) ofAxesto align the labels.Default is to align all Axes on the figure.

Notes

This assumes that all Axes inaxs are from the sameGridSpec,so that theirSubplotSpec positions correspond to figure positions.

align_titles(axs=None)[source]#

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

Alignment persists for draw events after this is called.

Parameters:
axslist ofAxes

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

Notes

This assumes that all Axes inaxs are from the sameGridSpec,so that theirSubplotSpec 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 labelalignment is being done automatically (i.e. the label position isnot 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 thatalso have their label on the bottom and that have the samebottom-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 ofAxes

Optional list of (orndarray)Axesto align the xlabels.Default is to align all Axes on the figure.

Notes

This assumes that all Axes inaxs are from the sameGridSpec,so that theirSubplotSpec 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 labelalignment is being done automatically (i.e. the label position isnot 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 thatalso have their label on the left and that have the sameleft-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 ofAxes

Optional list (orndarray) ofAxesto align the ylabels.Default is to align all Axes on the figure.

Notes

This assumes that all Axes inaxs are from the sameGridSpec,so that theirSubplotSpec 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 themand right align them. Also, a common use case is a number ofsubplots with shared x-axis where the x-axis is date data. Theticklabels are often long, and it helps to rotate them on thebottom subplot and turn them off on other subplots, as well asturn off xlabels.

Parameters:
bottomfloat, default: 0.2

The bottom of the subplots forsubplots_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

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

clf(keep_observers=False)[source]#

[Discouraged] Alias for theclear() method.

Discouraged

The use ofclf() is discouraged. Useclear() instead.

Parameters:
keep_observersbool, default: False

Setkeep_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

Thematplotlib.cm.ScalarMappable (i.e.,AxesImage,ContourSet, etc.) described by this colorbar. This argument ismandatory for theFigure.colorbar method but optional for thepyplot.colorbar function, which sets the default to the currentimage.

Note that one can create aScalarMappable "on-the-fly" togenerate 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. IfNone, then a newAxes is created and the space for it will be stolen from the Axes(s)specified inax.

axAxes or iterable ornumpy.ndarray of Axes, optional

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

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

use_gridspecbool, optional

Ifcax isNone, a newcax is created as an instance ofAxes. Ifax is positioned with a subplotspec anduse_gridspecisTrue, thencax 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 Axesis created. It also determines theorientation of the colorbar(colorbars on the left and right are vertical, colorbars at the topand bottom are horizontal). If None, the location will come from theorientation if it is set (vertical colorbars on the right, horizontalones at the bottom), or default to 'right' iforientation is unset.

orientationNone or {'vertical', 'horizontal'}

The orientation of the colorbar. It is preferable to set thelocationof the colorbar, as that also determines theorientation; passingincompatible values forlocation andorientation 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), orFalse, optional

The anchor point of the colorbar parent Axes. IfFalse, the parentaxes' 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 areset for a given colormap using the colormap set_under and set_over methods.

extendfrac{None, 'auto', length, lengths}

If set toNone, both the minimum and maximum triangular colorbarextensions will have a length of 5% of the interior colorbar length (thisis the default setting).

If set to 'auto', makes the triangular colorbar extensions the same lengthsas the interior boxes (whenspacing is set to 'uniform') or the samelengths as the respective adjacent interior boxes (whenspacing is set to'proportional').

If a scalar, indicates the length of both the minimum and maximumtriangular colorbar extensions as a fraction of the interior colorbarlength. A two-element sequence of fractions may also be given, indicatingthe lengths of the minimum and maximum colorbar extensions respectively asa fraction of the interior colorbar length.

extendrectbool

IfFalse the minimum and maximum colorbar extensions will be triangular(the default). IfTrue 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 alternativeFormatter 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 thanboundaries. Foreach region delimited by adjacent entries inboundaries, the color mappedto the corresponding value invalues will be used. The size of eachregion is determined by thespacing parameter.Normally only useful for indexed colors (i.e.norm=NoNorm()) or otherunusual circumstances.

spacing{'uniform', 'proportional'}

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

Notes

Ifmappable is aContourSet, itsextend kwarg isincluded automatically.

Theshrink kwarg provides a simple way to scale the colorbar withrespect to the Axes. Note that ifcax is specified, it determines thesize of the colorbar, andshrink andaspect are ignored.

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

It is known that some vector graphics viewers (svg and pdf) renderwhite gaps between segments of the colorbar. This is due to bugs inthe viewers, not Matplotlib. As a workaround, the colorbar can berendered 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 theAxesax 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_visiblereturns False).

Parameters:
rendererRendererBase subclass.

Notes

This method is overridden in the Artist subclasses.

propertyfigure#

The rootFigure. To get the parent of aSubFigure, use theget_figure method.

propertyframeon#

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

gca()[source]#

Get the current Axes.

If there is currently no Axes on this Figure, a new one is createdusingFigure.add_subplot. (To test whether there is currently anAxes on a Figure, check whetherfigure.axes is empty. To testwhether there is currently a Figure on the pyplot figure stack, checkwhetherpyplot.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 inFigure.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 theFigure orSubFigure 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.12root will default to False.

get_frameon()[source]#

Return the figure's background patch visibility, i.e.whether the figure background will be drawn. Equivalent toFigure.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 figurein inches.

Note thatFigureBase differs from all other artists, which returntheirBbox in pixels.

Artists that haveartist.set_in_layout(False) are not includedin the bbox.

Parameters:
rendererRendererBase subclass

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

bbox_extra_artistslist ofArtist orNone

List of artists to include in the tight bounding box. IfNone (default), then all artist children of each Axes areincluded 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.

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 boundingbox at 0, 0.

Warning

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

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

To get accurate results you may need to manually callmatplotlib.figure.Figure.savefig ormatplotlib.figure.Figure.draw_without_rendering to have Matplotlibcompute the rendered size.

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

Place a legend on the figure.

Call signatures:

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

The call signatures correspond to the following different ways to usethis method:

1. Automatic detection of elements to be shown in the legend

The elements to be added to the legend are automatically determined,when you do not pass in any extra arguments.

In this case, the labels are taken from the artist. You can specifythem either at artist creation or by calling theset_label() method on the artist:

ax.plot([1,2,3],label='Inline label')fig.legend()

or:

line,=ax.plot([1,2,3])line.set_label('Label via method')fig.legend()

Specific lines can be excluded from the automatic legend elementselection by defining a label starting with an underscore.This is default for all artists, so callingFigure.legend withoutany arguments and without setting the labels manually will result inno legend being drawn.

2. Explicitly listing the artists and labels in the legend

For full control of which artists have a legend entry, it is possibleto pass an iterable of legend artists followed by an iterable oflegend labels respectively:

fig.legend([line1,line2,line3],['label1','label2','label3'])

3. Explicitly listing the artists in the legend

This is similar to 2, but the labels are taken from the artists'label properties. Example:

line1,=ax1.plot([1,2,3],label='label1')line2,=ax2.plot([1,2,3],label='label2')fig.legend(handles=[line1,line2])

4. Labeling existing plot elements

Discouraged

This call signature is discouraged, because the relation betweenplot elements and labels is only implicit by their order and caneasily be mixed up.

To make a legend for all artists on all Axes, call this function withan iterable of strings, one for each legend item. For example:

fig,(ax1,ax2)=plt.subplots(1,2)ax1.plot([1,3,5],color='blue')ax2.plot([2,4,6],color='red')fig.legend(['the blues','the reds'])
Parameters:
handleslist ofArtist, optional

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

The length of handles and labels should be the same in thiscase. 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 withhandles, if you need full control on whatis shown in the legend and the automatic mechanism described aboveis not sufficient.

Returns:
Legend
Other Parameters:
locstr or pair of floats, default: 'upper right'

The location of the legend.

The strings'upperleft','upperright','lowerleft','lowerright' place the legend at the corresponding corner of thefigure.

The strings'uppercenter','lowercenter','centerleft','centerright' place the legend at the center of the corresponding edgeof the figure.

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

The location can also be a 2-tuple giving the coordinates of the lower-leftcorner of the legend in figure coordinates (in which casebbox_to_anchorwill be ignored).

For back-compatibility,'centerright' (but no other location) can alsobe spelled'right', and each "string" location can also be given as anumeric value:

Location String

Location Code

'best' (Axes only)

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

If a figure is using the constrained layout manager, the string codesof theloc keyword argument can get better layout behaviour using theprefix 'outside'. There is ambiguity at the corners, so 'outsideupper right' will make space for the legend above the rest of theaxes in the layout, and 'outside right upper' will make space on theright side of the layout. In addition to the values ofloclisted above, we have 'outside right upper', 'outside right lower','outside left upper', and 'outside left lower'. SeeLegend guide for more details.

bbox_to_anchorBboxBase, 2-tuple, or 4-tuple of floats

Box that is used to position the legend in conjunction withloc.Defaults toaxes.bbox (if called as a method toAxes.legend) orfigure.bbox (iffigure.legend). This argument allows arbitraryplacement of the legend.

Bbox coordinates are interpreted in the coordinate system given bybbox_transform, with the default transformAxes or Figure coordinates, depending on whichlegend is called.

If a 4-tuple orBboxBase 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 rightquadrant 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 byloc atx, y. For example, to put the legend's upper right-hand corner in thecenter of the Axes (or figure) the following keywords can be used:

loc='upper right',bbox_to_anchor=(0.5,0.5)
ncolsint, default: 1

The number of columns that the legend has.

For backward compatibility, the spellingncol is also supportedbut it is discouraged. If both are given,ncols takes precedence.

propNone orFontProperties or dict

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

fontsizeint 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 theabsolute font size in points. String values are relative to the currentdefault font size. This argument is only used ifprop is not specified.

labelcolorstr or list, default:rcParams["legend.labelcolor"] (default:'None')

The color of the text in the legend. Either a valid color string(for example, 'red'), or a list of color strings. The labelcolor canalso be made to match the color of the line or marker using 'linecolor','markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').

Labelcolor can be set globally usingrcParams["legend.labelcolor"] (default:'None'). If None,usercParams["text.color"] (default:'black').

numpointsint, default:rcParams["legend.numpoints"] (default:1)

The number of marker points in the legend when creating a legendentry for aLine2D (line).

scatterpointsint, default:rcParams["legend.scatterpoints"] (default:1)

The number of marker points in the legend when creatinga legend entry for aPathCollection (scatter plot).

scatteryoffsetsiterable of floats, default:[0.375,0.5,0.3125]

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

markerscalefloat, default:rcParams["legend.markerscale"] (default:1.0)

The relative size of legend markers compared to the originally drawn ones.

markerfirstbool, default: True

IfTrue, legend marker is placed to the left of the legend label.IfFalse, legend marker is placed to the right of the legend label.

reversebool, default: False

IfTrue, the legend labels are displayed in reverse order from the input.IfFalse, the legend labels are displayed in the same order as the input.

Added in version 3.7.

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

Whether the legend should be drawn on a patch (frame).

fancyboxbool, default:rcParams["legend.fancybox"] (default:True)

Whether round edges should be enabled around theFancyBboxPatch whichmakes up the legend's background.

shadowNone, bool or dict, default:rcParams["legend.shadow"] (default:False)

Whether to draw a shadow behind the legend.The shadow can be configured usingPatch keywords.Customization viarcParams["legend.shadow"] (default:False) is currently not supported.

framealphafloat, default:rcParams["legend.framealpha"] (default:0.8)

The alpha transparency of the legend's background.Ifshadow is activated andframealpha isNone, the default value isignored.

facecolor"inherit" or color, default:rcParams["legend.facecolor"] (default:'inherit')

The legend's background color.If"inherit", usercParams["axes.facecolor"] (default:'white').

edgecolor"inherit" or color, default:rcParams["legend.edgecolor"] (default:'0.8')

The legend's background patch edge color.If"inherit", usercParams["axes.edgecolor"] (default:'black').

mode{"expand", None}

Ifmode is set to"expand" the legend will be horizontallyexpanded to fill the Axes area (orbbox_to_anchor if definesthe legend's size).

bbox_transformNone orTransform

The transform for the bounding box (bbox_to_anchor). For a valueofNone (default) the Axes'matplotlib.axes.Axes.transAxes transform will be used.

titlestr or None

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

title_fontpropertiesNone orFontProperties or dict

The font properties of the legend's title. If None (default), thetitle_fontsize argument will be used if present; iftitle_fontsize isalso None, the currentrcParams["legend.title_fontsize"] (default:None) will be used.

title_fontsizeint or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'}, default:rcParams["legend.title_fontsize"] (default:None)

The font size of the legend's title.Note: This cannot be combined withtitle_fontproperties. If you wantto set the fontsize alongside other font properties, use thesizeparameter intitle_fontproperties.

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

The alignment of the legend title and the box of entries. The entriesare aligned as a single block, so that markers always lined up.

borderpadfloat, default:rcParams["legend.borderpad"] (default:0.4)

The fractional whitespace inside the legend border, in font-size units.

labelspacingfloat, default:rcParams["legend.labelspacing"] (default:0.5)

The vertical space between the legend entries, in font-size units.

handlelengthfloat, default:rcParams["legend.handlelength"] (default:2.0)

The length of the legend handles, in font-size units.

handleheightfloat, default:rcParams["legend.handleheight"] (default:0.7)

The height of the legend handles, in font-size units.

handletextpadfloat, default:rcParams["legend.handletextpad"] (default:0.8)

The pad between the legend handle and text, in font-size units.

borderaxespadfloat, default:rcParams["legend.borderaxespad"] (default:0.5)

The pad between the Axes and legend border, in font-size units.

columnspacingfloat, default:rcParams["legend.columnspacing"] (default:2.0)

The spacing between columns, in font-size units.

handler_mapdict or None

The custom dictionary mapping instances or types to a legendhandler. Thishandler_map updates the default handler mapfound atmatplotlib.legend.Legend.get_legend_handler_map.

draggablebool, default: False

Whether the legend can be dragged with the mouse.

See also

Axes.legend

Notes

Some artists are not supported by this function. SeeLegend guide for details.

sca(a)[source]#

Set the current Axes to bea and returna.

set(*,agg_filter=<UNSET>,alpha=<UNSET>,animated=<UNSET>,clip_box=<UNSET>,clip_on=<UNSET>,clip_path=<UNSET>,edgecolor=<UNSET>,facecolor=<UNSET>,frameon=<UNSET>,gid=<UNSET>,in_layout=<UNSET>,label=<UNSET>,linewidth=<UNSET>,mouseover=<UNSET>,path_effects=<UNSET>,picker=<UNSET>,rasterized=<UNSET>,sketch_params=<UNSET>,snap=<UNSET>,transform=<UNSET>,url=<UNSET>,visible=<UNSET>,zorder=<UNSET>)[source]#

Set multiple properties at once.

Supported properties are

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

float or None

animated

bool

clip_box

BboxBase or None

clip_on

bool

clip_path

Patch or (Path, Transform) or None

edgecolor

color

facecolor

color

figure

unknown

frameon

bool

gid

str

in_layout

bool

label

object

linewidth

number

mouseover

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

rasterized

bool

sketch_params

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

snap

bool or None

transform

Transform

url

str

visible

bool

zorder

float

set_edgecolor(color)[source]#

Set the edge color of the Figure rectangle.

Parameters:
colorcolor
set_facecolor(color)[source]#

Set the face color of the Figure rectangle.

Parameters:
colorcolor
set_figure(fig)[source]#

Deprecated since version 3.10:Currently this method will raise an exception iffig is anything otherthan the rootFigure this (Sub)Figure is on. In future it will alwaysraise an exception.

set_frameon(b)[source]#

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

Parameters:
bbool
set_linewidth(linewidth)[source]#

Set the line width of the Figure rectangle.

Parameters:
linewidthnumber
subfigures(nrows=1,ncols=1,squeeze=True,wspace=None,hspace=None,width_ratios=None,height_ratios=None,**kwargs)[source]#

Add a set of subfigures to this figure or subfigure.

A subfigure has the same artist methods as a figure, and is logicallythe same as a figure, but cannot print itself.SeeFigure subfigures.

Changed in version 3.10:subfigures are now added in row-major order.

Parameters:
nrows, ncolsint, default: 1

Number of rows/columns of the subfigure grid.

squeezebool, default: True

If True, extra dimensions are squeezed out from the returnedarray of subfigures.

wspace, hspacefloat, default: None

The amount of width/height reserved for space between subfigures,expressed as a fraction of the average subfigure width/height.If not given, the values will be inferred from rcParams if usingconstrained layout (seeConstrainedLayoutEngine), or zero ifnot using a layout engine.

width_ratiosarray-like of lengthncols, optional

Defines the relative widths of the columns. Each column gets arelative width ofwidth_ratios[i]/sum(width_ratios).If not given, all columns will have the same width.

height_ratiosarray-like of lengthnrows, optional

Defines the relative heights of the rows. Each row gets arelative height ofheight_ratios[i]/sum(height_ratios).If not given, all rows will have the same height.

subplot_mosaic(mosaic,*,sharex=False,sharey=False,width_ratios=None,height_ratios=None,empty_sentinel='.',subplot_kw=None,per_subplot_kw=None,gridspec_kw=None)[source]#

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

This is a helper function to build complex GridSpec layouts visually.

SeeComplex and semantic figure composition (subplot_mosaic)for an example and full API documentation

Parameters:
mosaiclist of list of {hashable or nested} or str

A visual layout of how you want your Axes to be arrangedlabeled as strings. For example

x=[['A panel','A panel','edge'],['C panel','.','edge']]

produces 4 Axes:

  • 'A panel' which is 1 row high and spans the first two columns

  • 'edge' which is 2 rows high and is on the right edge

  • 'C panel' which in 1 row and 1 column wide in the bottom left

  • a blank space 1 row and 1 column wide in the bottom center

Any of the entries in the layout can be a list of listsof the same form to create nested layouts.

If input is a str, then it can either be a multi-line string ofthe form

'''AAEC.E'''

where each character is a column and each line is a row. Or itcan be a single-line string where rows are separated by;:

'AB;CC'

The string notation allows only single character Axes labels anddoes not support nesting but is very terse.

The Axes identifiers may bestr or a non-iterable hashableobject (e.g.tuple s may not be used).

sharex, shareybool, default: False

If True, the x-axis (sharex) or y-axis (sharey) will be sharedamong all subplots. In that case, tick label visibility and axisunits behave as forsubplots. If False, each subplot's x- ory-axis will be independent.

width_ratiosarray-like of lengthncols, optional

Defines the relative widths of the columns. Each column gets arelative width ofwidth_ratios[i]/sum(width_ratios).If not given, all columns will have the same width. Equivalenttogridspec_kw={'width_ratios':[...]}. In the case of nestedlayouts, this argument applies only to the outer layout.

height_ratiosarray-like of lengthnrows, optional

Defines the relative heights of the rows. Each row gets arelative height ofheight_ratios[i]/sum(height_ratios).If not given, all rows will have the same height. Equivalenttogridspec_kw={'height_ratios':[...]}. In the case of nestedlayouts, this argument applies only to the outer layout.

subplot_kwdict, optional

Dictionary with keywords passed to theFigure.add_subplot callused to create each subplot. These values may be overridden byvalues inper_subplot_kw.

per_subplot_kwdict, optional

A dictionary mapping the Axes identifiers or tuples of identifiersto a dictionary of keyword arguments to be passed to theFigure.add_subplot call used to create each subplot. The valuesin these dictionaries have precedence over the values insubplot_kw.

Ifmosaic is a string, and thus all keys are single characters,it is possible to use a single string instead of a tuple as keys;i.e."AB" is equivalent to("A","B").

Added in version 3.7.

gridspec_kwdict, optional

Dictionary with keywords passed to theGridSpec constructor usedto create the grid the subplots are placed on. In the case ofnested layouts, this argument applies only to the outer layout.For more complex layouts, users should useFigure.subfiguresto create the nesting.

empty_sentinelobject, optional

Entry in the layout to mean "leave this space empty". Defaultsto'.'. Note, iflayout is a string, it is processed viainspect.cleandoc to remove leading white space, which mayinterfere with using white-space as the empty sentinel.

Returns:
dict[label, Axes]

A dictionary mapping the labels to the Axes objects. The order ofthe Axes is left-to-right and top-to-bottom of their position in thetotal layout.

subplots(nrows=1,ncols=1,*,sharex=False,sharey=False,squeeze=True,width_ratios=None,height_ratios=None,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 ofsubplots in a single call.

Parameters:
nrows, ncolsint, default: 1

Number of rows/columns of the subplot grid.

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

Controls sharing of x-axis (sharex) or y-axis (sharey):

  • 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 ticklabels of the bottom subplot are created. Similarly, when subplotshave a shared y-axis along a row, only the y tick labels of thefirst column subplot are created. To later turn other subplots'ticklabels on, usetick_params.

When subplots have a shared axis that has units, callingAxis.set_units will update each axis with the new units.

Note that it is not possible to unshare axes.

squeezebool, default: True
  • If True, extra dimensions are squeezed out from the returnedarray of Axes:

    • if only one subplot is constructed (nrows=ncols=1), theresulting single Axes object is returned as a scalar.

    • for Nx1 or 1xM subplots, the returned object is a 1D numpyobject 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 objectis always a 2D array containing Axes instances, even if it endsup being 1x1.

width_ratiosarray-like of lengthncols, optional

Defines the relative widths of the columns. Each column gets arelative width ofwidth_ratios[i]/sum(width_ratios).If not given, all columns will have the same width. Equivalenttogridspec_kw={'width_ratios':[...]}.

height_ratiosarray-like of lengthnrows, optional

Defines the relative heights of the rows. Each row gets arelative height ofheight_ratios[i]/sum(height_ratios).If not given, all rows will have the same height. Equivalenttogridspec_kw={'height_ratios':[...]}.

subplot_kwdict, optional

Dict with keywords passed to theFigure.add_subplot call used tocreate each subplot.

gridspec_kwdict, optional

Dict with keywords passed to theGridSpec constructor used to createthe grid the subplots are placed on.

Returns:
Axes or array of Axes

Either a singleAxes object or an array of Axesobjects if more than one subplot was created. The dimensions of theresulting array can be controlled with thesqueeze keyword, seeabove.

Examples

# First create some toy data:x=np.linspace(0,2*np.pi,400)y=np.sin(x**2)# Create a figurefig=plt.figure()# Create a subplotax=fig.subplots()ax.plot(x,y)ax.set_title('Simple plot')# Create two subplots and unpack the output array immediatelyax1,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 arrayaxes=fig.subplots(2,2,subplot_kw=dict(projection='polar'))axes[0,0].plot(x,y)axes[1,1].scatter(x,y)# Share an X-axis with each column of subplotsfig.subplots(2,2,sharex='col')# Share a Y-axis with each row of subplotsfig.subplots(2,2,sharey='row')# Share both X- and Y-axes with all subplotsfig.subplots(2,2,sharex='all',sharey='all')# Note that this is the same asfig.subplots(2,2,sharex=True,sharey=True)
subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)[source]#

Adjust the subplot layout parameters.

Unset parameters are left unmodified; initial values are given byrcParams["figure.subplot.[name]"].

(Sourcecode,2x.png,png)

Parameters:
leftfloat, optional

The position of the left edge of the subplots,as a fraction of the figure width.

rightfloat, optional

The position of the right edge of the subplots,as a fraction of the figure width.

bottomfloat, optional

The position of the bottom edge of the subplots,as a fraction of the figure height.

topfloat, optional

The position of the top edge of the subplots,as a fraction of the figure height.

wspacefloat, optional

The width of the padding between subplots,as a fraction of the average Axes width.

hspacefloat, optional

The height of the padding between subplots,as a fraction of the average Axes height.

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

Add a centered super title to the figure.

Parameters:
tstr

The super 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. SeeText.set_size for possiblevalues.

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

The font weight of the text. SeeText.set_weight for possiblevalues.

Returns:
text

TheText instance of the super title.

Other Parameters:
fontpropertiesNone or dict, optional

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

**kwargs

Additional kwargs arematplotlib.text.Text properties.

supxlabel(t,**kwargs)[source]#

Add a centered super xlabel to the figure.

Parameters:
tstr

The super xlabel text.

xfloat, default: 0.5

The x location of the text in figure coordinates.

yfloat, default: 0.01

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

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

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

The font size of the text. SeeText.set_size for possiblevalues.

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

The font weight of the text. SeeText.set_weight for possiblevalues.

Returns:
text

TheText instance of the super xlabel.

Other Parameters:
fontpropertiesNone or dict, optional

A dict of font properties. Iffontproperties is given thedefault values for font size and weight are taken from theFontProperties defaults.rcParams["figure.labelsize"] (default:'large') andrcParams["figure.labelweight"] (default:'normal') are ignored in this case.

**kwargs

Additional kwargs arematplotlib.text.Text properties.

supylabel(t,**kwargs)[source]#

Add a centered super ylabel to the figure.

Parameters:
tstr

The super ylabel text.

xfloat, default: 0.02

The x location of the text in figure coordinates.

yfloat, default: 0.5

The y location of the text in figure coordinates.

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

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

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

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

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

The font size of the text. SeeText.set_size for possiblevalues.

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

The font weight of the text. SeeText.set_weight for possiblevalues.

Returns:
text

TheText instance of the super ylabel.

Other Parameters:
fontpropertiesNone or dict, optional

A dict of font properties. Iffontproperties is given thedefault values for font size and weight are taken from theFontProperties defaults.rcParams["figure.labelsize"] (default:'large') andrcParams["figure.labelweight"] (default:'normal') are ignored in this case.

**kwargs

Additional kwargs arematplotlib.text.Text properties.

text(x,y,s,fontdict=None,**kwargs)[source]#

Add text to figure.

Parameters:
x, yfloat

The position to place the text. By default, this is in figurecoordinates, floats in [0, 1]. The coordinate system can be changedusing thetransform keyword.

sstr

The text string.

fontdictdict, optional

A dictionary to override the default text properties. If not given,the defaults are determined byrcParams["font.*"]. Properties passed askwargs override the corresponding ones given infontdict.

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

alpha

float or None

animated

bool

antialiased

bool

backgroundcolor

color

bbox

dict with properties forFancyBboxPatch or None

clip_box

unknown

clip_on

unknown

clip_path

unknown

color orc

color

figure

Figure orSubFigure

fontfamily orfamily orfontname

{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'}

fontproperties orfont orfont_properties

font_manager.FontProperties orstr orpathlib.Path

fontsize orsize

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

fontstretch orstretch

{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'}

fontstyle orstyle

{'normal', 'italic', 'oblique'}

fontvariant orvariant

{'normal', 'small-caps'}

fontweight orweight

{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 orha

{'left', 'center', 'right'}

in_layout

bool

label

object

linespacing

float (multiple of font size)

math_fontfamily

str

mouseover

bool

multialignment orma

{'left', 'right', 'center'}

parse_math

bool

path_effects

list ofAbstractPathEffect

picker

None or bool or float or callable

position

(float, float)

rasterized

bool

rotation

float or {'vertical', 'horizontal'}

rotation_mode

{None, 'default', 'anchor', 'xtick', 'ytick'}

sketch_params

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

snap

bool or None

text

object

transform

Transform

transform_rotates_text

bool

url

str

usetex

bool, default:rcParams["text.usetex"] (default:False)

verticalalignment orva

{'baseline', 'bottom', 'center', 'center_baseline', 'top'}

visible

bool

wrap

bool

x

float

y

float

zorder

float

Helper functions#

matplotlib.figure.figaspect(arg)[source]#

Calculate the width and height for a figure with a specified aspect ratio.

While the height is taken fromrcParams["figure.figsize"] (default:[6.4,4.8]), the width isadjusted to match the desired aspect ratio. Additionally, it is ensuredthat the width is in the range [4., 16.] and the height is in the range[2., 16.]. If necessary, the default height is adjusted to ensure this.

Parameters:
argfloat or 2D array

If a float, this defines the aspect ratio (i.e. the ratio height /width).In case of an array the aspect ratio is number of rows / number ofcolumns, so that the array could be fitted in the figure undistorted.

Returns:
size(2,) array

The width and height of the figure in inches.

Notes

If you want to create an Axes within the figure, that still preserves theaspect ratio, be sure to create it with equal width and height. Seeexamples below.

Thanks to Fernando Perez for this function.

Examples

Make a figure twice as tall as it is wide:

w,h=figaspect(2.)fig=Figure(figsize=(w,h))ax=fig.add_axes([0.1,0.1,0.8,0.8])ax.imshow(A,**kwargs)

Make a figure with the proper aspect for an array:

A=rand(5,3)w,h=figaspect(A)fig=Figure(figsize=(w,h))ax=fig.add_axes([0.1,0.1,0.8,0.8])ax.imshow(A,**kwargs)
On this page