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]
Bases: matplotlib.artist.Artist
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.
Attributes: |
|
---|
Parameters: |
|
---|
add_artist(self, artist, clip=False)
[source]
Add any Artist
to the figure.
Usually artists are added to axes objects using matplotlib.axes.Axes.add_artist()
, but use this method in the rare cases that adding directly to the figure is necessary.
Parameters: |
|
---|---|
Returns: |
|
add_axes(self, *args, **kwargs)
[source]
Add an axes to the figure.
Call signatures:
add_axes(rect, projection=None, polar=False, **kwargs) add_axes(ax)
Parameters: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Other Parameters: |
|
If the figure already has an axes with key (args, kwargs) then it will simply make that axes current and return it. This behavior is deprecated. 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 label attribute 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.
In rare circumstances, add_axes
may be called with a single argument, a 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,label=label1) fig.add_axes(rect,label=label2) fig.add_axes(rect, frameon=False, facecolor='g') fig.add_axes(rect, polar=True) ax=fig.add_axes(rect, projection='polar') fig.delaxes(ax) fig.add_axes(ax)
add_axobserver(self, func)
[source]
Whenever the axes state change, func(self)
will be called.
add_gridspec(self, nrows, ncols, **kwargs)
[source]
Return a GridSpec
that has this figure as a parent. This allows complex layout of axes in the figure.
Parameters: |
|
---|---|
Returns: |
|
Other Parameters: |
|
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_subplot(self, *args, **kwargs)
[source]
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()
Parameters: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Other Parameters: |
|
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. Meanwhile, if you do not want this behavior (i.e., you want to force the creation of a new subplot), you must use a unique set of args and kwargs. The axes label attribute has been exposed for this purpose: if you want two subplots that are otherwise identical to be added to the figure, make sure you give them unique labels.
fig = plt.figure() fig.add_subplot(221) # equivalent but more general ax1 = fig.add_subplot(2, 2, 1) # add a subplot with no frame ax2 = fig.add_subplot(222, frameon=False) # add a polar subplot fig.add_subplot(223, projection='polar') # add a red subplot that share the x-axis with ax1 fig.add_subplot(224, sharex=ax1, facecolor='red') #delete x2 from the figure fig.delaxes(ax2) #add x2 to the figure again fig.add_subplot(ax2)
align_labels(self, 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: |
|
---|
align_xlabels(self, 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: |
|
---|
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_ylabels(self, 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: |
|
---|
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()
autofmt_xdate(self, 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: |
|
---|
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
, subplot
or delaxes
to add or remove an axes.
clf(self, 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(self, mappable, cax=None, ax=None, use_gridspec=True, **kw)
[source]
Create a colorbar for a ScalarMappable instance, mappable.
Documentation for the pyplot thin wrapper:
Add a colorbar to a plot.
Function signatures for the pyplot
interface; all but the first are also method signatures for the colorbar()
method:
colorbar(**kwargs) colorbar(mappable, **kwargs) colorbar(mappable, cax=cax, **kwargs) colorbar(mappable, ax=ax, **kwargs)
Parameters: |
|
---|---|
Returns: |
|
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 ScalarFormatter is used. If a format string is given, e.g., '%.3f', that is used. An alternative Formatter object 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 viewers (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers, not Matplotlib. As a workaround, the colorbar can be rendered with overlapping segments:
cbar = colorbar() cbar.solids.set_edgecolor("face") draw()
However this has negative consequences in other circumstances, e.g. with semi-transparent images (alpha < 1) and colorbar extensions; therefore, this workaround is not used by default (see issue #1188).
contains(self, mouseevent)
[source]
Test whether the mouse event occurred on the figure.
Returns: |
|
---|
dpi
The resolution in dots per inch.
draw(self, renderer)
[source]
Render the figure using matplotlib.backend_bases.RendererBase
instance renderer.
draw_artist(self, a)
[source]
Draw matplotlib.artist.Artist
instance a only. This is available only after the figure is drawn.
execute_constrained_layout(self, renderer=None)
[source]
Use layoutbox
to determine pos positions within axes.
See also set_constrained_layout_pads
.
figimage(self, 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: |
|
---|---|
Returns: | |
Other Parameters: |
|
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].
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()
frameon
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible()
.
gca(self, **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_filter | a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array |
alpha | float |
anchor | 2-tuple of floats or {'C', 'SW', 'S', 'SE', ...} |
animated | bool |
aspect | {'auto', 'equal'} or num |
autoscale_on | bool |
autoscalex_on | bool |
autoscaley_on | bool |
axes_locator | Callable[[Axes, Renderer], Bbox] |
axisbelow | bool or 'line' |
clip_box | Bbox |
clip_on | bool |
clip_path | [(Path , Transform ) | Patch | None] |
contains | callable |
facecolor | color |
fc | color |
figure | Figure |
frame_on | bool |
gid | str |
in_layout | bool |
label | object |
navigate | bool |
navigate_mode | unknown |
path_effects | AbstractPathEffect |
picker | None or bool or float or callable |
position | [left, bottom, width, height] or Bbox
|
rasterization_zorder | float or None |
rasterized | bool or None |
sketch_params | (scale: float, length: float, randomness: float) |
snap | bool or None |
title | str |
transform | Transform |
url | str |
visible | bool |
xbound | unknown |
xlabel | str |
xlim | (left: float, right: float) |
xmargin | float greater than -0.5 |
xscale | {"linear", "log", "symlog", "logit", ...} |
xticklabels | List[str] |
xticks | list |
ybound | unknown |
ylabel | str |
ylim | (bottom: float, top: float) |
ymargin | float greater than -0.5 |
yscale | {"linear", "log", "symlog", "logit", ...} |
yticklabels | List[str] |
yticks | list |
zorder | float |
get_axes(self)
[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
, subplot
or delaxes
to add or remove an axes.
Note: This is equivalent to the property axes
.
get_children(self)
[source]
Get a list of artists contained in the figure.
get_constrained_layout(self)
[source]
Return a boolean: True means constrained layout is being used.
get_constrained_layout_pads(self, relative=False)
[source]
Get padding for constrained_layout
.
Returns a list of w_pad, h_pad
in inches and wspace
and hspace
as fractions of the subplot.
Parameters: |
|
---|
get_default_bbox_extra_artists(self)
[source]
get_dpi(self)
[source]
Return the resolution in dots per inch as a float.
get_edgecolor(self)
[source]
Get the edge color of the Figure rectangle.
get_facecolor(self)
[source]
Get the face color of the Figure rectangle.
get_figheight(self)
[source]
Return the figure height as a float.
get_figwidth(self)
[source]
Return the figure width as a float.
get_frameon(self)
[source]
Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.get_visible()
.
get_size_inches(self)
[source]
Returns the current size of the figure in inches.
Returns: |
|
---|
See also
matplotlib.Figure.set_size_inches
get_tight_layout(self)
[source]
Return whether tight_layout
is called when drawing.
get_tightbbox(self, renderer, bbox_extra_artists=None)
[source]
Return a (tight) bounding box of the figure in inches.
Artists that have artist.set_in_layout(False)
are not included in the bbox.
Parameters: |
|
---|---|
Returns: |
|
get_window_extent(self, *args, **kwargs)
[source]
Return the figure bounding box in display space. Arguments are ignored.
ginput(self, 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.
There are three possible interactions:
The actions are assigned to mouse buttons via the arguments mouse_add, mouse_pop and mouse_stop. Mouse buttons are defined by the numbers:
Parameters: |
|
---|---|
Returns: |
|
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.
init_layoutbox(self)
[source]
Initialize the layoutbox for use in constrained_layout.
legend(self, *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: |
| ||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: |
| ||||||||||||||||||||||||
Other Parameters: |
|
Not all kinds of artist are supported by the legend command. See Legend guide for details.
savefig(self, fname, *, transparent=None, **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, metadata=None)
The output formats available depend on the backend being used.
Parameters: |
|
---|---|
Other Parameters: |
|
sca(self, a)
[source]
Set the current axes to be a and return a.
set_canvas(self, canvas)
[source]
Set the canvas that contains the figure
Parameters: |
|
---|
set_constrained_layout(self, constrained)
[source]
Set whether constrained_layout
is 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_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.
Parameters: |
|
---|
set_constrained_layout_pads(self, **kwargs)
[source]
Set padding for constrained_layout
. Note the kwargs can be passed as a dictionary fig.set_constrained_layout(**paddict)
.
Parameters: |
|
---|
set_dpi(self, val)
[source]
Set the resolution of the figure in dots-per-inch.
Parameters: |
|
---|
set_edgecolor(self, color)
[source]
Set the edge color of the Figure rectangle.
Parameters: |
|
---|
set_facecolor(self, color)
[source]
Set the face color of the Figure rectangle.
Parameters: |
|
---|
set_figheight(self, val, forward=True)
[source]
Set the height of the figure in inches.
Parameters: |
|
---|
set_figwidth(self, val, forward=True)
[source]
Set the width of the figure in inches.
Parameters: |
|
---|
set_frameon(self, b)
[source]
Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to Figure.patch.set_visible()
.
Parameters: |
|
---|
set_size_inches(self, w, h=None, forward=True)
[source]
Set the figure size in inches.
Call signatures:
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(self, tight)
[source]
Set whether and how tight_layout
is called when drawing.
Parameters: |
|
---|
show(self, 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 a FigureManagerBase
, and 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.
Parameters: |
|
---|
subplots(self, 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.
This utility wrapper makes it convenient to create common layouts of subplots in a single call.
Parameters: |
|
---|---|
Returns: |
|
# First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure plt.figure() # Creates a subplot ax = fig.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Creates two subplots and unpacks 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) # Creates four polar axes, and accesses them through the # returned array axes = fig.subplots(2, 2, subplot_kw=dict(polar=True)) 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)
subplots_adjust(self, left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
[source]
Update the SubplotParams
with kwargs (defaulting to rc when None) and update the subplot locations.
suptitle(self, t, **kwargs)
[source]
Add a centered title to the figure.
Parameters: |
|
---|---|
Returns: |
|
Other Parameters: |
|
>>> fig.suptitle('This is the figure title', fontsize=12)
text(self, x, y, s, fontdict=None, withdash=<deprecated parameter>, **kwargs)
[source]
Add text to figure.
Parameters: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Returns: |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Other Parameters: |
|
See also
tight_layout(self, renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None)
[source]
Automatically adjust subplot parameters to give specified padding.
To exclude an artist on the axes from the bounding box calculation that determines the subplot parameters (i.e. legend, or annotation), then set a.set_in_layout(False)
for that artist.
Parameters: |
|
---|
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.
matplotlib.figure.Figure
© 2012–2018 Matplotlib Development Team. All rights reserved.
Licensed under the Matplotlib License Agreement.
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.figure.Figure.html