On this page
matplotlib.figure
matplotlib.figure implements the following classes:
-
Figure -
Top level
Artist, which holds all plot elements. Many methods are implemented inFigureBase. -
SubFigure -
A logical figure inside a figure, usually added to a figure (or parent
SubFigure) withFigure.add_subfigureorFigure.subfiguresmethods (provisional API v3.4). -
SubplotParams -
Control the default spacing between subplots.
Figures are typically created using pyplot methods figure, subplots, and subplot_mosaic.
fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
layout='constrained')
fig.suptitle('Figure')
ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
(Source code, png)
Some situations call for directly instantiating a Figure class, usually inside an application of some sort (see Embedding Matplotlib in graphical user interfaces for a list of examples) . More information about Figures can be found at Creating, viewing, and saving Matplotlib Figures.
- classmatplotlib.figure.Figure(figsize=None, dpi=None, *, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None, layout=None, **kwargs)[source]
-
The top level container for all the plot elements.
- Attributes:
-
- patch
-
The
Rectangleinstance representing the figure background patch. - suppressComposite
-
For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is a boolean, this will override the renderer.
- Parameters:
-
- figsize2-tuple of floats, default:
rcParams["figure.figsize"](default:[6.4, 4.8]) -
Figure dimension
(width, height)in inches. - dpifloat, default:
rcParams["figure.dpi"](default:100.0) -
Dots per inch.
- facecolordefault:
rcParams["figure.facecolor"](default:'white') -
The figure patch facecolor.
- edgecolordefault:
rcParams["figure.edgecolor"](default:'white') -
The figure patch edge color.
- linewidthfloat
-
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
- frameonbool, default:
rcParams["figure.frameon"](default:True) -
If
False, suppress drawing the figure background patch. - subplotpars
SubplotParams -
Subplot parameters. If not given, the default subplot parameters
rcParams["figure.subplot.*"]are used. - tight_layoutbool or dict, default:
rcParams["figure.autolayout"](default:False) -
Whether to use the tight layout mechanism. See
set_tight_layout.Discouraged
The use of this parameter is discouraged. Please use
layout='tight'instead for the common case oftight_layout=Trueand useset_tight_layoutotherwise. - constrained_layoutbool, default:
rcParams["figure.constrained_layout.use"](default:False) -
This is equal to
layout='constrained'.Discouraged
The use of this parameter is discouraged. Please use
layout='constrained'instead. - layout{'constrained', 'compressed', 'tight', 'none',
LayoutEngine, None}, default: None -
The layout mechanism for positioning of plot elements to avoid overlapping Axes decorations (labels, ticks, etc). Note that layout managers can have significant performance penalties.
'constrained': The constrained layout solver adjusts axes sizes to avoid overlapping axes decorations. Can handle complex plot layouts and colorbars, and is thus recommended.
See Constrained Layout Guide for examples.
- 'compressed': uses the same algorithm as 'constrained', but removes extra space between fixed-aspect-ratio Axes. Best for simple grids of axes.
- 'tight': Use the tight layout mechanism. This is a relatively simple algorithm that adjusts the subplot parameters so that decorations do not overlap. See
Figure.set_tight_layoutfor further details. - 'none': Do not use a layout engine.
- A
LayoutEngineinstance. Builtin layout classes areConstrainedLayoutEngineandTightLayoutEngine, more easily accessible by 'constrained' and 'tight'. Passing an instance allows third parties to provide their own layout engine.
If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults
rcParams["figure.autolayout"](default:False) andrcParams["figure.constrained_layout.use"](default:False).
- figsize2-tuple of floats, default:
- Other Parameters:
-
- **kwargs
Figureproperties, optional -
Property
Description
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
scalar or None
bool
FigureCanvas
bool
Patch or (Path, Transform) or None
unknown
unknown
float
color
color
float
float
bool
str
bool
object
unknown
number
bool
None or bool or float or callable
bool
(float, float) or float
(scale: float, length: float, randomness: float)
bool or None
unknown
str
bool
float
- **kwargs
- add_artist(artist, clip=False)[source]
-
Add an
Artistto the figure.Usually artists are added to
Axesobjects usingAxes.add_artist; this method can be used in the rare cases where one needs to add artists directly to the figure instead.
- add_axes(*args, **kwargs)[source]
-
Add an
Axesto 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, seeprojections. 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.Axessubclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples. - sharex, sharey
Axes, optional -
Share the x or y
axiswith 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 ofAxes-
The returned axes class depends on the projection used. It is
Axesif rectilinear projection is used andprojections.polar.PolarAxesif 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
Axescan 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
{'box', 'datalim'}
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
scalar or None
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
bool
{'auto', 'equal'} or float
bool
unknown
unknown
Callable[[Axes, Renderer], Bbox]
bool or 'line'
float or None
bool
Patch or (Path, Transform) or None
facecoloror fccolor
bool
str
bool
object
bool
bool
unknown
None or bool or float or callable
[left, bottom, width, height] or
Bboxunknown
float or None
bool
(scale: float, length: float, randomness: float)
bool or None
unknown
str
str
bool
unknown
str
(bottom: float, top: float)
float greater than -0.5
unknown
unknown
unknown
unknown
str
(bottom: float, top: float)
float greater than -0.5
unknown
unknown
unknown
float
Notes
In rare circumstances,
add_axesmay be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes.Examples
Some simple examples:
rect = l, b, w, h fig = plt.figure() fig.add_axes(rect) fig.add_axes(rect, frameon=False, facecolor='g') fig.add_axes(rect, polar=True) ax = fig.add_axes(rect, projection='polar') fig.delaxes(ax) fig.add_axes(ax)
- add_axobserver(func)[source]
-
Whenever the Axes state change,
func(self)will be called.
- add_callback(func)[source]
-
Add a callback function that will be called whenever one of the
Artist's properties changes.- Parameters:
-
- funccallable
-
The callback function. It must have the signature:
def func(artist: Artist) -> Anywhere artist is the calling
Artist. Return values may exist but are ignored.
- Returns:
-
- int
-
The observer id associated with the callback. This id can be used for removing the callback with
remove_callbacklater.
See also
- add_gridspec(nrows=1, ncols=1, **kwargs)[source]
-
Return a
GridSpecthat has this figure as a parent. This allows complex layout of Axes in the figure.- Parameters:
-
- nrowsint, default: 1
-
Number of rows in grid.
- ncolsint, default: 1
-
Number of columns in grid.
- Returns:
- Other Parameters:
-
- **kwargs
-
Keyword arguments are passed to
GridSpec.
See also
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
SubFigureto the figure as part of a subplot arrangement.- Parameters:
-
- subplotspec
gridspec.SubplotSpec -
Defines the region in a parent gridspec where the subfigure will be placed.
- subplotspec
- Returns:
- Other Parameters:
-
- **kwargs
-
Are passed to the
SubFigureobject.
See also
- add_subplot(*args, **kwargs)[source]
-
Add an
Axesto 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 asfig.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_subplotmay 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. - 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.,
- 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, seeprojections. 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.Axessubclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples. - sharex, sharey
Axes, optional -
Share the x or y
axiswith 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.
- *argsint, (int, int, index), or
- Returns:
-
-
Axes -
The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as
projections.polar.PolarAxesfor 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
Axescan be found in the following table but there might also be other keyword arguments if another projection is used.Property
Description
{'box', 'datalim'}
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
scalar or None
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...}
bool
{'auto', 'equal'} or float
bool
unknown
unknown
Callable[[Axes, Renderer], Bbox]
bool or 'line'
float or None
bool
Patch or (Path, Transform) or None
facecoloror fccolor
bool
str
bool
object
bool
bool
unknown
None or bool or float or callable
[left, bottom, width, height] or
Bboxunknown
float or None
bool
(scale: float, length: float, randomness: float)
bool or None
unknown
str
str
bool
unknown
str
(bottom: float, top: float)
float greater than -0.5
unknown
unknown
unknown
unknown
str
(bottom: float, top: float)
float greater than -0.5
unknown
unknown
unknown
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.
- align_xlabels(axs=None)[source]
-
Align the xlabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row.
- Parameters:
Notes
This assumes that
axsare from the sameGridSpec, so that theirSubplotSpecpositions correspond to figure positions.Examples
Example with rotated xtick labels:
fig, axs = plt.subplots(1, 2) for tick in axs[0].get_xticklabels(): tick.set_rotation(55) axs[0].set_xlabel('XLabel 0') axs[1].set_xlabel('XLabel 1') fig.align_xlabels()
- align_ylabels(axs=None)[source]
-
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
If a label is on the left, it is aligned with labels on Axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on Axes with the same right-most column.
- Parameters:
Notes
This assumes that
axsare from the sameGridSpec, so that theirSubplotSpecpositions correspond to figure positions.Examples
Example with large yticks labels:
fig, axs = plt.subplots(2, 1) axs[0].plot(np.arange(0, 1000, 50)) axs[0].set_ylabel('YLabel 0') axs[1].set_ylabel('YLabel 1') fig.align_ylabels()
- autofmt_xdate(bottom=0.2, rotation=30, ha='right', which='major')[source]
-
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.
- Parameters:
-
- bottomfloat, default: 0.2
-
The bottom of the subplots for
subplots_adjust. - rotationfloat, default: 30 degrees
-
The rotation angle of the xtick labels in degrees.
- ha{'left', 'center', 'right'}, default: 'right'
-
The horizontal alignment of the xticklabels.
- which{'major', 'minor', 'both'}, default: 'major'
-
Selects which ticklabels to rotate.
- propertyaxes
-
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.
Do not modify the list itself. Instead, use
add_axes,add_subplotordelaxesto add or remove an Axes.Note: The
Figure.axesproperty andget_axesmethod are equivalent.
- propertycallbacks[source]
- clear(keep_observers=False)[source]
-
Clear the figure.
- Parameters:
-
- keep_observersbool, default: False
-
Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.
- clf(keep_observers=False)[source]
-
[Discouraged] Alias for the
clear()method.Discouraged
The use of
clf()is discouraged. Useclear()instead.- Parameters:
-
- keep_observersbool, default: False
-
Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.
- colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kwargs)[source]
-
Add a colorbar to a plot.
- Parameters:
-
- mappable
-
The
matplotlib.cm.ScalarMappable(i.e.,AxesImage,ContourSet, etc.) described by this colorbar. This argument is mandatory for theFigure.colorbarmethod but optional for thepyplot.colorbarfunction, which sets the default to the current image.Note that one can create a
ScalarMappable"on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax) - cax
Axes, optional -
Axes into which the colorbar will be drawn.
- ax
Axesor iterable ornumpy.ndarrayof Axes, optional -
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
- use_gridspecbool, optional
-
If cax is
None, a new cax is created as an instance of Axes. If ax is positioned with a subplotspec and use_gridspec isTrue, then cax is also positioned with a subplotspec.
- Returns:
-
- colorbar
Colorbar
- colorbar
- Other Parameters:
-
- locationNone or {'left', 'right', 'top', 'bottom'}
-
The location, relative to the parent axes, where the colorbar axes is created. It also determines the orientation of the colorbar (colorbars on the left and right are vertical, colorbars at the top and bottom are horizontal). If None, the location will come from the orientation if it is set (vertical colorbars on the right, horizontal ones at the bottom), or default to 'right' if orientation is unset.
- orientationNone or {'vertical', 'horizontal'}
-
The orientation of the colorbar. It is preferable to set the location of the colorbar, as that also determines the orientation; passing incompatible values for location and orientation raises an exception.
- fractionfloat, default: 0.15
-
Fraction of original axes to use for colorbar.
- shrinkfloat, default: 1.0
-
Fraction by which to multiply the size of the colorbar.
- aspectfloat, default: 20
-
Ratio of long to short dimensions.
- padfloat, default: 0.05 if vertical, 0.15 if horizontal
-
Fraction of original axes between colorbar and new image axes.
- anchor(float, float), optional
-
The anchor point of the colorbar axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
- panchor(float, float), or False, optional
-
The anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged. Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
- extend{'neither', 'both', 'min', 'max'}
-
Make pointed end(s) for out-of-range values (unless 'neither'). These are set for a given colormap using the colormap set_under and set_over methods.
- extendfrac{None, 'auto', length, lengths}
-
If set to None, both the minimum and maximum triangular colorbar extensions will have a length of 5% of the interior colorbar length (this is the default setting).
If set to 'auto', makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to 'uniform') or the same lengths as the respective adjacent interior boxes (when spacing is set to 'proportional').
If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length.
- extendrectbool
-
If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
- spacing{'uniform', 'proportional'}
-
For discrete colorbars (
BoundaryNormor contours), 'uniform' gives each color the same space; 'proportional' makes the space proportional to the data interval. - ticksNone or list of ticks or Locator
-
If None, ticks are determined automatically from the input.
- formatNone or str or Formatter
-
If None,
ScalarFormatteris used. Format strings, e.g.,"%4.2e"or"{x:.2e}", are supported. An alternativeFormattermay be given instead. - drawedgesbool
-
Whether to draw lines at color boundaries.
- labelstr
-
The label on the colorbar's long axis.
- boundaries, valuesNone or a sequence
-
If unset, the colormap will be displayed on a 0-1 scale. If sequences, values must have a length 1 less than boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. Normally only useful for indexed colors (i.e.
norm=NoNorm()) or other unusual circumstances.
Notes
If mappable is a
ContourSet, its extend kwarg is included automatically.The shrink kwarg provides a simple way to scale the colorbar with respect to the axes. Note that if cax is specified, it determines the size of the colorbar and shrink and aspect kwargs are ignored.
For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:
cbar = colorbar() cbar.solids.set_edgecolor("face") draw()However, this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
- contains(mouseevent)[source]
-
Test whether the mouse event occurred on the figure.
- Returns:
-
- bool, {}
- convert_xunits(x)[source]
-
Convert x using the unit type of the xaxis.
If the artist is not contained in an Axes or if the xaxis does not have units, x itself is returned.
- convert_yunits(y)[source]
-
Convert y using the unit type of the yaxis.
If the artist is not contained in an Axes or if the yaxis does not have units, y itself is returned.
- propertydpi
-
The resolution in dots per inch.
- draw(renderer)[source]
-
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (
Artist.get_visiblereturns False).- Parameters:
-
- renderer
RendererBasesubclass.
- renderer
Notes
This method is overridden in the Artist subclasses.
- draw_without_rendering()[source]
-
Draw the figure with no output. Useful to get the final size of artists that require a draw before their size is known (e.g. text).
- execute_constrained_layout(renderer=None)[source]
-
[Deprecated] Use
layoutgridto determine pos positions within Axes.See also
set_constrained_layout_pads.- Returns:
-
- layoutgridprivate debugging object
Notes
Deprecated since version 3.6: Use figure.get_layout_engine().execute() instead.
- figimage(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs)[source]
-
Add a non-resampled image to the figure.
The image is attached to the lower or upper left corner depending on origin.
- Parameters:
-
- X
-
The image data. This is an array of one of the following shapes:
- (M, N): an image with scalar data. Color-mapping is controlled by cmap, norm, vmin, and vmax.
- (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
- (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency.
- xo, yoint
-
The x/y image offset in pixels.
- alphaNone or float
-
The alpha blending value.
- cmapstr or
Colormap, default:rcParams["image.cmap"](default:'viridis') -
The Colormap instance or registered colormap name used to map scalar data to colors.
This parameter is ignored if X is RGB(A).
- normstr or
Normalize, optional -
The normalization method used to scale scalar data to the [0, 1] range before mapping to colors using cmap. By default, a linear scaling is used, mapping the lowest value to 0 and the highest to 1.
If given, this can be one of the following:
- An instance of
Normalizeor one of its subclasses (see Colormap Normalization). - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a list of available scales, call
matplotlib.scale.get_scale_names(). In that case, a suitableNormalizesubclass is dynamically generated and instantiated.
This parameter is ignored if X is RGB(A).
- An instance of
- vmin, vmaxfloat, optional
-
When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. It is an error to use vmin/vmax when a norm instance is given (but using a
strnorm name together with vmin/vmax is acceptable).This parameter is ignored if X is RGB(A).
- origin{'upper', 'lower'}, default:
rcParams["image.origin"](default:'upper') -
Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes.
- resizebool
-
If True, resize the figure to match the given image size.
- Returns:
- Other Parameters:
-
- **kwargs
-
Additional kwargs are
Artistkwargs passed on toFigureImage.
Notes
figimage complements the Axes image (
imshow) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define anAxeswith extent [0, 0, 1, 1].Examples
f = plt.figure() nx = int(f.get_figwidth() * f.dpi) ny = int(f.get_figheight() * f.dpi) data = np.random.random((ny, nx)) f.figimage(data) plt.show()
- findobj(match=None, include_self=True)[source]
-
Find artist objects.
Recursively find all
Artistinstances contained in the artist.- Parameters:
-
- match
-
A filter criterion for the matches. This can be
- None: Return all objects contained in artist.
- A function with signature
def match(artist: Artist) -> bool. The result will only contain artists for which the function returns True. - A class instance: e.g.,
Line2D. The result will only contain artists of this class or its subclasses (isinstancecheck).
- include_selfbool
-
Include self in the list to be checked for a match.
- Returns:
-
-
list of
Artist
-
list of
- format_cursor_data(data)[source]
-
Return a string representation of data.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
The default implementation converts ints and floats and arrays of ints and floats into a comma-separated string enclosed in square brackets, unless the artist has an associated colorbar, in which case scalar values are formatted using the colorbar's formatter.
See also
- propertyframeon
-
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to
Figure.patch.get_visible().
- gca()[source]
-
Get the current Axes.
If there is currently no Axes on this Figure, a new one is created using
Figure.add_subplot. (To test whether there is currently an Axes on a Figure, check whetherfigure.axesis empty. To test whether there is currently a Figure on the pyplot figure stack, check whetherpyplot.get_fignums()is empty.)
- get_agg_filter()[source]
-
Return filter function to be used for agg filter.
- get_alpha()[source]
-
Return the alpha value used for blending - not supported on all backends.
- get_animated()[source]
-
Return whether the artist is animated.
- get_axes()[source]
-
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.
Do not modify the list itself. Instead, use
add_axes,add_subplotordelaxesto add or remove an Axes.Note: The
Figure.axesproperty andget_axesmethod are equivalent.
- get_children()[source]
-
Get a list of artists contained in the figure.
- get_clip_box()[source]
-
Return the clipbox.
- get_clip_on()[source]
-
Return whether the artist uses clipping.
- get_clip_path()[source]
-
Return the clip path.
- get_constrained_layout()[source]
-
Return whether constrained layout is being used.
- get_constrained_layout_pads(relative=False)[source]
-
[Deprecated] Get padding for
constrained_layout.Returns a list of
w_pad, h_padin inches andwspaceandhspaceas fractions of the subplot. All values are None ifconstrained_layoutis not used.- Parameters:
-
- relativebool
-
If
True, then convert from inches to figure relative.
Notes
Deprecated since version 3.6: Use fig.get_layout_engine().get() instead.
- get_cursor_data(event)[source]
-
Return the cursor data for a given event.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that
format_cursor_datacan convert the data to a string representation.The only current use case is displaying the z-value of an
AxesImagein the status bar of a plot window, while moving the mouse.- Parameters:
See also
- get_default_bbox_extra_artists()[source]
- get_dpi()[source]
-
Return the resolution in dots per inch as a float.
- get_edgecolor()[source]
-
Get the edge color of the Figure rectangle.
- get_facecolor()[source]
-
Get the face color of the Figure rectangle.
- get_figheight()[source]
-
Return the figure height in inches.
- get_figwidth()[source]
-
Return the figure width in inches.
- get_frameon()[source]
-
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to
Figure.patch.get_visible().
- get_gid()[source]
-
Return the group id.
- get_in_layout()[source]
-
Return boolean flag,
Trueif artist is included in layout calculations.E.g. Constrained Layout Guide,
Figure.tight_layout(), andfig.savefig(fname, bbox_inches='tight').
- get_label()[source]
-
Return the label used for this artist in the legend.
- get_layout_engine()[source]
- get_linewidth()[source]
-
Get the line width of the Figure rectangle.
- get_mouseover()[source]
-
Return whether this artist is queried for custom context information when the mouse cursor moves over it.
- get_path_effects()[source]
- get_picker()[source]
-
Return the picking behavior of the artist.
The possible values are described in
set_picker.See also
- get_rasterized()[source]
-
Return whether the artist is to be rasterized.
- get_size_inches()[source]
-
Return the current size of the figure in inches.
- Returns:
-
- ndarray
-
The size (width, height) of the figure in inches.
See also
Notes
The size in pixels can be obtained by multiplying with
Figure.dpi.
- get_sketch_params()[source]
-
Return the sketch parameters for the artist.
- Returns:
-
- tuple or None
-
A 3-tuple with the following elements:
- scale: The amplitude of the wiggle perpendicular to the source line.
- length: The length of the wiggle along the line.
- randomness: The scale factor by which the length is shrunken or expanded.
Returns None if no sketch parameters were set.
- get_tight_layout()[source]
-
Return whether
tight_layoutis called when drawing.
- get_tightbbox(renderer=None, bbox_extra_artists=None)[source]
-
Return a (tight) bounding box of the figure in inches.
Note that
FigureBasediffers from all other artists, which return theirBboxin pixels.Artists that have
artist.set_in_layout(False)are not included in the bbox.- Parameters:
-
- renderer
RendererBasesubclass -
Renderer that will be used to draw the figures (i.e.
fig.canvas.get_renderer()) - bbox_extra_artistslist of
ArtistorNone -
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.
- renderer
- Returns:
-
-
BboxBase -
containing the bounding box (in figure inches).
-
- get_transformed_clip_path_and_affine()[source]
-
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
- get_url()[source]
-
Return the url.
- get_visible()[source]
-
Return the visibility.
- get_window_extent(renderer=None, *args, **kwargs)[source]
-
Get the artist's bounding box in display space.
The bounding box' width and height are nonnegative.
Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0.
Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
- get_zorder()[source]
-
Return the artist's zorder.
- ginput(n=1, timeout=30, show_clicks=True, mouse_add=MouseButton.LEFT, mouse_pop=MouseButton.RIGHT, mouse_stop=MouseButton.MIDDLE)[source]
-
Blocking call to interact with a figure.
Wait until the user clicks n times on the figure, and return the coordinates of each click in a list.
There are three possible interactions:
- Add a point.
- Remove the most recently added point.
- Stop the interaction and return the points added so far.
The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop.
- Parameters:
-
- nint, default: 1
-
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
- timeoutfloat, default: 30 seconds
-
Number of seconds to wait before timing out. If zero or negative will never time out.
- show_clicksbool, default: True
-
If True, show a red cross at the location of each click.
- mouse_add
MouseButtonor None, default:MouseButton.LEFT -
Mouse button used to add points.
- mouse_pop
MouseButtonor None, default: