On this page
matplotlib.figure.Figure
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None, constrained_layout=None)[source]-
The top level container for all the plot elements.
The Figure instance supports callbacks through a callbacks attribute which is a
CallbackRegistryinstance. The events you can connect to are 'dpi_changed', and the callback will be called withfunc(fig)where fig is theFigureinstance.Attributes: - patch
-
The
Rectangleinstance representing the figure patch. - suppressComposite
-
For multiple figure images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is a boolean, this will override the renderer.
Parameters: -
figsize : 2-tuple of floats, default: rcParams["figure.figsize"] -
Figure dimension
(width, height)in inches. -
dpi : float, default: rcParams["figure.dpi"] -
Dots per inch.
-
facecolor : default: rcParams["figure.facecolor"] -
The figure patch facecolor.
-
edgecolor : default: rcParams["figure.edgecolor"] -
The figure patch edge color.
-
linewidth : float -
The linewidth of the frame (i.e. the edge linewidth of the figure patch).
-
frameon : bool, default: rcParams["figure.frameon"] -
If
False, suppress drawing the figure frame. -
subplotpars : SubplotParams -
Subplot parameters. If not given, the default subplot parameters
rcParams["figure.subplot.*"]are used. -
tight_layout : bool or dict, default: rcParams["figure.autolayout"] -
If
Falseuse subplotpars. IfTrueadjust subplot parameters usingtight_layoutwith default padding. When providing a dict containing the keyspad,w_pad,h_pad, andrect, the defaulttight_layoutpaddings will be overridden. -
constrained_layout : bool -
If
Trueuse constrained layout to adjust positioning of plot elements. Liketight_layout, but designed to be more flexible. See Constrained Layout Guide for examples. (Note: does not work withsubplot()orsubplot2grid().) Defaults torcParams["figure.constrained_layout.use"].
add_axes(*args, **kwargs)[source]-
Add an axes to the figure.
Call signature:
add_axes(rect, projection=None, polar=False, **kwargs)Parameters: -
rect : sequence of float -
The dimensions [left, bottom, width, height] of the new axes. All quantities are in fractions of figure width and height.
-
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', rectilinear'}, optional -
The projection type of the axes.
-
polar : boolean, optional -
If True, equivalent to projection='polar'.
- **kwargs
-
This method also takes the keyword arguments for
Axes.
Returns: -
axes : Axes -
The added axes.
Examples
Some simple examples:
rect = l, b, w, h fig.add_axes(rect) fig.add_axes(rect, frameon=False, facecolor='g') fig.add_axes(rect, polar=True) fig.add_axes(rect, projection='polar') fig.add_axes(ax)If the figure already has an axes with the same parameters, then it will simply make that axes current and return it. This behavior has been deprecated as of Matplotlib 2.1. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new Axes), you must use a unique set of args and kwargs. The axes
labelattribute has been exposed for this purpose: if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels:fig.add_axes(rect, label='axes1') fig.add_axes(rect, label='axes2')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. For example, if an axes has been removed with
delaxes(), it can be restored with:fig.add_axes(ax)In all cases, the
Axesinstance will be returned. -
add_axobserver(func)[source]-
Whenever the axes state change,
func(self)will be called.
add_subplot(*args, **kwargs)[source]-
Add a subplot.
Call signatures:
add_subplot(nrows, ncols, index, **kwargs) add_subplot(pos, **kwargs)Parameters: - *args
-
Either a 3-digit integer or three separate integers describing the position of the subplot. If the three integers are R, C, and P in order, the subplot will take the Pth position on a grid with R rows and C columns.
-
projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', rectilinear'}, optional -
The projection type of the axes.
-
polar : boolean, optional -
If True, equivalent to projection='polar'.
- **kwargs
-
This method also takes the keyword arguments for
Axes.
Returns: -
axes : Axes -
The axes of the subplot.
See also
matplotlib.pyplot.subplot- for an explanation of the args.
Notes
If the figure already has a subplot with key (args, kwargs) then it will simply make that subplot current and return it. This behavior is deprecated.
Examples
fig.add_subplot(111) # equivalent but more general fig.add_subplot(1, 1, 1) # add subplot with red background fig.add_subplot(212, facecolor='r') # add a polar subplot fig.add_subplot(111, projection='polar') # add Subplot instance sub fig.add_subplot(sub)
align_labels(axs=None)[source]-
Align the xlabels and ylabels of subplots with the same subplots row or column (respectively) if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
Parameters: -
axs : list of Axes -
Optional list (or ndarray) of
Axesto align the labels. Default is to align all axes on the figure.
-
align_xlabels(axs=None)[source]-
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
If a label is on the bottom, it is aligned with labels on axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on axes with the same top-most row.
Parameters: -
axs : list of Axes -
Optional list of (or ndarray)
Axesto align the xlabels. Default is to align all axes on the figure.
Notes
This assumes that
axsare from the sameGridSpec, so that theirSubplotSpecpositions correspond to figure positions.Examples
Example with rotated xtick labels:
fig, axs = plt.subplots(1, 2) for tick in axs[0].get_xticklabels(): tick.set_rotation(55) axs[0].set_xlabel('XLabel 0') axs[1].set_xlabel('XLabel 1') fig.align_xlabels() -
align_ylabels(axs=None)[source]-
Align the ylabels of subplots in the same subplot column if label alignment is being done automatically (i.e. the label position is not manually set).
Alignment persists for draw events after this is called.
If a label is on the left, it is aligned with labels on axes that also have their label on the left and that have the same left-most subplot column. If the label is on the right, it is aligned with labels on axes with the same right-most column.
Parameters: -
axs : list of Axes -
Optional list (or ndarray) of
Axesto align the ylabels. Default is to align all axes on the figure.
Notes
This assumes that
axsare from the sameGridSpec, so that theirSubplotSpecpositions correspond to figure positions.Examples
Example with large yticks labels:
fig, axs = plt.subplots(2, 1) axs[0].plot(np.arange(0, 1000, 50)) axs[0].set_ylabel('YLabel 0') axs[1].set_ylabel('YLabel 1') fig.align_ylabels() -
autofmt_xdate(bottom=0.2, rotation=30, ha='right', which=None)[source]-
Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.
Parameters: -
bottom : scalar -
The bottom of the subplots for
subplots_adjust(). -
rotation : angle in degrees -
The rotation of the xtick labels.
-
ha : string -
The horizontal alignment of the xticklabels.
-
which : {None, 'major', 'minor', 'both'} -
Selects which ticklabels to rotate. Default is None which works the same as major.
-
axes-
List of axes in the Figure. You can access the axes in the Figure through this list. Do not modify the list itself. Instead, use
add_axes,subplotordelaxesto add or remove an axes.
clf(keep_observers=False)[source]-
Clear the figure.
Set keep_observers to True if, for example, a gui widget is tracking the axes in the figure.
colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]-
Create a colorbar for a ScalarMappable instance, mappable.
Documentation for the pylab thin wrapper:
Add a colorbar to a plot.
Function signatures for the
pyplotinterface; all but the first are also method signatures for thecolorbar()method:colorbar(**kwargs) colorbar(mappable, **kwargs) colorbar(mappable, cax=cax, **kwargs) colorbar(mappable, ax=ax, **kwargs)Parameters: - mappable :
-
The
Image,ContourSet, etc. to which the colorbar applies; this argument is mandatory for the Figurecolorbar()method but optional for the pyplotcolorbar()function, which sets the default to the current image. -
cax : Axes object, optional -
Axes into which the colorbar will be drawn.
-
ax : Axes, list of Axes, optional -
Parent axes from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.
-
use_gridspec : bool, optional -
If cax is
None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec isTrue, cax is created as an instance of Subplot using the grid_spec module.
Returns: - :class:`~matplotlib.colorbar.Colorbar` instance
-
See also its base class,
ColorbarBase. Call theset_label()method to label the colorbar.
Notes
Additional keyword arguments are of two kinds:
axes properties:
Property Description orientation vertical or horizontal fraction 0.15; fraction of original axes to use for colorbar pad 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes shrink 1.0; fraction by which to multiply the size of the colorbar aspect 20; ratio of long to short dimensions anchor (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal; the anchor point of the colorbar axes panchor (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal; the anchor point of the colorbar parent axes. If False, the parent axes' anchor will be unchanged 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 | list of ticks | Locator object ] If None, ticks are determined automatically from the input. format [ None | format string | Formatter object ] If None, the ScalarFormatteris used. If a format string is given, e.g., '%.3f', that is used. An alternativeFormatterobject may be given instead.drawedges bool Whether to draw lines at color boundaries. 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 color mapped 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 viewer (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. Particularly with semi transparent images (alpha < 1) and colorbar extensions and is not enabled by default see (issue #1188).
contains(mouseevent)[source]-
Test whether the mouse event occurred on the figure.
Returns: - bool, {}
dpi-
The resolution in dots per inch.
draw(renderer)[source]-
Render the figure using
matplotlib.backend_bases.RendererBaseinstance renderer.
draw_artist(a)[source]-
Draw
matplotlib.artist.Artistinstance a only. This is available only after the figure is drawn.
execute_constrained_layout(renderer=None)[source]-
Use
layoutboxto determine pos positions within axes.See also
set_constrained_layout_pads.
figimage(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs)[source]-
Add a non-resampled image to the figure.
The image is attached to the lower or upper left corner depending on origin.
Parameters: - X
-
The image data. This is an array of one of the following shapes:
- MxN: luminance (grayscale) values
- MxNx3: RGB values
- MxNx4: RGBA values
-
xo, yo : int -
The x/y image offset in pixels.
-
alpha : None or float -
The alpha blending value.
-
norm : matplotlib.colors.Normalize -
A
Normalizeinstance to map the luminance to the interval [0, 1]. -
cmap : str or matplotlib.colors.Colormap -
The colormap to use. Default:
rcParams["image.cmap"]. -
vmin, vmax : scalar -
If norm is not given, these values set the data limits for the colormap.
-
origin : {'upper', 'lower'} -
Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the axes. Defaults to
rcParams["image.origin"]. -
resize : bool -
If True, resize the figure to match the given image size.
Returns: - :class:`matplotlib.image.FigureImage`
Other Parameters: - **kwargs
-
Additional kwargs are
Artistkwargs passed on toFigureImage.
Notes
figimage complements the axes image (
imshow()) which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define anAxeswith extent [0,0,1,1].Examples:
f = plt.figure() nx = int(f.get_figwidth() * f.dpi) ny = int(f.get_figheight() * f.dpi) data = np.random.random((ny, nx)) f.figimage(data) plt.show()
figurePatch-
Deprecated since version 2.1: The figurePatch function was deprecated in version 2.1. Use
Figure.patchinstead.
gca(**kwargs)[source]-
Get the current axes, creating one if necessary.
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 adjustable[ 'box' | 'datalim'] agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alphafloat (0.0 transparent through 1.0 opaque) anchor[ 'C' | 'SW' | 'S' | 'SE' | 'E' | 'NE' | 'N' | 'NW' | 'W' ] animatedbool aspectunknown autoscale_onbool autoscalex_onbool autoscaley_onbool axes_locatora callable object which takes an axes instance and renderer and returns a bbox. axisbelow[ bool | 'line' ] clip_boxa Bboxinstanceclip_onbool clip_path[( Path,Transform) |Patch| None]containsa callable function facecolorcolor fccolor figureFigureframe_onbool gidan id string labelobject navigatebool navigate_modeunknown path_effectsAbstractPathEffectpicker[None | bool | float | callable] positionunknown rasterization_zorderfloat or None rasterizedbool or None sketch_params(scale: float, length: float, randomness: float) snapbool or None titleunknown transformTransformurla url string visiblebool xbound(lower: float, upper: float) xlabelunknown xlim(left: float, right: float) xmarginfloat greater than -0.5 xscale[ 'linear' | 'log' | 'symlog' | 'logit' | ... ] xticklabelslist of string labels xtickslist of tick locations. ybound(lower: float, upper: float) ylabelunknown ylim(bottom: float, top: float) ymarginfloat greater than -0.5 yscale[ 'linear' | 'log' | 'symlog' | 'logit' | ... ] yticklabelslist of string labels ytickslist of tick locations. zorderfloat
get_axes()[source]-
Return a 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,subplotordelaxesto add or remove an axes.Note: This is equivalent to the property
axes.
get_children()[source]-
Get a list of artists contained in the figure.
get_constrained_layout()[source]-
Return a boolean: True means constrained layout is being used.
get_constrained_layout_pads(relative=False)[source]-
Get padding for
constrained_layout.Returns a list of
w_pad, h_padin inches andwspaceandhspaceas fractions of the subplot.Parameters: -
relative : boolean -
If
True, then convert from inches to figure relative.
-
get_default_bbox_extra_artists()[source]
get_dpi()[source]-
Return the resolution in dots per inch as a float.
get_edgecolor()[source]-
Get the edge color of the Figure rectangle.
get_facecolor()[source]-
Get the face color of the Figure rectangle.
get_figheight()[source]-
Return the figure height as a float.
get_figwidth()[source]-
Return the figure width as a float.
get_frameon()[source]-
Return whether the figure frame will be drawn.
get_size_inches()[source]-
Returns the current size of the figure in inches.
Returns: -
size : ndarray -
The size (width, height) of the figure in inches.
See also
matplotlib.Figure.set_size_inches -
get_tight_layout()[source]-
Return whether
tight_layoutis called when drawing.
get_tightbbox(renderer)[source]-
Return a (tight) bounding box of the figure in inches.
It only accounts axes title, axis labels, and axis ticklabels. Needs improvement.
get_window_extent(*args, **kwargs)[source]-
Return the figure bounding box in display space. Arguments are ignored.
ginput(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)[source]-
Blocking call to interact with a figure.
Wait until the user clicks n times on the figure, and return the coordinates of each click in a list.
The buttons used for the various actions (adding points, removing points, terminating the inputs) can be overridden via the arguments mouse_add, mouse_pop and mouse_stop, that give the associated mouse button: 1 for left, 2 for middle, 3 for right.
Parameters: -
n : int, optional, default: 1 -
Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually.
-
timeout : scalar, optional, default: 30 -
Number of seconds to wait before timing out. If zero or negative will never timeout.
-
show_clicks : bool, optional, default: False -
If True, show a red cross at the location of each click.
-
mouse_add : int, one of (1, 2, 3), optional, default: 1 (left click) -
Mouse button used to add points.
-
mouse_pop : int, one of (1, 2, 3), optional, default: 3 (right click) -
Mouse button used to remove the most recently added point.
-
mouse_stop : int, one of (1, 2, 3), optional, default: 2 (middle click) -
Mouse button used to stop input.
Returns: -
points : list of tuples -
A list of the clicked (x, y) coordinates.
Notes
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.
-
hold(b=None)[source]-
Deprecated since version 2.0: The hold function was deprecated in version 2.0.
Set the hold state. If hold is None (default), toggle the hold state. Else set the hold state to boolean value b.
e.g.:
hold() # toggle hold hold(True) # hold is on hold(False) # hold is offAll "hold" machinery is deprecated.
init_layoutbox()[source]-
Initialize the layoutbox for use in constrained_layout.
legend(*args, **kwargs)[source]-
Place a legend on the figure.
To make a legend from existing artists on every axes:
legend()To make a legend for a list of lines and labels:
legend( (line1, line2, line3), ('label1', 'label2', 'label3'), loc='upper right')These can also be specified by keyword:
legend(handles=(line1, line2, line3), labels=('label1', 'label2', 'label3'), loc='upper right')Parameters: -
handles : sequence of 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.
-
labels : sequence of strings, optional -
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.
Returns: - :class:`matplotlib.legend.Legend` instance
Other Parameters: -
loc : int or string or pair of floats, default: 'upper right' -
The location of the legend. Possible codes are:
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 Alternatively can be a 2-tuple giving
x, yof the lower-left corner of the legend in axes coordinates (in which casebbox_to_anchorwill be ignored). -
bbox_to_anchor : BboxBase or pair of floats -
Specify any arbitrary location for the legend in
bbox_transformcoordinates (default Axes coordinates).For example, to put the legend's upper right hand corner in the center of the axes the following keywords can be used:
loc='upper right', bbox_to_anchor=(0.5, 0.5) -
ncol : integer -
The number of columns that the legend has. Default is 1.
-
prop : None or matplotlib.font_manager.FontProperties or dict -
The font properties of the legend. If None (default), the current
matplotlib.rcParamswill be used. -
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large'} -
Controls 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
propis not specified. -
numpoints : None or int -
The number of marker points in the legend when creating a legend entry for a
Line2D(line). Default isNone, which will take the value fromrcParams["legend.numpoints"]. -
scatterpoints : None or int -
The number of marker points in the legend when creating a legend entry for a
PathCollection(scatter plot). Default isNone, which will take the value fromrcParams["legend.scatterpoints"]. -
scatteryoffsets : iterable of floats -
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]. Default is[0.375, 0.5, 0.3125]. -
markerscale : None or int or float -
The relative size of legend markers compared with the originally drawn ones. Default is
None, which will take the value fromrcParams["legend.markerscale"]. -
markerfirst : bool -
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. Default is True.
-
frameon : None or bool -
Control whether the legend should be drawn on a patch (frame). Default is
None, which will take the value fromrcParams["legend.frameon"]. -
fancybox : None or bool -
Control whether round edges should be enabled around the
FancyBboxPatchwhich makes up the legend's background. Default isNone, which will take the value fromrcParams["legend.fancybox"]. -
shadow : None or bool -
Control whether to draw a shadow behind the legend. Default is
None, which will take the value fromrcParams["legend.shadow"]. -
framealpha : None or float -
Control the alpha transparency of the legend's background. Default is
None, which will take the value fromrcParams["legend.framealpha"]. If shadow is activated and framealpha isNone, the default value is ignored. -
facecolor : None or "inherit" or a color spec -
Control the legend's background color. Default is
None, which will take the value fromrcParams["legend.facecolor"]. If"inherit", it will takercParams["axes.facecolor"]. -
edgecolor : None or "inherit" or a color spec -
Control the legend's background patch edge color. Default is
None, which will take the value fromrcParams["legend.edgecolor"]If"inherit", it will takercParams["axes.edgecolor"]. -
mode : {"expand", None} -
If
modeis set to"expand"the legend will be horizontally expanded to fill the axes area (orbbox_to_anchorif defines the legend's size). -
bbox_transform : None or matplotlib.transforms.Transform -
The transform for the bounding box (
bbox_to_anchor). For a value ofNone(default) the Axes'transAxestransform will be used. -
title : str or None -
The legend's title. Default is no title (
None). -
borderpad : float or None -
The fractional whitespace inside the legend border. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.borderpad"]. -
labelspacing : float or None -
The vertical space between the legend entries. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.labelspacing"]. -
handlelength : float or None -
The length of the legend handles. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.handlelength"]. -
handletextpad : float or None -
The pad between the legend handle and text. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.handletextpad"]. -
borderaxespad : float or None -
The pad between the axes and legend border. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.borderaxespad"]. -
columnspacing : float or None -
The spacing between columns. Measured in font-size units. Default is
None, which will take the value fromrcParams["legend.columnspacing"]. -
handler_map : dict or None -
The custom dictionary mapping instances or types to a legend handler. This
handler_mapupdates the default handler map found atmatplotlib.legend.Legend.get_legend_handler_map().
Notes
Not all kinds of artist are supported by the legend command. See Legend guide for details.
-
savefig(fname, **kwargs)[source]-
Save the current figure.
Call signature:
savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None)The output formats available depend on the backend being used.
Parameters: -
fname : str or file-like object -
A string containing a path to a filename, or a Python file-like object, or possibly some backend-dependent object such as
PdfPages.If format is None and fname is a string, the output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter
savefig.formatis used.If fname is not a string, remember to specify format to ensure that the correct backend is used.
Other Parameters: -
dpi : [ None | scalar > 0 | 'figure'] -
The resolution in dots per inch. If None it will default to the value
savefig.dpiin the matplotlibrc file. If 'figure' it will set the dpi to be the value of the figure. -
facecolor : color spec or None, optional -
the facecolor of the figure; if None, defaults to savefig.facecolor
-
edgecolor : color spec or None, optional -
the edgecolor of the figure; if None, defaults to savefig.edgecolor
-
orientation : {'landscape', 'portrait'} -
not supported on all backends; currently only on postscript output
-
papertype : str -
One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output.
-
format : str -
One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg.
-
transparent : bool -
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. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.
-
frameon : bool -
If True, the figure patch will be colored, if False, the figure background will be transparent. If not provided, the rcParam 'savefig.frameon' will be used.
-
bbox_inches : str or Bbox, optional -
Bbox in inches. Only the given portion of the figure is saved. If 'tight', try to figure out the tight bbox of the figure. If None, use savefig.bbox
-
pad_inches : scalar, optional -
Amount of padding around the figure when bbox_inches is 'tight'. If None, use savefig.pad_inches
-
bbox_extra_artists : list of Artist, optional -
A list of extra artists that will be considered when the tight bbox is calculated.
-
sca(a)[source]-
Set the current axes to be a and return a.
set_canvas(canvas)[source]-
Set the canvas that contains the figure
ACCEPTS: a FigureCanvas instance
set_constrained_layout(constrained)[source]-
Set whether
constrained_layoutis used upon drawing. If None, the rcParams['figure.constrained_layout.use'] value will be used.When providing a dict containing the keys
w_pad,h_padthe defaultconstrained_layoutpaddings will be overridden. These pads are in inches and default to 3.0/72.0.w_padis the width padding andh_padis the height padding.ACCEPTS: [True | False | dict | None ]
set_constrained_layout_pads(**kwargs)[source]-
Set padding for
constrained_layout. Note the kwargs can be passed as a dictionaryfig.set_constrained_layout(**paddict).Parameters: -
w_pad : scalar -
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
-
h_pad : scalar -
Height padding in inches. Defaults to 3 pts.
- wspace: scalar
-
Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace.
- hspace: scalar
-
Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace.
-
set_dpi(val)[source]-
Set the dots-per-inch of the figure.
ACCEPTS: float
set_edgecolor(color)[source]-
Set the edge color of the Figure rectangle.
ACCEPTS: any matplotlib color - see help(colors)
set_facecolor(color)[source]-
Set the face color of the Figure rectangle.
ACCEPTS: any matplotlib color - see help(colors)
set_figheight(val, forward=True)[source]-
Set the height of the figure in inches.
ACCEPTS: float
set_figwidth(val, forward=True)[source]-
Set the width of the figure in inches.
ACCEPTS: float
set_frameon(b)[source]-
Set whether the figure frame (background) is displayed or invisible
ACCEPTS: boolean
set_size_inches(w, h=None, forward=True)[source]-
Set the figure size in inches (1in == 2.54cm)
Usage
fig.set_size_inches(w, h) # OR fig.set_size_inches((w, h))optional kwarg forward=True will cause the canvas size to be automatically updated; e.g., you can resize the figure window from the shell
ACCEPTS: a w, h tuple with w, h in inches
See also
matplotlib.Figure.get_size_inches
set_tight_layout(tight)[source]-
Set whether and how
tight_layoutis called when drawing.Parameters: -
tight : bool or dict with keys "pad", "w_pad", "h_pad", "rect" or None -
If a bool, sets whether to call
tight_layoutupon drawing. IfNone, use thefigure.autolayoutrcparam instead. If a dict, pass it as kwargs totight_layout, overriding the default paddings.
-
show(warn=True)[source]-
If using a GUI backend with pyplot, display the figure window.
If the figure was not created using
figure(), it will lack aFigureManagerBase, and will raise an AttributeError.Parameters: -
warm : bool -
If
True, issue warning when called on a non-GUI backend
Notes
For non-GUI backends, this does nothing, in which case a warning will be issued if warn is
True(default). -
subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None)[source]-
Add a set of subplots to this figure.
Parameters: -
nrows, ncols : int, default: 1 -
Number of rows/cols of the subplot grid.
-
sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False -
Controls sharing of properties among x (
sharex) or y (sharey) axes:- True or 'all': x- or y-axis will be shared among all subplots.
- False or 'none': each subplot x- or y-axis will be independent.
- 'row': each subplot row will share an x- or y-axis.
- 'col': each subplot column will share an x- or y-axis.
When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use
tick_params(). -
squeeze : bool, optional, default: True -
If True, extra dimensions are squeezed out from the returned array of Axes:
- if only one subplot is constructed (nrows=ncols=1), the resulting single Axes object is returned as a scalar.
- for Nx1 or 1xM subplots, the returned object is a 1D numpy object array of Axes objects.
- for NxM, subplots with N>1 and M>1 are returned as a 2D array.
- If False, no squeezing at all is done: the returned Axes object is always a 2D array containing Axes instances, even if it ends up being 1x1.
-
subplot_kw : dict, default: {} -
Dict with keywords passed to the
add_subplot()call used to create each subplots. -
gridspec_kw : dict, default: {} -
Dict with keywords passed to the
GridSpecconstructor used to create the grid the subplots are placed on.
Returns: -
ax : single Axes object or array of Axes objects -
The added axes. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.
See also
pyplot.subplots- pyplot API; docstring includes examples.
-
subplots_adjust(*args, **kwargs)[source]-
Call signature:
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)Update the
SubplotParamswith kwargs (defaulting to rc when None) and update the subplot locations.
suptitle(t, **kwargs)[source]-
Add a centered title to the figure.
kwargs are
matplotlib.text.Textproperties. Using figure coordinates, the defaults are:x : 0.5- The x location of the text in figure coords
y : 0.98- The y location of the text in figure coords
horizontalalignment : 'center'- The horizontal alignment of the text
verticalalignment : 'top'- The vertical alignment of the text
If the
fontpropertieskeyword argument is given then the rcParams defaults forfontsize(figure.titlesize) andfontweight(figure.titleweight) will be ignored in favour of theFontPropertiesdefaults.A
matplotlib.text.Textinstance is returned.Example:
fig.suptitle('this is the figure title', fontsize=12)
text(x, y, s, *args, **kwargs)[source]-
Add text to figure.
Call signature:
text(x, y, s, fontdict=None, **kwargs)Add text to figure at location x, y (relative 0-1 coords). See
text()for the meaning of the other arguments.kwargs control the
Textproperties:Property Description agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array alphafloat (0.0 transparent through 1.0 opaque) animatedbool backgroundcolorany matplotlib color bboxFancyBboxPatch prop dict clip_boxa matplotlib.transforms.Bboxinstanceclip_onbool clip_path[ ( Path,Transform) |Patch| None ]colorany matplotlib color containsa callable function familyor fontfamily or fontname or name[FONTNAME | 'serif' | 'sans-serif' | 'cursive' | 'fantasy' | 'monospace' ] figurea Figureinstancefontpropertiesor font_propertiesa matplotlib.font_manager.FontPropertiesinstancegidan id string horizontalalignmentor ha[ 'center' | 'right' | 'left' ] labelobject linespacingfloat (multiple of font size) multialignmentor ma['left' | 'right' | 'center' ] path_effectsAbstractPathEffectpicker[None | bool | float | callable] position(x,y) rasterizedbool or None rotation[ angle in degrees | 'vertical' | 'horizontal' ] rotation_mode[ None | "default" | "anchor" ] sizeor fontsize[size in points | 'xx-small' | 'x-small' | 'small' | 'medium' | 'large' | 'x-large' | 'xx-large' ] sketch_params(scale: float, length: float, randomness: float) snapbool or None stretchor fontstretch[a numeric value in range 0-1000 | 'ultra-condensed' | 'extra-condensed' | 'condensed' | 'semi-condensed' | 'normal' | 'semi-expanded' | 'expanded' | 'extra-expanded' | 'ultra-expanded' ] styleor fontstyle[ 'normal' | 'italic' | 'oblique'] textstring or anything printable with '%s' conversion. transformTransformurla url string usetexbool or None variantor fontvariant[ 'normal' | 'small-caps' ] verticalalignmentor va[ 'center' | 'top' | 'bottom' | 'baseline' ] visiblebool weightor fontweight[a numeric value in range 0-1000 | 'ultralight' | 'light' | 'normal' | 'regular' | 'book' | 'medium' | 'roman' | 'semibold' | 'demibold' | 'demi' | 'bold' | 'heavy' | 'extra bold' | 'black' ] wrapbool xfloat yfloat zorderfloat
tight_layout(renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]-
Adjust subplot parameters to give specified padding.
Parameters: -
pad : float -
padding between the figure edge and the edges of subplots, as a fraction of the font-size.
-
h_pad, w_pad : float, optional -
padding (height/width) between edges of adjacent subplots. Defaults to
pad_inches. -
rect : tuple (left, bottom, right, top), optional -
a rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1).
-
-
Blocking call to interact with the figure.
This will return True is a key was pressed, False if a mouse button was pressed and None if timeout was reached without either being pressed.
If timeout is negative, does not timeout.
Examples using matplotlib.figure.Figure
© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/2.2.3/api/_as_gen/matplotlib.figure.Figure.html