| [ Web Proxy ] |
| Viewing: https://matplotlib.org/stable/api/_as_gen/../../gallery/mplot3d/../../api/figure_api.html | [Back] [Original] |
matplotlib.figure#matplotlib.figure implements the following classes:
FigureTop level Artist, which holds all plot elements.
Many methods are implemented in FigureBase.
SubFigureA logical figure inside a figure, usually added to a figure (or parent SubFigure)
with Figure.add_subfigure or Figure.subfigures methods.
Figures are typically created using pyplot methods figure,
subplots, and subplot_mosaic.
fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue',
layout='constrained')
fig.suptitle('Figure')
ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium')
(Source code, 2x.png, png)
[]
Some situations call for directly instantiating a Figure class,
usually inside an application of some sort (see Embedding Matplotlib in graphical user interfaces for a
list of examples) . More information about Figures can be found at
Introduction to Figures.
The top level container for all the plot elements. |
Add an |
|
Add an |
|
Add a set of subplots to this figure. |
|
Build a layout of Axes based on ASCII art or nested lists. |
|
Low-level API for creating a |
|
List of Axes in the Figure. |
|
List of Axes in the Figure. |
|
Remove the |
|
Add a set of subfigures to this figure or subfigure. |
|
Add a |
Save the current figure as an image or vector graphic to a file. |
Add a colorbar to a plot. |
|
Place a legend on the figure. |
|
Add text to figure. |
|
Add a centered super title to the figure. |
|
Return the suptitle as string or an empty string if not set. |
|
Add a centered super xlabel to the figure. |
|
Return the supxlabel as string or an empty string if not set. |
|
Add a centered super ylabel to the figure. |
|
Return the supylabel as string or an empty string if not set. |
|
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). |
|
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). |
|
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). |
|
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). |
|
Date ticklabels often overlap, so it is useful to rotate them and right align them. |
Set the figure size in inches. |
|
Return the current size of the figure in inches. |
|
Set the height of the figure in inches. |
|
Return the figure height in inches. |
|
Set the width of the figure in inches. |
|
Return the figure width in inches. |
|
The resolution in dots per inch. |
|
Set the resolution of the figure in dots-per-inch. |
|
Return the resolution in dots per inch as a float. |
Adjust the subplot layout parameters. |
|
Set the layout engine for this figure. |
|
Adjust the padding between and around subplots. |
|
[Deprecated] Set whether and how |
|
Return whether |
|
[Deprecated] Set whether |
|
Return whether constrained layout is being used. |
|
[Deprecated] Set padding for |
|
[Deprecated] Get padding for |
See also
Blocking call to interact with a figure. |
|
Whenever the Axes state change, |
|
Blocking call to interact with the figure. |
|
Process a pick event. |
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. |
|
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. |
|
Set the line width of the Figure rectangle. |
|
Get the line width of the Figure rectangle. |
|
Set the face color of the Figure rectangle. |
|
Get the face color of the Figure rectangle. |
|
Set the edge color of the Figure rectangle. |
|
Get the edge color of the Figure rectangle. |
Add an |
|
Get a list of artists contained in the figure. |
|
Add a non-resampled image to the figure. |
See also
Clear the figure. |
|
Get the current Axes. |
|
Set the current Axes to be a and return a. |
|
Return a (tight) bounding box of the figure in inches. |
|
Get the artist's bounding box in display space, ignoring clipping. |
|
If using a GUI backend with pyplot, display the figure window. |
|
Set the canvas that contains the figure |
|
Draw the Artist (and its children) using the given renderer. |
|
Draw the figure with no output. |
|
Draw |
Matplotlib has the concept of a SubFigure, which is a logical figure inside
a parent Figure. It has many of the same methods as the parent. See
Nested Axes layouts.
(Source code, 2x.png, png)
[]
Logical figure that can be placed inside a figure. |
Add an |
|
Add an |
|
Add a set of subplots to this figure. |
|
Build a layout of Axes based on ASCII art or nested lists. |
|
Low-level API for creating a |
|
Remove the |
|
Add a |
|
Add a set of subfigures to this figure or subfigure. |
Add a colorbar to a plot. |
|
Place a legend on the figure. |
|
Add text to figure. |
|
Add a centered super title to the figure. |
|
Return the suptitle as string or an empty string if not set. |
|
Add a centered super xlabel to the figure. |
|
Return the supxlabel as string or an empty string if not set. |
|
Add a centered super ylabel to the figure. |
|
Return the supylabel as string or an empty string if not set. |
|
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). |
|
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). |
|
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). |
|
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). |
Add an |
|
Get a list of artists contained in the figure. |
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. |
|
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. |
|
Set the line width of the Figure rectangle. |
|
Get the line width of the Figure rectangle. |
|
Set the face color of the Figure rectangle. |
|
Get the face color of the Figure rectangle. |
|
Set the edge color of the Figure rectangle. |
|
Get the edge color of the Figure rectangle. |
Set the resolution of parent figure in dots-per-inch. |
|
Return the resolution of the parent figure in dots-per-inch as a float. |
Base class for Figure and SubFigure containing the methods that add
artists to the figure or subfigure, create Axes, etc.
Add an Artist to the figure.
Usually artists are added to Axes objects using
Axes.add_artist; this method can be used in the rare cases where
one needs to add artists directly to the figure instead.
Add an Axes to the figure.
Call signatures:
add_axes(rect, projection=None, polar=False, **kwargs)
add_axes(ax)
The dimensions (left, bottom, width, height) of the new
Axes. All quantities are in fractions of figure width and
height.
The projection type of the Axes. str is the name of
a custom projection, see projections. The default
None results in a 'rectilinear' projection.
If True, equivalent to projection='polar'.
Axes, optionalThe axes.Axes subclass that is instantiated. This parameter
is incompatible with projection and polar. See
axisartist for examples.
Axes, optionalShare the x or y axis with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared Axes.
A label for the returned Axes.
Axes, or a subclass of AxesThe returned Axes class depends on the projection used. It is
Axes if rectilinear projection is used and
projections.polar.PolarAxes if polar projection is used.
This method also takes the keyword arguments for
the returned Axes class. The keyword arguments for the
rectilinear Axes class Axes can be found in
the following table but there might also be other keyword
arguments if another projection is used, see the actual Axes
class.
Property |
Description |
|---|---|
{'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 |
|
float 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 |
|
bool or "auto" |
|
bool |
|
str |
|
bool |
|
object |
|
bool |
|
bool |
|
unknown |
|
list of |
|
None or bool or float or callable |
|
[left, bottom, width, height] or |
|
float or None |
|
bool |
|
(scale: float, length: float, randomness: float) |
|
bool or None |
|
unknown |
|
str |
|
str |
|
bool |
|
(lower: float, upper: float) |
|
unknown |
|
str |
|
(left: float, right: float) |
|
float greater than -0.5 |
|
unknown |
|
unknown |
|
unknown |
|
(lower: float, upper: float) |
|
unknown |
|
str |
|
(bottom: float, top: float) |
|
float greater than -0.5 |
|
unknown |
|
unknown |
|
unknown |
|
float |
Notes
In rare circumstances, add_axes may be called with a single
argument, an Axes instance already created in the present figure but
not in the figure's list of Axes.
Examples
Some simple examples:
rect = l, b, w, h
fig = plt.figure()
fig.add_axes(rect)
fig.add_axes(rect, frameon=False, facecolor='g')
fig.add_axes(rect, polar=True)
ax = fig.add_axes(rect, projection='polar')
fig.delaxes(ax)
fig.add_axes(ax)
Low-level API for creating a GridSpec that has this figure as a parent.
This is a low-level API, allowing you to create a gridspec and
subsequently add subplots based on the gridspec. Most users do
not need that freedom and should use the higher-level methods
subplots or subplot_mosaic.
Number of rows in grid.
Number of columns in grid.
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 a SubFigure to the figure as part of a subplot arrangement.
gridspec.SubplotSpecDefines the region in a parent gridspec where the subfigure will be placed.
Are passed to the SubFigure object.
See also
Add an Axes to the figure as part of a subplot arrangement.
Call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
SubplotSpec, default: (1, 1, 1)The position of the subplot described by one of
Three integers (nrows, ncols, index). The subplot will
take the index position on a grid with nrows rows and
ncols columns. index starts at 1 in the upper left corner
and increases to the right. index can also be a two-tuple
specifying the (first, last) indices (1-based, and including
last) of the subplot, e.g., fig.add_subplot(3, 1, (1, 2))
makes a subplot that spans the upper 2/3 of the figure.
A 3-digit integer. The digits are interpreted as if given
separately as three single-digit integers, i.e.
fig.add_subplot(235) is the same as
fig.add_subplot(2, 3, 5). Note that this can only be used
if there are no more than 9 subplots.
A SubplotSpec.
In rare circumstances, add_subplot may be called with a single
argument, a subplot Axes instance already created in the
present figure but not in the figure's list of Axes.
The projection type of the subplot (Axes). str is the
name of a custom projection, see projections. The
default None results in a 'rectilinear' projection.
If True, equivalent to projection='polar'.
Axes, optionalThe axes.Axes subclass that is instantiated. This parameter
is incompatible with projection and polar. See
axisartist for examples.
Axes, optionalShare the x or y axis with sharex and/or sharey.
The axis will have the same limits, ticks, and scale as the axis
of the shared Axes.
A label for the returned Axes.
AxesThe Axes of the subplot. The returned Axes can actually be an
instance of a subclass, such as projections.polar.PolarAxes for
polar projections.
This method also takes the keyword arguments for the returned Axes
base class; except for the figure argument. The keyword arguments
for the rectilinear base class Axes can be found in
the following table but there might also be other keyword
arguments if another projection is used.
Property |
Description |
|---|---|
{'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 |
|
float 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 |
|
bool or "auto" |
|
bool |
|
str |
|
bool |
|
object |
|
bool |
|
bool |
|
unknown |
|
list of |
|
None or bool or float or callable |
|
[left, bottom, width, height] or |
|
float or None |
|
bool |
|
(scale: float, length: float, randomness: float) |
|
bool or None |
|
unknown |
|
str |
|
str |
|
bool |
|
(lower: float, upper: float) |
|
unknown |
|
str |
|
(left: float, right: float) |
|
float greater than -0.5 |
|
unknown |
|
unknown |
|
unknown |
|
(lower: float, upper: float) |
|
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 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.
See also
Notes
This assumes that all Axes in axs are from the same GridSpec,
so that their SubplotSpec positions correspond to figure positions.
Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set).
Alignment persists for draw events after this is called.
See also
Notes
This assumes that all Axes in axs are from the same GridSpec,
so that their SubplotSpec positions correspond to figure positions.
Examples
Example with titles:
fig, axs = plt.subplots(1, 2)
axs[0].set_aspect('equal')
axs[0].set_title('Title 0')
axs[1].set_title('Title 1')
fig.align_titles()
Align the xlabels of subplots in the same subplot row if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row.
See also
Notes
This assumes that all Axes in axs are from the same GridSpec,
so that their SubplotSpec positions correspond to figure positions.
Examples
Example with rotated xtick labels:
fig, axs = plt.subplots(1, 2)
axs[0].tick_params(axis='x', rotation=55)
axs[0].set_xlabel('XLabel 0')
axs[1].set_xlabel('XLabel 1')
fig.align_xlabels()
Align 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.
See also
Notes
This assumes that all Axes in axs are from the same GridSpec,
so that their SubplotSpec positions correspond to figure positions.
Examples
Example with large yticks labels:
fig, axs = plt.subplots(2, 1)
axs[0].plot(np.arange(0, 1000, 50))
axs[0].set_ylabel('YLabel 0')
axs[1].set_ylabel('YLabel 1')
fig.align_ylabels()
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.
The bottom of the subplots for subplots_adjust.
The rotation angle of the xtick labels in degrees.
The horizontal alignment of the xticklabels.
Selects which ticklabels to rotate.
Clear the figure.
Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.
[Discouraged] Alias for the clear() method.
Discouraged
The use of clf() is discouraged. Use clear() instead.
Set keep_observers to True if, for example, a gui widget is tracking the Axes in the figure.
Add a colorbar to a plot.
The matplotlib.colorizer.ColorizingArtist (i.e., AxesImage,
ContourSet, etc.) described by this colorbar. This argument is
mandatory for the Figure.colorbar method but optional for the
pyplot.colorbar function, which sets the default to the current
image.
Note that one can create a colorizer.ColorizingArtist "on-the-fly"
to generate colorbars not attached to a previously drawn artist, e.g.
cr = colorizer.Colorizer(norm=norm, cmap=cmap)
fig.colorbar(colorizer.ColorizingArtist(cr), ax=ax)
Axes, optionalAxes into which the colorbar will be drawn. If None, then a new
Axes is created and the space for it will be stolen from the Axes(s)
specified in ax.
Axes or iterable or numpy.ndarray of Axes, optionalThe one or more parent Axes from which space for a new colorbar Axes will be stolen. This parameter is only used if cax is not set.
Defaults to the Axes that contains the mappable used to create the colorbar.
If cax is None, a new cax is created as an instance of
Axes. If ax is positioned with a subplotspec and use_gridspec
is True, then cax is also positioned with a subplotspec.
ColorbarThe 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.
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.
Fraction of original Axes to use for colorbar.
Fraction by which to multiply the size of the colorbar.
Ratio of long to short dimensions.
Fraction of original Axes between colorbar and new image Axes.
The anchor point of the colorbar Axes. Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
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.
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.
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.
If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular.
If None, ticks are determined automatically from the input.
If None, ScalarFormatter is used.
Format strings, e.g., "%4.2e" or "{x:.2e}", are supported.
An alternative Formatter may be given instead.
Whether to draw lines at color boundaries.
The label on the colorbar's long axis.
If unset, the colormap will be displayed on a 0-1 scale.
If sequences, values must have a length 1 less than boundaries. For
each region delimited by adjacent entries in boundaries, the color mapped
to the corresponding value in values will be used. The size of each
region is determined by the spacing parameter.
Normally only useful for indexed colors (i.e. norm=NoNorm()) or other
unusual circumstances.
For discrete colorbars (BoundaryNorm or contours), 'uniform' gives each
color the same space; 'proportional' makes the space proportional to the
data interval.
Notes
If mappable is a ContourSet, its extend kwarg is
included automatically.
The shrink kwarg provides a simple way to scale the colorbar with respect to the Axes. Note that if cax is specified, it determines the size of the colorbar, and shrink and aspect are ignored.
For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the Axes properties kwargs.
It is known that some vector graphics viewers (svg and pdf) render white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:
cbar = colorbar()
cbar.solids.set_edgecolor("face")
draw()
However, this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
Test whether the mouse event occurred on the figure.
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (Artist.get_visible
returns False).
RendererBase subclass.Notes
This method is overridden in the Artist subclasses.
The root Figure. To get the parent of a SubFigure, use the get_figure method.
Return the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
Figure.patch.get_visible().
Get the current Axes.
If there is currently no Axes on this Figure, a new one is created
using Figure.add_subplot. (To test whether there is currently an
Axes on a Figure, check whether figure.axes is empty. To test
whether there is currently a Figure on the pyplot figure stack, check
whether pyplot.get_fignums() is empty.)
Return a list of Artists typically used in Figure.get_tightbbox.
Return the Figure or SubFigure instance the (Sub)Figure belongs to.
If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures.
Deprecated since version 3.10: From version 3.12 root will default to False.
Return the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
Figure.patch.get_visible().
Return a (tight) bounding box of the figure in inches.
Note that FigureBase differs from all other artists, which return
their Bbox in pixels.
Artists that have artist.set_in_layout(False) are not included
in the bbox.
RendererBase subclassRenderer that will be used to draw the figures (i.e.
fig.canvas.get_renderer())
Artist or NoneList 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.
BboxBasecontaining the bounding box (in figure inches).
Get the artist's bounding box in display space, ignoring clipping.
The bounding box's width and height are non-negative.
Subclasses should override for inclusion in the bounding box "tight" calculation. Default is to return an empty bounding box at 0, 0.
Warning
The extent can change due to any changes in the transform stack, such as changing the Axes limits, the figure size, the canvas used (as is done when saving a figure), or the DPI.
Relying on a once-retrieved window extent can lead to unexpected behavior in various cases such as interactive figures being resized or moved to a screen with different dpi, or figures that look fine on screen render incorrectly when saved to file.
To get accurate results you may need to manually call
savefig or draw_without_rendering to have
Matplotlib compute the rendered size.
RendererBase, optionalRenderer used to draw the figure (i.e. fig.canvas.get_renderer()).
See also
Artist.get_tightbboxGet the artist bounding box, taking clipping into account.
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 use this 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 specify
them either at artist creation or by calling the
set_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 element
selection by defining a label starting with an underscore.
This is default for all artists, so calling Figure.legend without
any arguments and without setting the labels manually will result in
no 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 possible to pass an iterable of legend artists followed by an iterable of legend 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 between plot elements and labels is only implicit by their order and can easily be mixed up.
To make a legend for all artists on all Axes, call this function with an 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'])
Artist, optionalA list of Artists (lines, patches) to be added to the legend. Use this together with labels, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The length of handles and labels should be the same in this case. If they are not, they are truncated to the smaller length.
A list of labels to show next to the artists. Use this together with handles, if you need full control on what is shown in the legend and the automatic mechanism described above is not sufficient.
The location of the legend.
The string locations place the legend at the corresponding position within the bounding box, which by default is the full figure area. The bounding box can be changed via bbox_to_anchor.
The positions are visualized below:
+--------------+--------------+---------------+
| 'upper left' |'upper center'| 'upper right' |
+--------------+--------------+---------------+
|'center left' | 'center' |'center right' |
+--------------+--------------+---------------+
| 'lower left' |'lower center'| 'lower right' |
+--------------+--------------+---------------+
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in figure coordinates (in which case bbox_to_anchor will be ignored).
For back-compatibility, 'center right' (but no other location) can also
be spelled 'right', and each "string" location can also be given as a
numeric 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 codes of the loc keyword argument can get better layout behaviour using the prefix 'outside'. There is ambiguity at the corners, so 'outside upper right' will make space for the legend above the rest of the axes in the layout, and 'outside right upper' will make space on the right side of the layout. In addition to the values of loc listed above, we have 'outside right upper', 'outside right lower', 'outside left upper', and 'outside left lower'. See Legend guide for more details.
BboxBase, 2-tuple, or 4-tuple of floatsBox that is used to position the legend in conjunction with loc. This is an advanced option for free placement of the legend. For most use cases, loc alone is sufficient.
Defaults to axes.bbox (if called as a method to Axes.legend) or
figure.bbox (if figure.legend).
Bbox coordinates are interpreted in the coordinate system given by
bbox_transform, with the default transform
Axes or Figure coordinates, depending on which legend is called.
If a 4-tuple or BboxBase is given, then it specifies the bbox
(x, y, width, height) that the legend is placed in.
To put the legend in the best location in the bottom right
quadrant of the Axes (or figure):
loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by loc at
x, y. For example, to put the legend's upper right-hand corner in the
center of the Axes (or figure) the following keywords can be used:
loc='upper right', bbox_to_anchor=(0.5, 0.5)
For more details on legend positioning, see the Legend guide.
The number of columns that the legend has.
For backward compatibility, the spelling ncol is also supported but it is discouraged. If both are given, ncols takes precedence.
FontProperties or dictThe font properties of the legend. If None (default), the current
matplotlib.rcParams will be used.
The font size of the legend. If the value is numeric the size will be the absolute font size in points. String values are relative to the current default font size. This argument is only used if prop is not specified.
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 can also 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 using rcParams["legend.labelcolor"] (default: 'None'). If None,
use rcParams["text.color"] (default: 'black').
rcParams["legend.numpoints"] (default: 1)The number of marker points in the legend when creating a legend
entry for a Line2D (line).
rcParams["legend.scatterpoints"] (default: 1)The number of marker points in the legend when creating
a legend entry for a PathCollection (scatter plot).
[0.375, 0.5, 0.3125]The vertical offset (relative to the font size) for the markers
created for a scatter plot legend entry. 0.0 is at the base the
legend text, and 1.0 is at the top. To draw all markers at the
same height, set to [0.5].
rcParams["legend.markerscale"] (default: 1.0)The relative size of legend markers compared to the originally drawn ones.
If True, legend marker is placed to the left of the legend label. If False, legend marker is placed to the right of the legend label.
If True, the legend labels are displayed in reverse order from the input. If False, the legend labels are displayed in the same order as the input.
Added in version 3.7.
rcParams["legend.frameon"] (default: True)Whether the legend should be drawn on a patch (frame).
rcParams["legend.fancybox"] (default: True)Whether round edges should be enabled around the FancyBboxPatch which
makes up the legend's background.
rcParams["legend.shadow"] (default: False)Whether to draw a shadow behind the legend.
The shadow can be configured using Patch keywords.
Customization via rcParams["legend.shadow"] (default: False) is currently not supported.
rcParams["legend.framealpha"] (default: 0.8)The alpha transparency of the legend's background.
If shadow is activated and framealpha is None, the default value is
ignored.
rcParams["legend.facecolor"] (default: 'inherit')The legend's background color.
If "inherit", use rcParams["axes.facecolor"] (default: 'white').
rcParams["legend.edgecolor"] (default: '0.8')The legend's background patch edge color.
If "inherit", use rcParams["axes.edgecolor"] (default: 'black').
rcParams["legend.linewidth"] (default: None)The legend's background patch edge linewidth.
If None, use rcParams["patch.linewidth"] (default: 1.0).
Added in version 3.11.
If mode is set to "expand" the legend will be horizontally
expanded to fill the Axes area (or bbox_to_anchor if defines
the legend's size).
TransformThe transform for the bounding box (bbox_to_anchor). For a value
of None (default) the Axes'
matplotlib.axes.Axes.transAxes transform will be used.
The legend's title. Default is no title (None).
FontProperties or dictThe font properties of the legend's title. If None (default), the
title_fontsize argument will be used if present; if title_fontsize is
also None, the current rcParams["legend.title_fontsize"] (default: None) will be used.
rcParams["legend.title_fontsize"] (default: None)The font size of the legend's title. Note: This cannot be combined with title_fontproperties. If you want to set the fontsize alongside other font properties, use the size parameter in title_fontproperties.
The alignment of the legend title and the box of entries. The entries are aligned as a single block, so that markers always lined up.
rcParams["legend.borderpad"] (default: 0.4)The fractional whitespace inside the legend border, in font-size units.
rcParams["legend.labelspacing"] (default: 0.5)The vertical space between the legend entries, in font-size units.
rcParams["legend.handlelength"] (default: 2.0)The length of the legend handles, in font-size units.
rcParams["legend.handleheight"] (default: 0.7)The height of the legend handles, in font-size units.
rcParams["legend.handletextpad"] (default: 0.8)The pad between the legend handle and text, in font-size units.
rcParams["legend.borderaxespad"] (default: 0.5)The pad between the Axes and legend border, in font-size units.
rcParams["legend.columnspacing"] (default: 2.0)The spacing between columns, in font-size units.
The custom dictionary mapping instances or types to a legend
handler. This handler_map updates the default handler map
found at matplotlib.legend.Legend.get_legend_handler_map.
Whether the legend can be dragged with the mouse.
See also
Notes
Some artists are not supported by this function. See Legend guide for details.
Set multiple properties at once.
a.set(a=A, b=B, c=C)
is equivalent to
a.set_a(A)
a.set_b(B)
a.set_c(C)
In addition to the full property names, aliases are also supported, e.g.
set(lw=2) is equivalent to set(linewidth=2), but it is an error
to pass both simultaneously.
The order of the individual setter calls matches the order of parameters
in set(). However, most properties do not depend on each other so
that order is rarely relevant.
Supported properties are
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
float or None
bool
BboxBaseor Nonebool
Patch or (Path, Transform) or None
unknown
bool
str
bool
object
number
bool
list of
AbstractPathEffectNone or bool or float or callable
bool
(scale: float, length: float, randomness: float)
bool or None
str
bool
float
Deprecated since version 3.10: Currently this method will raise an exception if fig is anything other
than the root Figure this (Sub)Figure is on. In future it will always
raise an exception.
Set the figure's background patch visibility, i.e.
whether the figure background will be drawn. Equivalent to
Figure.patch.set_visible().
Set the line width of the Figure rectangle.
Add a set of subfigures to this figure or subfigure.
A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See Figure subfigures.
Changed in version 3.10: subfigures are now added in row-major order.
Number of rows/columns of the subfigure grid.
If True, extra dimensions are squeezed out from the returned array of subfigures.
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 using
constrained layout (see ConstrainedLayoutEngine), or zero if
not using a layout engine.
Defines the relative widths of the columns. Each column gets a
relative width of width_ratios[i] / sum(width_ratios).
If not given, all columns will have the same width.
Defines the relative heights of the rows. Each row gets a
relative height of height_ratios[i] / sum(height_ratios).
If not given, all rows will have the same height.
Build a layout of Axes based on ASCII art or nested lists.
This is a helper function to build complex GridSpec layouts visually.
See Complex and semantic figure composition (subplot_mosaic) for an example and full API documentation
A visual layout of how you want your Axes to be arranged labeled 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 lists of the same form to create nested layouts.
If input is a str, then it can either be a multi-line string of the form
'''
AAE
C.E
'''
where each character is a column and each line is a row. Or it
can be a single-line string where rows are separated by ;:
'AB;CC'
The string notation allows only single character Axes labels and does not support nesting but is very terse.
The Axes identifiers may be str or a non-iterable hashable
object (e.g. tuple s may not be used).
If True, the x-axis (sharex) or y-axis (sharey) will be shared
among all subplots. In that case, tick label visibility and axis
units behave as for subplots. If False, each subplot's x- or
y-axis will be independent.
Defines the relative widths of the columns. Each column gets a
relative width of width_ratios[i] / sum(width_ratios).
If not given, all columns will have the same width. Equivalent
to gridspec_kw={'width_ratios': [...]}. In the case of nested
layouts, this argument applies only to the outer layout.
Defines the relative heights of the rows. Each row gets a
relative height of height_ratios[i] / sum(height_ratios).
If not given, all rows will have the same height. Equivalent
to gridspec_kw={'height_ratios': [...]}. In the case of nested
layouts, this argument applies only to the outer layout.
Dictionary with keywords passed to the Figure.add_subplot call
used to create each subplot. These values may be overridden by
values in per_subplot_kw.
A dictionary mapping the Axes identifiers or tuples of identifiers
to a dictionary of keyword arguments to be passed to the
Figure.add_subplot call used to create each subplot. The values
in these dictionaries have precedence over the values in
subplot_kw.
If mosaic 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.
Dictionary with keywords passed to the GridSpec constructor used
to create the grid the subplots are placed on. In the case of
nested layouts, this argument applies only to the outer layout.
For more complex layouts, users should use Figure.subfigures
to create the nesting.
Entry in the layout to mean "leave this space empty". Defaults
to '.'. Note, if layout is a string, it is processed via
inspect.cleandoc to remove leading white space, which may
interfere with using white-space as the empty sentinel.
A dictionary mapping the labels to the Axes objects. The order of the Axes is left-to-right and top-to-bottom of their position in the total layout.
Add a set of subplots to this figure.
This utility wrapper makes it convenient to create common layouts of subplots in a single call.
Number of rows/columns of the subplot grid.
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 tick
labels of the bottom subplot are created. Similarly, when subplots
have a shared y-axis along a row, only the y tick labels of the
first column subplot are created. To later turn other subplots'
ticklabels on, use tick_params.
When subplots have a shared axis that has units, calling
Axis.set_units will update each axis with the new units.
Note that it is not possible to unshare axes.
If True, extra dimensions are squeezed out from the returned array of Axes:
if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.
for NxM, subplots with N>1 and M>1 are returned as a 2D array.
If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
Defines the relative widths of the columns. Each column gets a
relative width of width_ratios[i] / sum(width_ratios).
If not given, all columns will have the same width. Equivalent
to gridspec_kw={'width_ratios': [...]}.
Defines the relative heights of the rows. Each row gets a
relative height of height_ratios[i] / sum(height_ratios).
If not given, all rows will have the same height. Equivalent
to gridspec_kw={'height_ratios': [...]}.
Dict with keywords passed to the Figure.add_subplot call used to
create each subplot.
Dict with keywords passed to the
GridSpec constructor used to create
the grid the subplots are placed on.
Examples
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
# Create a figure
fig = plt.figure()
# Create a subplot
ax = fig.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')
# Create two subplots and unpack the output array immediately
ax1, ax2 = fig.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
# Create four polar Axes and access them through the returned array
axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar'))
axes[0, 0].plot(x, y)
axes[1, 1].scatter(x, y)
# Share an X-axis with each column of subplots
fig.subplots(2, 2, sharex='col')
# Share a Y-axis with each row of subplots
fig.subplots(2, 2, sharey='row')
# Share both X- and Y-axes with all subplots
fig.subplots(2, 2, sharex='all', sharey='all')
# Note that this is the same as
fig.subplots(2, 2, sharex=True, sharey=True)
Adjust the subplot layout parameters.
Unset parameters are left unmodified; initial values are given by
rcParams["figure.subplot.[name]"].
(Source code, png)
[]
The position of the left edge of the subplots, as a fraction of the figure width.
The position of the right edge of the subplots, as a fraction of the figure width.
The position of the bottom edge of the subplots, as a fraction of the figure height.
The position of the top edge of the subplots, as a fraction of the figure height.
The width of the padding between subplots, as a fraction of the average Axes width.
The height of the padding between subplots, as a fraction of the average Axes height.
Add a centered super title to the figure.
The super title text.
The x location of the text in figure coordinates.
The y location of the text in figure coordinates.
The horizontal alignment of the text relative to (x, y).
The vertical alignment of the text relative to (x, y).
rcParams["figure.titlesize"] (default: 'large')The font size of the text. See Text.set_size for possible
values.
rcParams["figure.titleweight"] (default: 'normal')The font weight of the text. See Text.set_weight for possible
values.
The Text instance of the super title.
A dict of font properties. If fontproperties is given the
default values for font size and weight are taken from the
FontProperties defaults. rcParams["figure.titlesize"] (default: 'large') and
rcParams["figure.titleweight"] (default: 'normal') are ignored in this case.
Additional kwargs are matplotlib.text.Text properties.
Add a centered super xlabel to the figure.
The super xlabel text.
The x location of the text in figure coordinates.
The y location of the text in figure coordinates.
The horizontal alignment of the text relative to (x, y).
The vertical alignment of the text relative to (x, y).
rcParams["figure.labelsize"] (default: 'large')The font size of the text. See Text.set_size for possible
values.
rcParams["figure.labelweight"] (default: 'normal')The font weight of the text. See Text.set_weight for possible
values.
The Text instance of the super xlabel.
A dict of font properties. If fontproperties is given the
default values for font size and weight are taken from the
FontProperties defaults. rcParams["figure.labelsize"] (default: 'large') and
rcParams["figure.labelweight"] (default: 'normal') are ignored in this case.
Additional kwargs are matplotlib.text.Text properties.
Add a centered super ylabel to the figure.
The super ylabel text.
The x location of the text in figure coordinates.
The y location of the text in figure coordinates.
The horizontal alignment of the text relative to (x, y).
The vertical alignment of the text relative to (x, y).
rcParams["figure.labelsize"] (default: 'large')The font size of the text. See Text.set_size for possible
values.
rcParams["figure.labelweight"] (default: 'normal')The font weight of the text. See Text.set_weight for possible
values.
The Text instance of the super ylabel.
A dict of font properties. If fontproperties is given the
default values for font size and weight are taken from the
FontProperties defaults. rcParams["figure.labelsize"] (default: 'large') and
rcParams["figure.labelweight"] (default: 'normal') are ignored in this case.
Additional kwargs are matplotlib.text.Text properties.
Add text to figure.
The position to place the text. By default, this is in figure coordinates, floats in [0, 1]. The coordinate system can be changed using the transform keyword.
The text string.
A dictionary to override the default text properties. If not given,
the defaults are determined by rcParams["font.*"]. Properties passed as
kwargs override the corresponding ones given in fontdict.
Text propertiesOther miscellaneous text parameters.
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 |
|
float or None |
|
bool |
|
bool |
|
dict with properties for |
|
unknown |
|
unknown |
|
unknown |
|
|
{FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} |
list of str, or tuple of str, or None |
|
float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} |
|
{a numeric value in range 0-1000, 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'} |
|
{'normal', 'italic', 'oblique'} |
|
{'normal', 'small-caps'} |
|
|
{a numeric value in range 0-1000, 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'} |
str |
|
{'left', 'center', 'right'} |
|
bool |
|
object |
|
str or None |
|
'normal' or float, default: 'normal' |
|
str |
|
bool |
|
|
{'left', 'right', 'center'} |
bool |
|
list of |
|
None or bool or float or callable |
|
(float, float) |
|
bool |
|
float or {'vertical', 'horizontal'} |
|
{None, 'default', 'anchor', 'xtick', 'ytick'} |
|
(scale: float, length: float, randomness: float) |
|
bool or None |
|
object |
|
bool |
|
str |
|
bool, default: |
|
{'baseline', 'bottom', 'center', 'center_baseline', 'top'} |
|
bool |
|
bool |
|
float |
|
float |
|
float |
See also
Calculate the width and height for a figure with a specified aspect ratio.
While the height is taken from rcParams["figure.figsize"] (default: [6.4, 4.8]), the width is
adjusted to match the desired aspect ratio. Additionally, it is ensured
that 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.
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 of columns, so that the array could be fitted in the figure undistorted.
The width and height of the figure in inches.
Notes
If you want to create an Axes within the figure, that still preserves the aspect ratio, be sure to create it with equal width and height. See examples 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)
| Web Proxy Viewer | New URL | Original Page |