matplotlib.figure
implements the following classes:
Figure
Top level Artist
, which holds all plot elements. Many methods are implemented in FigureBase
.
SubFigure
A logical figure inside a figure, usually added to a figure (or parent SubFigure
) with Figure.add_subfigure
or Figure.subfigures
methods (provisional API v3.4).
SubplotParams
Control the default spacing between subplots.
The top level container for all the plot elements.
The Figure instance supports callbacks through a callbacks attribute which is a CallbackRegistry
instance. The events you can connect to are 'dpi_changed', and the callback will be called with func(fig)
where fig is the Figure
instance.
The Rectangle
instance representing the figure background patch.
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.
rcParams["figure.figsize"]
(default: [6.4, 4.8]
)
Figure dimension (width, height)
in inches.
rcParams["figure.dpi"]
(default: 100.0
)
Dots per inch.
rcParams["figure.facecolor"]
(default: 'white'
)
The figure patch facecolor.
rcParams["figure.edgecolor"]
(default: 'white'
)
The figure patch edge color.
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
rcParams["figure.frameon"]
(default: True
)
If False
, suppress drawing the figure background patch.
SubplotParams
Subplot parameters. If not given, the default subplot parameters rcParams["figure.subplot.*"]
are used.
rcParams["figure.autolayout"]
(default: False
)
Whether to use the tight layout mechanism. See set_tight_layout
.
Discouraged
The use of this parameter is discouraged. Please use layout='tight'
instead for the common case of tight_layout=True
and use set_tight_layout
otherwise.
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.
The layout mechanism for positioning of plot elements. Supported values:
'constrained': The constrained layout solver usually gives the best layout results and is thus recommended. However, it is computationally expensive and can be slow for complex figures with many elements.
See Constrained Layout Guide for examples.
Figure.set_tight_layout
for further details.If not given, fall back to using the parameters tight_layout and constrained_layout, including their config defaults rcParams["figure.autolayout"]
(default: False
) and rcParams["figure.constrained_layout.use"]
(default: False
).
Figure
properties, 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 | |
scalar or None | |
bool | |
FigureCanvas | |
bool | |
Patch or (Path, Transform) or None | |
bool or dict or None | |
float, default: | |
float | |
color | |
color | |
float | |
float | |
bool | |
str | |
bool | |
object | |
number | |
None or bool or float or callable | |
bool | |
(float, float) or float | |
(scale: float, length: float, randomness: float) | |
bool or None | |
bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None | |
str | |
bool | |
float |
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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
Axes
, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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)
Whenever the Axes state change, func(self)
will be called.
Add a callback function that will be called whenever one of the Artist
's properties changes.
The callback function. It must have the signature:
def func(artist: Artist) -> Any
where artist is the calling Artist
. Return values may exist but are ignored.
The observer id associated with the callback. This id can be used for removing the callback with remove_callback
later.
See also
Return a GridSpec
that has this figure as a parent. This allows complex layout of Axes in the figure.
Number of rows in grid.
Number or columns in grid.
Keyword arguments are passed to GridSpec
.
See also
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.SubplotSpec
Defines 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
fig.add_subplot(3, 1, (1, 2))
makes a subplot that spans the upper 2/3 of the figure.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.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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
axes.SubplotBase
, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used. The returned Axes is then a subplot subclass of the base class.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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 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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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.
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.
Do not modify the list itself. Instead, use add_axes
, add_subplot
or delaxes
to add or remove an Axes.
Note: The Figure.axes
property and get_axes
method are equivalent.
Clear the figure.
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.cm.ScalarMappable
(i.e., AxesImage
, ContourSet
, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar
method but optional for the pyplot.colorbar
function, which sets the default to the current image.
Note that one can create a ScalarMappable
"on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
Axes
, optional
Axes into which the colorbar will be drawn.
Axes
, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
If cax is None
, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True
, cax is created as an instance of Subplot using the gridspec
module.
Colorbar
Additional keyword arguments are of two kinds:
axes properties:
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.
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.
colorbar properties:
Property | Description |
---|---|
extend | {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. 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 with 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. |
extendrect | bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. |
spacing | {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. |
ticks | None or list of ticks or Locator If None, ticks are determined automatically from the input. |
format | None or str or Formatter If None, |
drawedges | bool Whether to draw lines at color boundaries. |
label | str The label on the colorbar's long axis. |
The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property | Description |
---|---|
boundaries | None or a sequence |
values | None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. |
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).
Test whether the mouse event occurred on the figure.
Convert x using the unit type of the xaxis.
If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
Convert y using the unit type of the yaxis.
If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
The resolution in dots per inch.
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.
This method is overridden in the Artist subclasses.
Draw Artist
a only.
This method can only be used after an initial draw of the figure, because that creates and caches the renderer needed here.
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).
Use layoutgrid
to determine pos positions within Axes.
See also set_constrained_layout_pads
.
Add a non-resampled image to the figure.
The image is attached to the lower or upper left corner depending on origin.
The image data. This is an array of one of the following shapes:
The x/y image offset in pixels.
The alpha blending value.
matplotlib.colors.Normalize
A Normalize
instance to map the luminance to the interval [0, 1].
matplotlib.colors.Colormap
, default: rcParams["image.cmap"]
(default: 'viridis'
)
The colormap to use.
If norm is not given, these values set the data limits for the colormap.
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.
If True, resize the figure to match the given image size.
Additional kwargs are Artist
kwargs passed on to FigureImage
.
figimage complements the Axes image (imshow
) which will be resampled to fit the current Axes. If you want a resampled image to fill the entire figure, you can define an Axes
with extent [0, 0, 1, 1].
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()
Find artist objects.
Recursively find all Artist
instances contained in the artist.
A filter criterion for the matches. This can be
def match(artist: Artist) -> bool
. The result will only contain artists for which the function returns True.Line2D
. The result will only contain artists of this class or its subclasses (isinstance
check).Include self in the list to be checked for a match.
Artist
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
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.)
The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
Return filter function to be used for agg filter.
Return the alpha value used for blending - not supported on all backends.
Return whether the artist is animated.
List of Axes in the Figure. You can access and modify the Axes in the Figure through this list.
Do not modify the list itself. Instead, use add_axes
, add_subplot
or delaxes
to add or remove an Axes.
Note: The Figure.axes
property and get_axes
method are equivalent.
Get a list of artists contained in the figure.
Return the clipbox.
Return whether the artist uses clipping.
Return the clip path.
Return whether constrained layout is being used.
Get padding for constrained_layout
.
Returns a list of w_pad, h_pad
in inches and wspace
and hspace
as fractions of the subplot.
If True
, then convert from inches to figure relative.
Return the cursor data for a given event.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data
can convert the data to a string representation.
The only current use case is displaying the z-value of an AxesImage
in the status bar of a plot window, while moving the mouse.
See also
Return the resolution in dots per inch as a float.
Get the edge color of the Figure rectangle.
Get the face color of the Figure rectangle.
Return the figure height in inches.
Return the figure width in inches.
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible()
.
Return the group id.
Return boolean flag, True
if artist is included in layout calculations.
E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Return the label used for this artist in the legend.
Get the line width of the Figure rectangle.
Return the picking behavior of the artist.
The possible values are described in set_picker
.
See also
Return whether the artist is to be rasterized.
Return the current size of the figure in inches.
The size (width, height) of the figure in inches.
See also
The size in pixels can be obtained by multiplying with Figure.dpi
.
Return the sketch parameters for the artist.
A 3-tuple with the following elements:
Returns None if no sketch parameters were set.
Return whether tight_layout
is called when drawing.
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
subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()
)
Artist
or None
List of artists to include in the tight bounding box. If None
(default), then all artist children of each Axes are included in the tight bounding box.
BboxBase
containing the bounding box (in figure inches).
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
Return the url.
Return the visibility.
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.
Return the artist's zorder.
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:
The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop.
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
Number of seconds to wait before timing out. If zero or negative will never timeout.
If True, show a red cross at the location of each click.
MouseButton
or None, default: MouseButton.LEFT
Mouse button used to add points.
MouseButton
or None, default: MouseButton.RIGHT
Mouse button used to remove the most recently added point.
MouseButton
or None, default: MouseButton.MIDDLE
Mouse button used to stop input.
A list of the clicked (x, y) coordinates.
The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.
Return whether units are set on any axis.
Return whether the Artist has an explicitly set transform.
This is True after set_transform
has been called.
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
, optional
A 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.
rcParams["legend.loc"]
(default: 'best'
) ('best' for axes, 'upper right' for figures)
The location of the legend.
The strings 'upper left', 'upper right', 'lower left', 'lower right'
place the legend at the corresponding corner of the axes/figure.
The strings 'upper center', 'lower center', 'center left', 'center right'
place the legend at the center of the corresponding edge of the axes/figure.
The string 'center'
places the legend at the center of the axes/figure.
The string 'best'
places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes 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" locations can also be given as a numeric value:
Location String | Location Code |
---|---|
'best' | 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 |
BboxBase
, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox
(if called as a method to Axes.legend
) or figure.bbox
(if Figure.legend
). This argument allows arbitrary placement of the 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)
The number of columns that the legend has.
matplotlib.font_manager.FontProperties
or dict
The 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 with 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.
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.
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 take rcParams["axes.edgecolor"]
(default: 'black'
).
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).
matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None
(default) the Axes' transAxes
transform will be used.
The legend's title. Default is no title (None
).
matplotlib.font_manager.FontProperties
or dict
The 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.
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
.
See also
Some artists are not supported by this function. See Legend guide for details.
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it.
See also get_cursor_data()
, ToolCursorPosition
and NavigationToolbar2
.
Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See also
Process a pick event.
Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set.
See also
Return whether the artist is pickable.
See also
Return a dictionary of all the properties of the artist.
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle
. Call relim
to update the axes limits if desired.
Note: relim
will not see collections even if the collection was added to the axes with autolim = True.
Note: there is no support for removing the artist's legend entry.
Remove a callback based on its observer id.
See also
Save the current figure.
Call signature:
savefig(fname, *, dpi='figure', format=None, metadata=None, bbox_inches=None, pad_inches=0.1, facecolor='auto', edgecolor='auto', backend=None, **kwargs )
The available output formats depend on the backend being used.
A path, or a Python file-like object, or possibly some backend-dependent object such as matplotlib.backends.backend_pdf.PdfPages
.
If format is set, it determines the output format, and the file is saved as fname. Note that fname is used verbatim, and there is no attempt to make the extension, if any, of fname match format, and no extension is appended.
If format is not set, then the format is inferred from the extension of fname, if there is one. If format is not set and fname has no extension, then the file is saved with rcParams["savefig.format"]
(default: 'png'
) and the appropriate extension is appended to fname.
rcParams["savefig.dpi"]
(default: 'figure'
)
The resolution in dots per inch. If 'figure', use the figure's dpi value.
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under fname.
Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend:
Bbox
, default: rcParams["savefig.bbox"]
(default: None
)
Bounding box in inches: only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure.
rcParams["savefig.pad_inches"]
(default: 0.1
)
Amount of padding around the figure when bbox_inches is 'tight'.
rcParams["savefig.facecolor"]
(default: 'auto'
)
The facecolor of the figure. If 'auto', use the current figure facecolor.
rcParams["savefig.edgecolor"]
(default: 'auto'
)
The edgecolor of the figure. If 'auto', use the current figure edgecolor.
Use a non-default backend to render the file, e.g. to render a png file with the "cairo" backend rather than the default "agg", or a pdf file with the "pgf" backend rather than the default "pdf". Note that the default backend is normally sufficient. See The builtin backends for a list of valid backends for each file format. Custom backends can be referenced as "module://...".
Currently only supported by the postscript backend.
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.
If True, the Axes patches will all be transparent; the Figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs.
If False has no effect and the color of the Axes and Figure patches are unchanged (unless the Figure patch is specified via the facecolor and/or edgecolor keyword arguments in which case those colors are used).
The transparency of these patches will be restored to their original values upon exit of this function.
This is useful, for example, for displaying a plot on top of a colored background on a web page.
Artist
, optional
A list of extra artists that will be considered when the tight bbox is calculated.
Additional keyword arguments that are passed to PIL.Image.Image.save
when saving the figure.
Set the current Axes to be a and return a.
Set multiple properties at once.
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 | |
scalar or None | |
bool | |
FigureCanvas | |
bool | |
Patch or (Path, Transform) or None | |
bool or dict or None | |
float, default: | |
float | |
color | |
color | |
float | |
float | |
bool | |
str | |
bool | |
object | |
number | |
None or bool or float or callable | |
bool | |
(float, float) or float | |
(scale: float, length: float, randomness: float) | |
bool or None | |
bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None | |
str | |
bool | |
float |
Set the agg filter.
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
Set the alpha value used for blending - not supported on all backends.
alpha must be within the 0-1 range, inclusive.
Set whether the artist is intended to be used in an animation.
If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist
/ Axes.draw_artist
explicitly on the artist. This appoach is used to speed up animations using blitting.
See also matplotlib.animation
and Faster rendering by using blitting.
Set the canvas that contains the figure
Set whether the artist uses clipping.
When False artists will be visible outside of the axes which can lead to unexpected results.
Set the artist's clip path.
Patch
or Path
or TransformedPath
or None
The clip path. If given a Path
, transform must be provided as well. If None, a previously set clip path is removed.
Transform
, optional
Only used if path is a Path
, in which case the given Path
is converted to a TransformedPath
using transform.
For efficiency, if path is a Rectangle
this method will set the clipping box to the corresponding rectangle and set the clipping path to None
.
For technical reasons (support of set
), a tuple (path, transform) is also accepted as a single positional parameter.
Set whether constrained_layout
is used upon drawing. If None, rcParams["figure.constrained_layout.use"]
(default: False
) value will be used.
When providing a dict containing the keys w_pad
, h_pad
the default constrained_layout
paddings will be overridden. These pads are in inches and default to 3.0/72.0. w_pad
is the width padding and h_pad
is the height padding.
Set padding for constrained_layout
.
Tip: The parameters can be passed from a dictionary by using fig.set_constrained_layout(**pad_dict)
.
rcParams["figure.constrained_layout.w_pad"]
(default: 0.04167
)
Width padding in inches. This is the pad around Axes and is meant to make sure there is enough room for fonts to look good. Defaults to 3 pts = 0.04167 inches
rcParams["figure.constrained_layout.h_pad"]
(default: 0.04167
)
Height padding in inches. Defaults to 3 pts.
rcParams["figure.constrained_layout.wspace"]
(default: 0.02
)
Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace.
rcParams["figure.constrained_layout.hspace"]
(default: 0.02
)
Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace.
Set the resolution of the figure in dots-per-inch.
Set the edge color of the Figure rectangle.
Set the face color of the Figure rectangle.
Set the height of the figure in inches.
See set_size_inches
.
Set the width of the figure in inches.
See set_size_inches
.
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible()
.
Set the (group) id for the artist.
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Set a label that will be displayed in the legend.
s will be converted to a string by calling str
.
Set the line width of the Figure rectangle.
Set the path effects.
AbstractPathEffect
Define the picking behavior of the artist.
This can be one of the following:
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
Force rasterized (bitmap) drawing for vector graphics output.
Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued.
This setting is ignored for pixel-based output.
See also Rasterization for vector graphics.
Set the figure size in inches.
Call signatures:
fig.set_size_inches(w, h) # OR fig.set_size_inches((w, h))
Width and height in inches (if height not specified as a separate argument) or width.
Height in inches.
If True
, the canvas size is automatically updated, e.g., you can resize the figure window from the shell.
See also
To transform from pixels to inches divide by Figure.dpi
.
Set the sketch parameters.
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None
, or not provided, no sketch filter will be provided.
The length of the wiggle along the line, in pixels (default 128.0)
The scale factor by which the length is shrunken or expanded (default 16.0)
The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Possible values:
Set whether and how tight_layout
is called when drawing.
If a bool, sets whether to call tight_layout
upon drawing. If None
, use rcParams["figure.autolayout"]
(default: False
) instead. If a dict, pass it as kwargs to tight_layout
, overriding the default paddings.
Set the url for the artist.
Set the artist's visibility.
Set the zorder for the artist. Artists with lower zorder values are drawn first.
If using a GUI backend with pyplot, display the figure window.
If the figure was not created using figure
, it will lack a FigureManagerBase
, and this method will raise an AttributeError.
Warning
This does not manage an GUI event loop. Consequently, the figure may only be shown briefly or not shown at all if you or your environment are not managing an event loop.
Proper use cases for Figure.show
include running this from a GUI application or an IPython shell.
If you're running a pure python shell or executing a non-GUI python script, you should use matplotlib.pyplot.show
instead, which takes care of managing the event loop for you.
If True
and we are not running headless (i.e. on Linux with an unset DISPLAY), issue warning when called on a non-GUI backend.
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
x
and y
sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram.
Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1.
This attribute cannot be assigned to; however, the x
and y
lists can be modified in place as needed.
>>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax)
Add a subfigure 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.
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 a figure or rcParams when necessary.
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.
Note
This API is provisional and may be revised in the future based on early user feedback.
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:
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.
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.
Dictionary with keywords passed to the Figure.add_subplot
call used to create each subplot.
Dictionary with keywords passed to the GridSpec
constructor used to create the grid the subplots are placed on.
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):
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.
If True, extra dimensions are squeezed out from the returned array of Axes:
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.
# First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure 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 a 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]"]
.
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 suptitle to the figure.
The suptitle 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 suptitle.
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 supxlabel to the figure.
The supxlabel 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 supxlabel.
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 supylabel to the figure.
The supylabel 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 supylabel.
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 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
properties
Other 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 | |
scalar or None | |
bool | |
color | |
dict with properties for | |
unknown | |
unknown | |
unknown | |
| color |
| {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} |
| |
| 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 | |
| {'center', 'right', 'left'} |
bool | |
object | |
float (multiple of font size) | |
str | |
| {'left', 'right', 'center'} |
bool | |
None or bool or float or callable | |
(float, float) | |
bool | |
float or {'vertical', 'horizontal'} | |
{None, 'default', 'anchor'} | |
(scale: float, length: float, randomness: float) | |
bool or None | |
object | |
bool | |
str | |
bool or None | |
| {'center', 'top', 'bottom', 'baseline', 'center_baseline'} |
bool | |
bool | |
float | |
float | |
float |
See also
Adjust the padding between and around subplots.
To exclude an artist on the Axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), set a.set_in_layout(False)
for that artist.
Padding between the figure edge and the edges of subplots, as a fraction of the font size.
Padding (height/width) between edges of adjacent subplots, as a fraction of the font size.
A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit.
Update this artist's properties from the dict props.
Copy properties from other to self.
Blocking call to interact with the figure.
Wait for user input and return True if a key was pressed, False if a mouse button was pressed and None if no input was given within timeout seconds. Negative values deactivate timeout.
Base class for figure.Figure
and figure.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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
Axes
, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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 a callback function that will be called whenever one of the Artist
's properties changes.
The callback function. It must have the signature:
def func(artist: Artist) -> Any
where artist is the calling Artist
. Return values may exist but are ignored.
The observer id associated with the callback. This id can be used for removing the callback with remove_callback
later.
See also
Return a GridSpec
that has this figure as a parent. This allows complex layout of Axes in the figure.
Number of rows in grid.
Number or columns in grid.
Keyword arguments are passed to GridSpec
.
See also
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.SubplotSpec
Defines 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
fig.add_subplot(3, 1, (1, 2))
makes a subplot that spans the upper 2/3 of the figure.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.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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
axes.SubplotBase
, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used. The returned Axes is then a subplot subclass of the base class.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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 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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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.
The Axes
instance the artist resides in, or None.
Add a colorbar to a plot.
The matplotlib.cm.ScalarMappable
(i.e., AxesImage
, ContourSet
, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar
method but optional for the pyplot.colorbar
function, which sets the default to the current image.
Note that one can create a ScalarMappable
"on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
Axes
, optional
Axes into which the colorbar will be drawn.
Axes
, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
If cax is None
, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True
, cax is created as an instance of Subplot using the gridspec
module.
Colorbar
Additional keyword arguments are of two kinds:
axes properties:
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.
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.
colorbar properties:
Property | Description |
---|---|
extend | {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. 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 with 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. |
extendrect | bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. |
spacing | {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. |
ticks | None or list of ticks or Locator If None, ticks are determined automatically from the input. |
format | None or str or Formatter If None, |
drawedges | bool Whether to draw lines at color boundaries. |
label | str The label on the colorbar's long axis. |
The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property | Description |
---|---|
boundaries | None or a sequence |
values | None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. |
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).
Test whether the mouse event occurred on the figure.
Convert x using the unit type of the xaxis.
If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
Convert y using the unit type of the yaxis.
If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
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.
This method is overridden in the Artist subclasses.
Find artist objects.
Recursively find all Artist
instances contained in the artist.
A filter criterion for the matches. This can be
def match(artist: Artist) -> bool
. The result will only contain artists for which the function returns True.Line2D
. The result will only contain artists of this class or its subclasses (isinstance
check).Include self in the list to be checked for a match.
Artist
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
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.)
The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
Return filter function to be used for agg filter.
Return the alpha value used for blending - not supported on all backends.
Return whether the artist is animated.
Get a list of artists contained in the figure.
Return the clipbox.
Return whether the artist uses clipping.
Return the clip path.
Return the cursor data for a given event.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data
can convert the data to a string representation.
The only current use case is displaying the z-value of an AxesImage
in the status bar of a plot window, while moving the mouse.
See also
Get the edge color of the Figure rectangle.
Get the face color of the Figure rectangle.
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible()
.
Return the group id.
Return boolean flag, True
if artist is included in layout calculations.
E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Return the label used for this artist in the legend.
Get the line width of the Figure rectangle.
Return the picking behavior of the artist.
The possible values are described in set_picker
.
See also
Return whether the artist is to be rasterized.
Return the sketch parameters for the artist.
A 3-tuple with the following elements:
Returns None if no sketch parameters were set.
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
subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()
)
Artist
or None
List of artists to include in the tight bounding box. If None
(default), then all artist children of each Axes are included in the tight bounding box.
BboxBase
containing the bounding box (in figure inches).
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
Return the url.
Return the visibility.
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.
Return the artist's zorder.
Return whether units are set on any axis.
Return whether the Artist has an explicitly set transform.
This is True after set_transform
has been called.
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
, optional
A 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.
rcParams["legend.loc"]
(default: 'best'
) ('best' for axes, 'upper right' for figures)
The location of the legend.
The strings 'upper left', 'upper right', 'lower left', 'lower right'
place the legend at the corresponding corner of the axes/figure.
The strings 'upper center', 'lower center', 'center left', 'center right'
place the legend at the center of the corresponding edge of the axes/figure.
The string 'center'
places the legend at the center of the axes/figure.
The string 'best'
places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes 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" locations can also be given as a numeric value:
Location String | Location Code |
---|---|
'best' | 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 |
BboxBase
, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox
(if called as a method to Axes.legend
) or figure.bbox
(if Figure.legend
). This argument allows arbitrary placement of the 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)
The number of columns that the legend has.
matplotlib.font_manager.FontProperties
or dict
The 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 with 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.
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.
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 take rcParams["axes.edgecolor"]
(default: 'black'
).
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).
matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None
(default) the Axes' transAxes
transform will be used.
The legend's title. Default is no title (None
).
matplotlib.font_manager.FontProperties
or dict
The 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.
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
.
See also
Some artists are not supported by this function. See Legend guide for details.
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it.
See also get_cursor_data()
, ToolCursorPosition
and NavigationToolbar2
.
Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See also
Process a pick event.
Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set.
See also
Return whether the artist is pickable.
See also
Return a dictionary of all the properties of the artist.
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle
. Call relim
to update the axes limits if desired.
Note: relim
will not see collections even if the collection was added to the axes with autolim = True.
Note: there is no support for removing the artist's legend entry.
Remove a callback based on its observer id.
See also
Set the current Axes to be a and return a.
Set multiple properties at once.
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 | |
scalar or None | |
bool | |
bool | |
Patch or (Path, Transform) or None | |
color | |
color | |
bool | |
str | |
bool | |
object | |
number | |
None or bool or float or callable | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
bool | |
float |
Set the agg filter.
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
Set the alpha value used for blending - not supported on all backends.
alpha must be within the 0-1 range, inclusive.
Set whether the artist is intended to be used in an animation.
If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist
/ Axes.draw_artist
explicitly on the artist. This appoach is used to speed up animations using blitting.
See also matplotlib.animation
and Faster rendering by using blitting.
Set whether the artist uses clipping.
When False artists will be visible outside of the axes which can lead to unexpected results.
Set the artist's clip path.
Patch
or Path
or TransformedPath
or None
The clip path. If given a Path
, transform must be provided as well. If None, a previously set clip path is removed.
Transform
, optional
Only used if path is a Path
, in which case the given Path
is converted to a TransformedPath
using transform.
For efficiency, if path is a Rectangle
this method will set the clipping box to the corresponding rectangle and set the clipping path to None
.
For technical reasons (support of set
), a tuple (path, transform) is also accepted as a single positional parameter.
Set the edge color of the Figure rectangle.
Set the face color of the Figure rectangle.
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible()
.
Set the (group) id for the artist.
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Set a label that will be displayed in the legend.
s will be converted to a string by calling str
.
Set the line width of the Figure rectangle.
Set the path effects.
AbstractPathEffect
Define the picking behavior of the artist.
This can be one of the following:
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
Force rasterized (bitmap) drawing for vector graphics output.
Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued.
This setting is ignored for pixel-based output.
See also Rasterization for vector graphics.
Set the sketch parameters.
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None
, or not provided, no sketch filter will be provided.
The length of the wiggle along the line, in pixels (default 128.0)
The scale factor by which the length is shrunken or expanded (default 16.0)
The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Possible values:
Set the url for the artist.
Set the artist's visibility.
Set the zorder for the artist. Artists with lower zorder values are drawn first.
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
x
and y
sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram.
Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1.
This attribute cannot be assigned to; however, the x
and y
lists can be modified in place as needed.
>>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax)
Add a subfigure 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.
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 a figure or rcParams when necessary.
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.
Note
This API is provisional and may be revised in the future based on early user feedback.
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:
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.
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.
Dictionary with keywords passed to the Figure.add_subplot
call used to create each subplot.
Dictionary with keywords passed to the GridSpec
constructor used to create the grid the subplots are placed on.
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):
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.
If True, extra dimensions are squeezed out from the returned array of Axes:
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.
# First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure 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 a 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]"]
.
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 suptitle to the figure.
The suptitle 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 suptitle.
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 supxlabel to the figure.
The supxlabel 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 supxlabel.
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 supylabel to the figure.
The supylabel 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 supylabel.
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 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
properties
Other 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 | |
scalar or None | |
bool | |
color | |
dict with properties for | |
unknown | |
unknown | |
unknown | |
| color |
| {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} |
| |
| 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 | |
| {'center', 'right', 'left'} |
bool | |
object | |
float (multiple of font size) | |
str | |
| {'left', 'right', 'center'} |
bool | |
None or bool or float or callable | |
(float, float) | |
bool | |
float or {'vertical', 'horizontal'} | |
{None, 'default', 'anchor'} | |
(scale: float, length: float, randomness: float) | |
bool or None | |
object | |
bool | |
str | |
bool or None | |
| {'center', 'top', 'bottom', 'baseline', 'center_baseline'} |
bool | |
bool | |
float | |
float | |
float |
See also
Update this artist's properties from the dict props.
Copy properties from other to self.
Logical figure that can be placed inside a figure.
Typically instantiated using Figure.add_subfigure
or SubFigure.add_subfigure
, or SubFigure.subfigures
. A subfigure has the same methods as a figure except for those particularly tied to the size or dpi of the figure, and is confined to a prescribed region of the figure. For example the following puts two subfigures side-by-side:
fig = plt.figure() sfigs = fig.subfigures(1, 2) axsL = sfigs[0].subplots(1, 2) axsR = sfigs[1].subplots(2, 1)
figure.Figure
or figure.SubFigure
Figure or subfigure that contains the SubFigure. SubFigures can be nested.
gridspec.SubplotSpec
Defines the region in a parent gridspec where the subfigure will be placed.
rcParams["figure.facecolor"]
(default: 'white'
)
The figure patch face color.
rcParams["figure.edgecolor"]
(default: 'white'
)
The figure patch edge color.
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
rcParams["figure.frameon"]
(default: True
)
If False
, suppress drawing the figure background patch.
SubFigure
properties, 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 | |
scalar or None | |
bool | |
bool | |
Patch or (Path, Transform) or None | |
color | |
color | |
bool | |
str | |
bool | |
object | |
number | |
None or bool or float or callable | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
bool | |
float |
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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
Axes
, or a subclass of Axes
The returned axes class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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 a callback function that will be called whenever one of the Artist
's properties changes.
The callback function. It must have the signature:
def func(artist: Artist) -> Any
where artist is the calling Artist
. Return values may exist but are ignored.
The observer id associated with the callback. This id can be used for removing the callback with remove_callback
later.
See also
Return a GridSpec
that has this figure as a parent. This allows complex layout of Axes in the figure.
Number of rows in grid.
Number or columns in grid.
Keyword arguments are passed to GridSpec
.
See also
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.SubplotSpec
Defines 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
fig.add_subplot(3, 1, (1, 2))
makes a subplot that spans the upper 2/3 of the figure.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.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
, optional
The axes.Axes
subclass that is instantiated. This parameter is incompatible with projection and polar. See axisartist for examples.
Axes
, optional
Share the x or y axis
with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared axes.
A label for the returned Axes.
axes.SubplotBase
, or another subclass of Axes
The Axes of the subplot. The returned Axes base class depends on the projection used. It is Axes
if rectilinear projection is used and projections.polar.PolarAxes
if polar projection is used. The returned Axes is then a subplot subclass of the base class.
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
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.
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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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 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.
This assumes that axs
are from the same GridSpec
, so that their SubplotSpec
positions correspond to figure positions.
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.
List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list.
Do not modify the list itself. Instead, use add_axes
, add_subplot
or delaxes
to add or remove an Axes.
Note: The SubFigure.axes
property and get_axes
method are equivalent.
Add a colorbar to a plot.
The matplotlib.cm.ScalarMappable
(i.e., AxesImage
, ContourSet
, etc.) described by this colorbar. This argument is mandatory for the Figure.colorbar
method but optional for the pyplot.colorbar
function, which sets the default to the current image.
Note that one can create a ScalarMappable
"on-the-fly" to generate colorbars not attached to a previously drawn artist, e.g.
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
Axes
, optional
Axes into which the colorbar will be drawn.
Axes
, list of Axes, optional
One or more parent axes from which space for a new colorbar axes will be stolen, if cax is None. This has no effect if cax is set.
If cax is None
, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True
, cax is created as an instance of Subplot using the gridspec
module.
Colorbar
Additional keyword arguments are of two kinds:
axes properties:
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.
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.
colorbar properties:
Property | Description |
---|---|
extend | {'neither', 'both', 'min', 'max'} If not 'neither', make pointed end(s) for out-of- range values. 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 with 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. |
extendrect | bool If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. |
spacing | {'uniform', 'proportional'} Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. |
ticks | None or list of ticks or Locator If None, ticks are determined automatically from the input. |
format | None or str or Formatter If None, |
drawedges | bool Whether to draw lines at color boundaries. |
label | str The label on the colorbar's long axis. |
The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property | Description |
---|---|
boundaries | None or a sequence |
values | None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the colormapped to the corresponding value in values will be used. |
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).
Test whether the mouse event occurred on the figure.
Convert x using the unit type of the xaxis.
If the artist is not in contained in an Axes or if the xaxis does not have units, x itself is returned.
Convert y using the unit type of the yaxis.
If the artist is not in contained in an Axes or if the yaxis does not have units, y itself is returned.
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.
This method is overridden in the Artist subclasses.
Find artist objects.
Recursively find all Artist
instances contained in the artist.
A filter criterion for the matches. This can be
def match(artist: Artist) -> bool
. The result will only contain artists for which the function returns True.Line2D
. The result will only contain artists of this class or its subclasses (isinstance
check).Include self in the list to be checked for a match.
Artist
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
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.)
The following kwargs are supported for ensuring the returned Axes adheres to the given projection etc., and for Axes creation if the active Axes does not exist:
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 | |
scalar or None | |
(float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', ...} | |
bool | |
{'auto', 'equal'} or float | |
bool | |
bool | |
bool | |
Callable[[Axes, Renderer], Bbox] | |
bool or 'line' | |
float or None | |
bool | |
Patch or (Path, Transform) or None | |
| color |
bool | |
str | |
bool | |
object | |
bool | |
unknown | |
None or bool or float or callable | |
[left, bottom, width, height] or | |
unknown | |
float or None | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
str | |
bool | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
unknown | |
str | |
(bottom: float, top: float) | |
float greater than -0.5 | |
{"linear", "log", "symlog", "logit", ...} or | |
unknown | |
unknown | |
float |
Return filter function to be used for agg filter.
Return the alpha value used for blending - not supported on all backends.
Return whether the artist is animated.
List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list.
Do not modify the list itself. Instead, use add_axes
, add_subplot
or delaxes
to add or remove an Axes.
Note: The SubFigure.axes
property and get_axes
method are equivalent.
Get a list of artists contained in the figure.
Return the clipbox.
Return whether the artist uses clipping.
Return the clip path.
Return whether constrained layout is being used.
Get padding for constrained_layout
.
Returns a list of w_pad, h_pad
in inches and wspace
and hspace
as fractions of the subplot.
If True
, then convert from inches to figure relative.
Return the cursor data for a given event.
Note
This method is intended to be overridden by artist subclasses. As an end-user of Matplotlib you will most likely not call this method yourself.
Cursor data can be used by Artists to provide additional context information for a given event. The default implementation just returns None.
Subclasses can override the method and return arbitrary data. However, when doing so, they must ensure that format_cursor_data
can convert the data to a string representation.
The only current use case is displaying the z-value of an AxesImage
in the status bar of a plot window, while moving the mouse.
See also
Get the edge color of the Figure rectangle.
Get the face color of the Figure rectangle.
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible()
.
Return the group id.
Return boolean flag, True
if artist is included in layout calculations.
E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Return the label used for this artist in the legend.
Get the line width of the Figure rectangle.
Return the picking behavior of the artist.
The possible values are described in set_picker
.
See also
Return whether the artist is to be rasterized.
Return the sketch parameters for the artist.
A 3-tuple with the following elements:
Returns None if no sketch parameters were set.
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
subclass
renderer that will be used to draw the figures (i.e. fig.canvas.get_renderer()
)
Artist
or None
List of artists to include in the tight bounding box. If None
(default), then all artist children of each Axes are included in the tight bounding box.
BboxBase
containing the bounding box (in figure inches).
Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
Return the url.
Return the visibility.
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.
Return the artist's zorder.
Return whether units are set on any axis.
Return whether the Artist has an explicitly set transform.
This is True after set_transform
has been called.
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
, optional
A 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.
rcParams["legend.loc"]
(default: 'best'
) ('best' for axes, 'upper right' for figures)
The location of the legend.
The strings 'upper left', 'upper right', 'lower left', 'lower right'
place the legend at the corresponding corner of the axes/figure.
The strings 'upper center', 'lower center', 'center left', 'center right'
place the legend at the center of the corresponding edge of the axes/figure.
The string 'center'
places the legend at the center of the axes/figure.
The string 'best'
places the legend at the location, among the nine locations defined so far, with the minimum overlap with other drawn artists. This option can be quite slow for plots with large amounts of data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes 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" locations can also be given as a numeric value:
Location String | Location Code |
---|---|
'best' | 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 |
BboxBase
, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with loc. Defaults to axes.bbox
(if called as a method to Axes.legend
) or figure.bbox
(if Figure.legend
). This argument allows arbitrary placement of the 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)
The number of columns that the legend has.
matplotlib.font_manager.FontProperties
or dict
The 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 with 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.
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.
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 take rcParams["axes.edgecolor"]
(default: 'black'
).
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).
matplotlib.transforms.Transform
The transform for the bounding box (bbox_to_anchor). For a value of None
(default) the Axes' transAxes
transform will be used.
The legend's title. Default is no title (None
).
matplotlib.font_manager.FontProperties
or dict
The 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.
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
.
See also
Some artists are not supported by this function. See Legend guide for details.
If this property is set to True, the artist will be queried for custom context information when the mouse cursor moves over it.
See also get_cursor_data()
, ToolCursorPosition
and NavigationToolbar2
.
Call all of the registered callbacks.
This function is triggered internally when a property is changed.
See also
Process a pick event.
Each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set.
See also
Return whether the artist is pickable.
See also
Return a dictionary of all the properties of the artist.
Remove the artist from the figure if possible.
The effect will not be visible until the figure is redrawn, e.g., with FigureCanvasBase.draw_idle
. Call relim
to update the axes limits if desired.
Note: relim
will not see collections even if the collection was added to the axes with autolim = True.
Note: there is no support for removing the artist's legend entry.
Remove a callback based on its observer id.
See also
Set the current Axes to be a and return a.
Set multiple properties at once.
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 | |
scalar or None | |
bool | |
bool | |
Patch or (Path, Transform) or None | |
color | |
color | |
bool | |
str | |
bool | |
object | |
number | |
None or bool or float or callable | |
bool | |
(scale: float, length: float, randomness: float) | |
bool or None | |
str | |
bool | |
float |
Set the agg filter.
A filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array.
Set the alpha value used for blending - not supported on all backends.
alpha must be within the 0-1 range, inclusive.
Set whether the artist is intended to be used in an animation.
If True, the artist is excluded from regular drawing of the figure. You have to call Figure.draw_artist
/ Axes.draw_artist
explicitly on the artist. This appoach is used to speed up animations using blitting.
See also matplotlib.animation
and Faster rendering by using blitting.
Set whether the artist uses clipping.
When False artists will be visible outside of the axes which can lead to unexpected results.
Set the artist's clip path.
Patch
or Path
or TransformedPath
or None
The clip path. If given a Path
, transform must be provided as well. If None, a previously set clip path is removed.
Transform
, optional
Only used if path is a Path
, in which case the given Path
is converted to a TransformedPath
using transform.
For efficiency, if path is a Rectangle
this method will set the clipping box to the corresponding rectangle and set the clipping path to None
.
For technical reasons (support of set
), a tuple (path, transform) is also accepted as a single positional parameter.
Set the edge color of the Figure rectangle.
Set the face color of the Figure rectangle.
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible()
.
Set the (group) id for the artist.
Set if artist is to be included in layout calculations, E.g. Constrained Layout Guide, Figure.tight_layout()
, and fig.savefig(fname, bbox_inches='tight')
.
Set a label that will be displayed in the legend.
s will be converted to a string by calling str
.
Set the line width of the Figure rectangle.
Set the path effects.
AbstractPathEffect
Define the picking behavior of the artist.
This can be one of the following:
A function: If picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
Force rasterized (bitmap) drawing for vector graphics output.
Rasterized drawing is not supported by all artists. If you try to enable this on an artist that does not support it, the command has no effect and a warning will be issued.
This setting is ignored for pixel-based output.
See also Rasterization for vector graphics.
Set the sketch parameters.
The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None
, or not provided, no sketch filter will be provided.
The length of the wiggle along the line, in pixels (default 128.0)
The scale factor by which the length is shrunken or expanded (default 16.0)
The PGF backend uses this argument as an RNG seed and not as described above. Using the same seed yields the same random shape.
Set the snapping behavior.
Snapping aligns positions with the pixel grid, which results in clearer images. For example, if a black line of 1px width was defined at a position in between two pixels, the resulting image would contain the interpolated value of that line in the pixel grid, which would be a grey value on both adjacent pixel positions. In contrast, snapping will move the line to the nearest integer pixel value, so that the resulting image will really contain a 1px wide black line.
Snapping is currently only supported by the Agg and MacOSX backends.
Possible values:
Set the url for the artist.
Set the artist's visibility.
Set the zorder for the artist. Artists with lower zorder values are drawn first.
Whether the artist is 'stale' and needs to be re-drawn for the output to match the internal state of the artist.
x
and y
sticky edge lists for autoscaling.
When performing autoscaling, if a data limit coincides with a value in the corresponding sticky_edges list, then no margin will be added--the view limit "sticks" to the edge. A typical use case is histograms, where one usually expects no margin on the bottom edge (0) of the histogram.
Moreover, margin expansion "bumps" against sticky edges and cannot cross them. For example, if the upper data limit is 1.0, the upper view limit computed by simple margin application is 1.2, but there is a sticky edge at 1.1, then the actual upper view limit will be 1.1.
This attribute cannot be assigned to; however, the x
and y
lists can be modified in place as needed.
>>> artist.sticky_edges.x[:] = (xmin, xmax) >>> artist.sticky_edges.y[:] = (ymin, ymax)
Add a subfigure 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.
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 a figure or rcParams when necessary.
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.
Note
This API is provisional and may be revised in the future based on early user feedback.
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:
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.
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.
Dictionary with keywords passed to the Figure.add_subplot
call used to create each subplot.
Dictionary with keywords passed to the GridSpec
constructor used to create the grid the subplots are placed on.
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):
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.
If True, extra dimensions are squeezed out from the returned array of Axes:
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.
# First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure 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 a 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]"]
.
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 suptitle to the figure.
The suptitle 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 suptitle.
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 supxlabel to the figure.
The supxlabel 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 supxlabel.
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 supylabel to the figure.
The supylabel 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 supylabel.
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 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
properties
Other 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 | |
scalar or None | |
bool | |
color | |
dict with properties for | |
unknown | |
unknown | |
unknown | |
| color |
| {FONTNAME, 'serif', 'sans-serif', 'cursive', 'fantasy', 'monospace'} |
| |
| 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 | |
| {'center', 'right', 'left'} |
bool | |
object | |
float (multiple of font size) | |
str | |
| {'left', 'right', 'center'} |
bool | |
None or bool or float or callable | |
(float, float) | |
bool | |
float or {'vertical', 'horizontal'} | |
{None, 'default', 'anchor'} | |
(scale: float, length: float, randomness: float) | |
bool or None | |
object | |
bool | |
str | |
bool or None | |
| {'center', 'top', 'bottom', 'baseline', 'center_baseline'} |
bool | |
bool | |
float | |
float | |
float |
See also
Update this artist's properties from the dict props.
Copy properties from other to self.
A class to hold the parameters for a subplot.
Defaults are given by rcParams["figure.subplot.[name]"]
.
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.
Update the dimensions of the passed parameters. None means unchanged.
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 figure size in inches.
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.
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)
© 2012–2021 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.5.1/api/figure_api.html