rL i&*dZddlmZddlZddlZddlZddlZddlmZddl Z ddl Z ddl Z ddl mZmZmZmZddlmZmZmZddlmZmZmZmZmZddlmZddlmZddl m!Z"ddl#m$Z%ddl&m'Z'dd l(m)Z)m*Z*dd l+m,Z,m-Z-m.Z.m/Z/ddl0m1Z2dd l3m4Z4dd l5m6Z6dd l7m8Z8m9Z9m:Z:m;Z;ejxe=Z>dZ?GddZ@GddeZAejGddeAZCejGddeAZDdZEy)a `matplotlib.figure` implements the following classes: `Figure` Top level `~matplotlib.artist.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. Figures are typically created using pyplot methods `~.pyplot.figure`, `~.pyplot.subplots`, and `~.pyplot.subplot_mosaic`. .. plot:: :include-source: fig, ax = plt.subplots(figsize=(2, 2), facecolor='lightskyblue', layout='constrained') fig.suptitle('Figure') ax.set_title('Axes', loc='left', fontstyle='oblique', fontsize='medium') Some situations call for directly instantiating a `~.figure.Figure` class, usually inside an application of some sort (see :ref:`user_interfaces` for a list of examples) . More information about Figures can be found at :ref:`figure-intro`. ) ExitStackN)Integral)_blocking_input backend_bases _docstring projections)Artistallow_rasterization_finalize_rasterization) DrawEventFigureCanvasBaseNonGuiException MouseButton _get_renderer)Axes)GridSpec SubplotParams)ConstrainedLayoutEngineTightLayoutEngine LayoutEnginePlaceHolderLayoutEngine) Rectangle)Text)Affine2DBboxBboxTransformToTransformedBboxc<|jdx}||_yy)NFroot) get_figurestale)selfvalfigs W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/matplotlib/figure.py_stale_figure_callbackr'As$E**7 8c@eZdZdZdZdZdZdZdZdZ dZ d Z y ) _AxesStacka  Helper class to track Axes in a figure. Axes are tracked both in the order in which they have been added (``self._axes`` insertion/iteration order) and in the separate "gca" stack (which is the index to which they map in the ``self._axes`` dict). cDi|_tj|_yN)_axes itertoolscount_counterr#s r&__init__z_AxesStack.__init__Os !) r(cg|jS)z1List the Axes that have been added to the figure.)r-r1s r&as_listz_AxesStack.as_listSs}r(c:|jj|y)zRemove the Axes from the stack.N)r-popr#as r&removez_AxesStack.removeWs qr(cz||jvr tdt|j|j|<y)z@Move an Axes, which must already exist in the stack, to the top.zAxes has not been added yetN)r- ValueErrornextr0r7s r&bubblez_AxesStack.bubble[s0 DJJ :; ;T]]+ 1 r(cf||jvr#t|j|j|<yy)z9Add an Axes to the stack, ignoring it if already present.N)r-r<r0r7s r&addz_AxesStack.addas) DJJ  /DJJqM r(cZt|j|jjdS)z6Return the active Axes, or None if the stack is empty.N)keydefault)maxr- __getitem__r1s r&currentz_AxesStack.currentfs4::4::#9#94HHr(cjit|dt|jjdiS)Nr0r)rB)varsrCr-valuesr1s r& __getstate__z_AxesStack.__getstate__js6 4j DJJ--/;  r(c|jd}t|j|tj||_y)Nr0)r6rGupdater.r/r0)r#state next_counters r& __setstate__z_AxesStack.__setstate__ps2yy,  T % ! 5 r(N) __name__ __module__ __qualname____doc__r2r4r9r=r?rErIrNr(r&r*r*Fs0*, 0 I 6r(r*c eZdZdZfdZdZ dPdZdZdQdZdZ e e jed e d Z d ZdQdZdZej$ddddddej&edZdZej$ddddddej&edZdZej$ddd d!ddej&ed"Zd#Zd$Zd%Zd&Zd'Zd(Zd)Zd*Z d+Z!e ee!Z"dRd-Z#ejHd.Z%ejHd/Z&d0Z'dSd,d,d ddddd1d2Z(d3Z)d4Z*dRd5Z+dRd6Z,ejHd7Z-ejHdQd8Z.ejH dTd9Z/ dUd:Z0dQd;Z1dQd<Z2dQd=Z3dQd>Z4dSd?Z5 dVd@Z6dAZ7dBZ8dCZ9dDZ:dd,ddEdFZ;dGZdJZ?e>dKZ@d,d,dddLddddMdNZAdOZBxZCS)W FigureBasez Base class for `.Figure` and `.SubFigure` containing the methods that add artists to the figure or subfigure, create Axes, etc. c t||`d|_d|_d|_t jt jt jd|_g|_ g|_ g|_ g|_ g|_ g|_g|_g|_d|_d|_|j&di|y)N)xytitleTrS)superr2r- _suptitle _supxlabel _supylabelcbookGrouper_align_label_groups _localaxesartistslinespatchestextsimageslegendssubfigsr"suppressCompositeset)r#kwargs __class__s r&r2zFigureBase.__init__{s  J ]]_$          !%6r(c|j}|j|jtd|Dd}|jD]|}|j }|j |r |||nd|jD];}t|ds|j }|j |r |||nd=~|S)zAlso runs apply_aspectc3BK|]}|jr|ywr,) get_animated).0artists r& z/FigureBase._get_draw_artists..s G1D1D1FV Gsc"|jSr,) get_zorder)rqs r&z.FigureBase._get_draw_artists..sv002r()rAN apply_aspect) get_childrenr9patchsortedraget_axes_locatorrvhasattr)r#rendererrbaxlocatorchilds r&_get_draw_artistszFigureBase._get_draw_artistss##%tzz" G' G24// GB))+G OOWGB1$ G* G5.1#446G&&4;x0G G  Gr(ctjgd||jDcgc]}|jdk7s|}}t d|D}t |dk(rG|jdj |D]$}|j||j|&n|r|D]}|jjr:|j |D]$}|j||j|&[|j |D]}|jd|jd|j} |r | | jr|j| d |_y cc}w) a\ Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared x-axis where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels. Parameters ---------- bottom : float, default: 0.2 The bottom of the subplots for `subplots_adjust`. rotation : float, default: 30 degrees The rotation angle of the xtick labels in degrees. ha : {'left', 'center', 'right'}, default: 'right' The horizontal alignment of the xticklabels. which : {'major', 'minor', 'both'}, default: 'major' Selects which ticklabels to rotate. )majorminorboth)whichz c3<K|]}|jywr,)get_subplotspec)rpr}s r&rrz+FigureBase.autofmt_xdate..s>2",,.>srFN)bottomT)_api check_in_listaxes_labelalllenget_xticklabelsset_ha set_rotationr is_last_row set_visible set_xlabelget_layout_engineadjust_compatiblesubplots_adjustr") r#rrotationharr}r allsubplotslabelengines r& autofmt_xdatezFigureBase.autofmt_xdatesg* 5UC!YYDr"))|*CDD>>> t9>155E5B - R ""8, -*B))+779%'%7%7e%7%D9E!LL,!..x89&(%7%7e%7%D5E!--e45 b)*'') FNf.F.F   / +Es E>E>c|jg|j|j|j|j|j |j |j|jS)z.Get a list of artists contained in the figure.) rxrbrarcrdrerfrgrhr1s r&rwzFigureBase.get_childrens       r(Nc|j|ur|S|j|jur |jS|d}tjd|d}|r |jS|jS)a Return the `.Figure` or `.SubFigure` instance the (Sub)Figure belongs to. Parameters ---------- root : bool, default=True If False, return the (Sub)Figure this artist is on. If True, return the root Figure for a nested tree of SubFigures. .. deprecated:: 3.10 From version 3.12 *root* will default to False. zFrom Matplotlib 3.12 SubFigure.get_figure will by default return the direct parent figure, which may be a SubFigure. To suppress this warning, pass the root parameter. Pass `True` to maintain the old behavior and `False` to opt-in to the future behavior.3.10messageT) _root_figure_parentrwarn_deprecated)r#r rs r&r!zFigureBase.get_figuresq    $K <<4,, ,<<  <.G   9D $$ $||r(cnd}||jurtjd|dyt|)z .. deprecated:: 3.10 Currently this method will raise an exception if *fig* is anything other than the root `.Figure` this (Sub)Figure is on. In future it will always raise an exception. z\The parent and root figures of a (Sub)Figure are set at instantiation and cannot be changed.rz= From Matplotlib 3.12 this operation will raise an exception.rN)rrrr;)r#r% no_switchs r& set_figurezFigureBase.set_figuresG< $## #  %;')) + ##r(TrzTThe root `Figure`. To get the parent of a `SubFigure`, use the `get_figure` method.docc|j|rdifS|jj|j|j}|ifS)z| Test whether the mouse event occurred on the figure. Returns ------- bool, {} F)_different_canvasbboxcontainsrWrX)r# mouseeventinsides r&rzFigureBase.contains%sD  ! !* -"9 ##JLL*,,?rzr(c|jSr,rr#r|s r&get_window_extentzFigureBase.get_window_extent2s yyr(c |jdd}|jdd}|ddvr|du}n |ddk(r|du}||d}||d}tj|t}|j d |d |j d |d |j d |d d|vrL|j dt j |d|j dt j |dt||d}|7|j||j||f|jdi|n%|j|||fi|}t||d||_ d|_|S)a Add a centered %(name)s to the figure. Parameters ---------- t : str The %(name)s text. x : float, default: %(x0)s The x location of the text in figure coordinates. y : float, default: %(y0)s The y location of the text in figure coordinates. horizontalalignment, ha : {'center', 'left', 'right'}, default: %(ha)s The horizontal alignment of the text relative to (*x*, *y*). verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, default: %(va)s The vertical alignment of the text relative to (*x*, *y*). fontsize, size : default: :rc:`figure.%(rc)ssize` The font size of the text. See `.Text.set_size` for possible values. fontweight, weight : default: :rc:`figure.%(rc)sweight` The font weight of the text. See `.Text.set_weight` for possible values. Returns ------- text The `.Text` instance of the %(name)s. Other Parameters ---------------- fontproperties : None or dict, optional A dict of font properties. If *fontproperties* is given the default values for font size and weight are taken from the `.FontProperties` defaults. :rc:`figure.%(rc)ssize` and :rc:`figure.%(rc)sweight` are ignored in this case. **kwargs Additional kwargs are `matplotlib.text.Text` properties. rWNrXname)r\r[r]x0y0horizontalalignmentrverticalalignmentvarfontpropertiesfontsizesize fontweightweightTrS)r6r^normalize_kwargsr setdefaultmplrcParamsgetattrset_text set_positionrjtextsetattr_autoposr")r#tinforkrWrXautopossuplabs r& _suplabelszFigureBase._suplabels6sR JJsD ! JJsD ! <6 64iG &\\ )4iG 9T A 9T A''5/d<-tDz:*d:&67 6 )   j#,,tF|*D E   lCLLh,H ItF|,   OOA    A ' FJJ  TYYq!Q1&1F D$v, /!  r(?\(\?z super titlecentertoprY)rrrrrrcc @ddddddddd }|j||fi|S) Nr[rrrrrzfigure.titlesizezfigure.titleweightrrrrrrrrrr#rrkrs r&suptitlezFigureBase.suptitles: $3de*6JLtq$1&11r(cB|j}|dS|jS)z>%r>8+<+<+>>r({Gz?z super xlabelrrc @ddddddddd }|j||fi|S) Nr\rrrrrfigure.labelsizefigure.labelweightrrrs r& supxlabelzFigureBase.supxlabels: %CthA*6JLtq$1&11r(cB|j}|dS|jS)z=Return the supxlabel as string or an empty string if not set.r)r\rrs r& get_supxlabelzFigureBase.get_supxlabel$??%r>8+<+<+>>r({Gz?z super ylabelleftc Bddddddddd d }|j||fi|S) Nr]rrrrverticalanchorrr) rrrrrr rotation_moderrrrs r& supylabelzFigureBase.supylabels< %DH*!)3E.0tq$1&11r(cB|j}|dS|jS)z=Return the supylabel as string or an empty string if not set.r)r]rrs r& get_supylabelzFigureBase.get_supylabelrr(c6|jjS)z+Get the edge color of the Figure rectangle.)rx get_edgecolorr1s r&rzFigureBase.get_edgecolorzz''))r(c6|jjS)z+Get the face color of the Figure rectangle.)rx get_facecolorr1s r&rzFigureBase.get_facecolorrr(c6|jjS)z Return the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to ``Figure.patch.get_visible()``. )rx get_visibler1s r& get_frameonzFigureBase.get_frameons zz%%''r(c:|jj|y)z Set the line width of the Figure rectangle. Parameters ---------- linewidth : number N)rx set_linewidth)r# linewidths r&rzFigureBase.set_linewidths   +r(c6|jjS)z= Get the line width of the Figure rectangle. )rx get_linewidthr1s r&rzFigureBase.get_linewidthszz''))r(c:|jj|y)z Set the edge color of the Figure rectangle. Parameters ---------- color : :mpltype:`color` N)rx set_edgecolorr#colors r&rzFigureBase.set_edgecolor   'r(c:|jj|y)z Set the face color of the Figure rectangle. Parameters ---------- color : :mpltype:`color` N)rx set_facecolorrs r&rzFigureBase.set_facecolorrr(cH|jj|d|_y)z Set the figure's background patch visibility, i.e. whether the figure background will be drawn. Equivalent to ``Figure.patch.set_visible()``. Parameters ---------- b : bool TN)rxrr")r#bs r& set_frameonzFigureBase.set_frameons q! r(FcR|j||jj||jj|_|j s|j |j|r+|j|j|jd|_ |S)a Add an `.Artist` to the figure. Usually artists are added to `~.axes.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. Parameters ---------- artist : `~matplotlib.artist.Artist` The artist to add to the figure. If the added artist has no transform previously set, its transform will be set to ``figure.transSubfigure``. clip : bool, default: False Whether the added artist should be clipped by the figure patch. Returns ------- `~matplotlib.artist.Artist` The added artist. T) rrbappendr9_remove_methodis_transform_set set_transformtransSubfigure get_clip_path set_clip_pathrxr")r#rqclips r& add_artistzFigureBase.add_artists, $ F# $ 3 3&&(  !4!4 5 F((*2   ,  r(cBt|sd|vr tdd|vr(t|r td|jdf}t|dk7r tjddt|t |dt r/|\}|j}|jd|urctd |\}tj|jstd ||jd i|\}}|||fi|}||f}|j||S) ad Add an `~.axes.Axes` to the figure. Call signatures:: add_axes(rect, projection=None, polar=False, **kwargs) add_axes(ax) Parameters ---------- rect : tuple (left, bottom, width, height) The dimensions (left, bottom, width, height) of the new `~.axes.Axes`. All quantities are in fractions of figure width and height. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional The projection type of the `~.axes.Axes`. *str* is the name of a custom projection, see `~matplotlib.projections`. The default None results in a 'rectilinear' projection. polar : bool, default: False If True, equivalent to projection='polar'. axes_class : subclass type of `~.axes.Axes`, optional The `.axes.Axes` subclass that is instantiated. This parameter is incompatible with *projection* and *polar*. See :ref:`axisartist_users-guide-index` for examples. sharex, sharey : `~matplotlib.axes.Axes`, optional Share the x or y `~matplotlib.axis` with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes. label : str A label for the returned Axes. Returns ------- `~.axes.Axes`, or a subclass of `~.axes.Axes` The returned Axes class depends on the projection used. It is `~.axes.Axes` if rectilinear projection is used and `.projections.polar.PolarAxes` if polar projection is used. Other Parameters ---------------- **kwargs This method also takes the keyword arguments for the returned Axes class. The keyword arguments for the rectilinear Axes class `~.axes.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. %(Axes:kwdoc)s Notes ----- In rare circumstances, `.add_axes` may be called with a single argument, an Axes instance already created in the present figure but not in the figure's list of Axes. See Also -------- .Figure.add_subplot .pyplot.subplot .pyplot.axes .Figure.subplots .pyplot.subplots Examples -------- Some simple examples:: rect = l, b, w, h fig = plt.figure() fig.add_axes(rect) fig.add_axes(rect, frameon=False, facecolor='g') fig.add_axes(rect, polar=True) ax = fig.add_axes(rect, projection='polar') fig.delaxes(ax) fig.add_axes(ax) rectz9add_axes() missing 1 required positional argument: 'rect'z2add_axes() got multiple values for argument 'rect'radd_axesrFr5The Axes must have been created in the present figurez'all entries in rect must be finite not rS)r TypeErrorr6r nargs_error isinstancer_projection_initr!r;npisfiniter _process_projection_requirements_add_axes_internal)r#argsrkr8rArprojection_classpkws r&rzFigureBase.add_axess0l4yV61WX X v 4y TUUJJv&)D t9>"":q#d)< < d1gt $BA$$C|||'t3 KMMED;;t$((* #J4&!QRR$ID$I$I$SF$S ! c!t3s3A#S)C&&q#..r(c ^d|vrtjddt|dk(rtt|dtj j jrC|djr0|d}|j}|jd|urtd|sd}t|dk(rIt|dtr6d |dcxkrd kr(nn%tttt!|d}|j"d i|\}}||g|i|}||f}|j%||S) aw Add an `~.axes.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 ---------- *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1) The position of the subplot described by one of - Three integers (*nrows*, *ncols*, *index*). The subplot will take the *index* position on a grid with *nrows* rows and *ncols* columns. *index* starts at 1 in the upper left corner and increases to the right. *index* can also be a two-tuple specifying the (*first*, *last*) indices (1-based, and including *last*) of the subplot, e.g., ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the upper 2/3 of the figure. - A 3-digit integer. The digits are interpreted as if given separately as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used if there are no more than 9 subplots. - A `.SubplotSpec`. In rare circumstances, `.add_subplot` may be called with a single argument, a subplot Axes instance already created in the present figure but not in the figure's list of Axes. projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', str}, optional The projection type of the subplot (`~.axes.Axes`). *str* is the name of a custom projection, see `~matplotlib.projections`. The default None results in a 'rectilinear' projection. polar : bool, default: False If True, equivalent to projection='polar'. axes_class : subclass type of `~.axes.Axes`, optional The `.axes.Axes` subclass that is instantiated. This parameter is incompatible with *projection* and *polar*. See :ref:`axisartist_users-guide-index` for examples. sharex, sharey : `~matplotlib.axes.Axes`, optional Share the x or y `~matplotlib.axis` with sharex and/or sharey. The axis will have the same limits, ticks, and scale as the axis of the shared Axes. label : str A label for the returned Axes. Returns ------- `~.axes.Axes` The Axes of the subplot. The returned Axes can actually be an instance of a subclass, such as `.projections.polar.PolarAxes` for polar projections. Other Parameters ---------------- **kwargs This method also takes the keyword arguments for the returned Axes base class; except for the *figure* argument. The keyword arguments for the rectilinear base class `~.axes.Axes` can be found in the following table but there might also be other keyword arguments if another projection is used. %(Axes:kwdoc)s See Also -------- .Figure.add_axes .pyplot.subplot .pyplot.axes .Figure.subplots .pyplot.subplots Examples -------- :: fig = plt.figure() fig.add_subplot(231) ax1 = fig.add_subplot(2, 3, 1) # equivalent but more general fig.add_subplot(232, frameon=False) # subplot with no frame fig.add_subplot(233, projection='polar') # polar subplot fig.add_subplot(234, sharex=ax1) # subplot sharing x-axis with ax1 fig.add_subplot(235, facecolor="red") # red subplot ax1.remove() # delete ax1 from the figure fig.add_subplot(ax1) # add ax1 back to the figure figure add_subplotrrFrr)rrrdirS)r kwarg_errorrrrr_base _AxesBaserrr!r;rtuplemapintstrrr)r#rrkr}rAr r!s r&r$zFigureBase.add_subplots,J v ""=(; ; INtAw(@(@AG++-aB%%C}}%}(4 "677 D Q:d1gx#@tAw-#-Sc$q'l34$ID$I$I$SF$S ! c!$555B#S)C&&r3//r(c|jj|||jvr|jj||j ||j |_||_d|_t|_ |S)z0Private helper for `add_axes` and `add_subplot`.T) _axstackr?rar scadelaxesr rr"r'stale_callback)r#r}rAs r&rzFigureBase._add_axes_internalse " T__ $ OO " "2 &   LL! 2 r()sharexshareysqueeze width_ratios height_ratios subplot_kw gridspec_kwct| xsi} |d| vr td|| d<|d| vr td|| d<|j||fd|i| } | j||||} | S)ab 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 ---------- nrows, ncols : int, default: 1 Number of rows/columns of the subplot grid. sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False Controls sharing of x-axis (*sharex*) or y-axis (*sharey*): - True or 'all': x- or y-axis will be shared among all subplots. - False or 'none': each subplot x- or y-axis will be independent. - 'row': each subplot row will share an x- or y-axis. - 'col': each subplot column will share an x- or y-axis. When subplots have a shared x-axis along a column, only the x tick labels of the bottom subplot are created. Similarly, when subplots have a shared y-axis along a row, only the y tick labels of the first column subplot are created. To later turn other subplots' ticklabels on, use `~matplotlib.axes.Axes.tick_params`. When subplots have a shared axis that has units, calling `.Axis.set_units` will update each axis with the new units. Note that it is not possible to unshare axes. squeeze : bool, 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. width_ratios : array-like of length *ncols*, optional Defines the relative widths of the columns. Each column gets a relative width of ``width_ratios[i] / sum(width_ratios)``. If not given, all columns will have the same width. Equivalent to ``gridspec_kw={'width_ratios': [...]}``. height_ratios : array-like of length *nrows*, optional Defines the relative heights of the rows. Each row gets a relative height of ``height_ratios[i] / sum(height_ratios)``. If not given, all rows will have the same height. Equivalent to ``gridspec_kw={'height_ratios': [...]}``. subplot_kw : dict, optional Dict with keywords passed to the `.Figure.add_subplot` call used to create each subplot. gridspec_kw : dict, optional Dict with keywords passed to the `~matplotlib.gridspec.GridSpec` constructor used to create the grid the subplots are placed on. Returns ------- `~.axes.Axes` or array of Axes Either a single `~matplotlib.axes.Axes` object or an array of Axes objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the *squeeze* keyword, see above. See Also -------- .pyplot.subplots .Figure.add_subplot .pyplot.subplot Examples -------- :: # First create some toy data: x = np.linspace(0, 2*np.pi, 400) y = np.sin(x**2) # Create a figure fig = plt.figure() # Create a subplot ax = fig.subplots() ax.plot(x, y) ax.set_title('Simple plot') # Create two subplots and unpack the output array immediately ax1, ax2 = fig.subplots(1, 2, sharey=True) ax1.plot(x, y) ax1.set_title('Sharing Y axis') ax2.scatter(x, y) # Create four polar Axes and access them through the returned array axes = fig.subplots(2, 2, subplot_kw=dict(projection='polar')) axes[0, 0].plot(x, y) axes[1, 1].scatter(x, y) # Share an X-axis with each column of subplots fig.subplots(2, 2, sharex='col') # Share a Y-axis with each row of subplots fig.subplots(2, 2, sharey='row') # Share both X- and Y-axes with all subplots fig.subplots(2, 2, sharex='all', sharey='all') # Note that this is the same as fig.subplots(2, 2, sharex=True, sharey=True) r6Q'height_ratios' must not be defined both as parameter and as key in 'gridspec_kw'r5P'width_ratios' must not be defined both as parameter and as key in 'gridspec_kw'r#)r2r3r4r7)dictr; add_gridspecsubplots) r#nrowsncolsr2r3r4r5r6r7r8gsaxss r&r>zFigureBase.subplotssr;,"-  $+- "IJJ+8K (  #, "IJJ*6K ' T  ue HD HK Hkk%/1 r(cV|j||j|jgy)zY Remove the `~.axes.Axes` *ax* from the figure; update the current Axes. )ownersN) _remove_axesr.rar#r}s r&r0zFigureBase.delaxess$ "dmmT__%EFr(c|D]}|j||jjd|d|_|jj j ||jD]}|j|}|j|Dcgc] }||us| }}|s8|j||dj|}|jj||jj||jj||jj||j j|ycc}w)aD Common helper for removal of standard Axes (via delaxes) and of child Axes. Parameters ---------- ax : `~.AxesBase` The Axes to remove. owners List of objects (list or _AxesStack) "owning" the Axes, from which the Axes will be remove()d. _axes_change_eventTrN)r9 _axobserversprocessr"rcanvas release_mouse _axis_names _shared_axes get_siblings _axis_mapget_major_formatterset_axisget_major_locatorget_minor_formatterget_minor_locator _twinned_axes) r#r}rDownerrgrouperothersiblingsremaining_axiss r&rEzFigureBase._remove_axessA E LL   !!"6=    ..r2NN HDood+G+2+?+?+CW%uTVWHW NN2 &a[2248N  . . 0 9 9. I  , , . 7 7 G  . . 0 9 9. I  , , . 7 7 G H #Xs  E"E"cd|_|jD]}|j|g|_t|jD]#}|j|j |%g|_g|_g|_g|_ g|_ g|_ |stj|_d|_d|_d|_d|_y)z Clear the figure. Parameters ---------- keep_observers : bool, default: False Set *keep_observers* to True if, for example, a gui widget is tracking the Axes in the figure. Nkeep_observersT)rirhclearr)rr0rbrcrdrerfrgr^CallbackRegistryrIr[r\r]r")r#r^subfigr}s r&r_zFigureBase.clears"&ll 8F LLL 7 8  " B HHJ LL         % 6 6 8D  r(c&|j|S)a} [*Discouraged*] Alias for the `clear()` method. .. admonition:: Discouraged The use of ``clf()`` is discouraged. Use ``clear()`` instead. Parameters ---------- keep_observers : bool, default: False Set *keep_observers* to True if, for example, a gui widget is tracking the Axes in the figure. r])r_)r#r^s r&clfzFigureBase.clfszzz88r(c6tj|jg|i|\}}}|jd|jtj |||fi|}|j j||j j|_ d|_ |S)a4 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 :meth:`~.Artist.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** .. admonition:: 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']) Parameters ---------- handles : list 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 : list of str, 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 ------- `~matplotlib.legend.Legend` Other Parameters ---------------- %(_legend_kw_figure)s See Also -------- .Axes.legend Notes ----- Some artists are not supported by this function. See :ref:`legend_guide` for details. bbox_transformT) mlegend_parse_legend_argsrrrLegendrgr r9r r")r#rrkhandleslabelsls r&legendzFigureBase.legends^#*"<"> )RZZ8 "''  kk"oUrUT1)jej4 J%%'3--/AA$ "2sxx~~'?'?@**,"55bCFC V"nnR:6: V GGJ  HHU&vH > Hl +&.&9&9t&9&DD"Q (9(99""@ 1236 1 1234567 H ]]3L#\\^-KQq8I/IAqD-KL+/E"( -Ks  H (H cr|j0|jjstjdy|jj |||||||j D]A}|j|j|jj|Cd|_ y)aQ Adjust the subplot layout parameters. Unset parameters are left unmodified; initial values are given by :rc:`figure.subplot.[name]`. .. plot:: _embedded_plots/figure_subplots_adjust.py Parameters ---------- left : float, optional The position of the left edge of the subplots, as a fraction of the figure width. right : float, optional The position of the right edge of the subplots, as a fraction of the figure width. bottom : float, optional The position of the bottom edge of the subplots, as a fraction of the figure height. top : float, optional The position of the top edge of the subplots, as a fraction of the figure height. wspace : float, optional The width of the padding between subplots, as a fraction of the average Axes width. hspace : float, optional The height of the padding between subplots, as a fraction of the average Axes height. NzThis figure was using a layout engine that is incompatible with subplots_adjust and/or tight_layout; not calling subplots_adjust.T) rrrr subplotparsrKrr _set_position get_positionr")r#rrrightrwspacehspacer}s r&rzFigureBase.subplots_adjust!s>  " " $ 0**,>>   / 0  feS&&I)) JB!!#/  !3!3!5!B!B4!HI J r(c| |j}tj|Dcgc]}|j|}}|D]}tj d|j |jj}|jj}|D]}|jj|k(s!|jj}|dk(r|j|jk(s |dk(s_|j|jk(sy|jdj||ycc}w)a Align the xlabels of subplots in the same subplot row if label alignment is being done automatically (i.e. the label position is not manually set). Alignment persists for draw events after this is called. If a label is on the bottom, it is aligned with labels on Axes that also have their label on the bottom and that have the same bottom-most subplot row. If the label is on the top, it is aligned with labels on Axes with the same top-most row. Parameters ---------- axs : list of `~matplotlib.axes.Axes` Optional list of (or `~numpy.ndarray`) `~matplotlib.axes.Axes` to align the xlabels. Default is to align all Axes on the figure. See Also -------- matplotlib.figure.Figure.align_ylabels matplotlib.figure.Figure.align_titles matplotlib.figure.Figure.align_labels Notes ----- This assumes that all Axes in ``axs`` are from the same `.GridSpec`, so that their `.SubplotSpec` positions correspond to figure positions. Examples -------- Example with rotated xtick labels:: fig, axs = plt.subplots(1, 2) 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() N Working on: %srrrW)rrravelr_logdebug get_xlabelrowspanxaxisget_label_positionstartstopr`join)r#rBr}rposaxcrowspancs r& align_xlabelszFigureBase.align_xlabelsMsT ;))CHHSMNbR-?-?-A-MrNN DB JJ("--/ :((*22G((--/C  D99//1S8"224<D>c| |j}tj|Dcgc]}|j|}}|D]}tj d|j |jj}|jj}|D]}|jj|k(s!|jj}|dk(r|j|jk(s |dk(s_|j|jk(sy|jdj||ycc}w)a 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 `~matplotlib.axes.Axes` Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes` to align the ylabels. Default is to align all Axes on the figure. See Also -------- matplotlib.figure.Figure.align_xlabels matplotlib.figure.Figure.align_titles matplotlib.figure.Figure.align_labels Notes ----- This assumes that all Axes in ``axs`` are from the same `.GridSpec`, so that their `.SubplotSpec` positions correspond to figure positions. Examples -------- Example with large yticks labels:: fig, axs = plt.subplots(2, 1) axs[0].plot(np.arange(0, 1000, 50)) axs[0].set_ylabel('YLabel 0') axs[1].set_ylabel('YLabel 1') fig.align_ylabels() NrrrrX)rrrrrr get_ylabelcolspanyaxisrrrr`r)r#rBr}rrrcolspancs r& align_ylabelszFigureBase.align_ylabelssR ;))CHHSMNbR-?-?-A-MrNN DB JJ("--/ :((*22G((--/C  D99//1S8"224<>*I7Nw||x}}/L005::2sC  D DOrc| |j}tj|Dcgc]}|j|}}|D]}tj d|j |jj}|D]U}|jj}|j|jk(s7|jdj||Wycc}w)aP Align the titles of subplots in the same subplot row if title alignment is being done automatically (i.e. the title position is not manually set). Alignment persists for draw events after this is called. Parameters ---------- axs : list of `~matplotlib.axes.Axes` Optional list of (or ndarray) `~matplotlib.axes.Axes` to align the titles. Default is to align all Axes on the figure. See Also -------- matplotlib.figure.Figure.align_xlabels matplotlib.figure.Figure.align_ylabels matplotlib.figure.Figure.align_labels Notes ----- This assumes that all Axes in ``axs`` are from the same `.GridSpec`, so that their `.SubplotSpec` positions correspond to figure positions. Examples -------- Example with titles:: fig, axs = plt.subplots(1, 2) axs[0].set_aspect('equal') axs[0].set_title('Title 0') axs[1].set_title('Title 1') fig.align_titles() NrrY) rrrrrr get_titlerrr`r)r#rBr}rrrs r& align_titleszFigureBase.align_titlessH ;))CHHSMNbR-?-?-A-MrNN DB JJ(",,. 9((*22G D..088MMX^^3,,W5::2sC D DOs C"C"cL|j||j|y)a 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 `~matplotlib.axes.Axes` Optional list (or `~numpy.ndarray`) of `~matplotlib.axes.Axes` to align the labels. Default is to align all Axes on the figure. See Also -------- matplotlib.figure.Figure.align_xlabels matplotlib.figure.Figure.align_ylabels matplotlib.figure.Figure.align_titles Notes ----- This assumes that all Axes in ``axs`` are from the same `.GridSpec`, so that their `.SubplotSpec` positions correspond to figure positions. )rBN)rr)r#rBs r& align_labelszFigureBase.align_labelss&4 s# s#r(c H|jdd}td|||d|}|S)aS Low-level API for creating a `.GridSpec` that has this figure as a parent. This is a low-level API, allowing you to create a gridspec and subsequently add subplots based on the gridspec. Most users do not need that freedom and should use the higher-level methods `~.Figure.subplots` or `~.Figure.subplot_mosaic`. Parameters ---------- nrows : int, default: 1 Number of rows in grid. ncols : int, default: 1 Number of columns in grid. Returns ------- `.GridSpec` Other Parameters ---------------- **kwargs Keyword arguments are passed to `.GridSpec`. See Also -------- matplotlib.pyplot.subplots Examples -------- Adding a subplot that spans two rows:: fig = plt.figure() gs = fig.add_gridspec(2, 2) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[1, 0]) # spans two rows: ax3 = fig.add_subplot(gs[:, 1]) r#N)r?r@r#rS)r6r)r#r?r@rk_rAs r&r=zFigureBase.add_gridspecs0V JJx &  FEt Fv F r(c Ht|||||||dddd } tj||ft} t |D]/} t |D]} |j | | | ffi|| | | f<!1|j p||l| j|\} }}}t| | |D]F\}}}t|||D]0\}}}tj||||}|j|2H|r/| jdk(r| jS| jS| S)a* Add a set of subfigures to this figure or subfigure. A subfigure has the same artist methods as a figure, and is logically the same as a figure, but cannot print itself. See :doc:`/gallery/subplots_axes_and_figures/subfigures`. .. versionchanged:: 3.10 subfigures are now added in row-major order. Parameters ---------- nrows, ncols : int, default: 1 Number of rows/columns of the subfigure grid. squeeze : bool, default: True If True, extra dimensions are squeezed out from the returned array of subfigures. wspace, hspace : float, default: None The amount of width/height reserved for space between subfigures, expressed as a fraction of the average subfigure width/height. If not given, the values will be inferred from rcParams if using constrained layout (see `~.ConstrainedLayoutEngine`), or zero if not using a layout engine. width_ratios : array-like of length *ncols*, optional 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. height_ratios : array-like of length *nrows*, optional 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. rr) r?r@r#rrr5r6rrrrdtyper)rremptyobjectrange add_subfigurerget_grid_positionszipr from_extents_redo_transform_rel_figritemr4)r#r?r@r4rrr5r6rkrAsfarrijbottomstopsleftsrightssfrowrrsfrrrs r& subfigureszFigureBase.subfiguresCsZPEt#F#/$1AaQ 8 %v6u EA5\ E0d00AqDDVDad  E E  ! ! # +1C171C,.+@+@+F (GT5&&)%$&? :"vs'*5%'@:OBe,,T65#FD..D.9: : $)::?5::< G  GLr(c t||fi|}|xj|gz c_|jj|_t|_d|_|S)a Add a `.SubFigure` to the figure as part of a subplot arrangement. Parameters ---------- subplotspec : `.gridspec.SubplotSpec` Defines the region in a parent gridspec where the subfigure will be placed. Returns ------- `.SubFigure` Other Parameters ---------------- **kwargs Are passed to the `.SubFigure` object. See Also -------- .Figure.subfigures T) SubFigurerhr9r r'r1r")r# subplotspecrkrs r&rzFigureBase.add_subfiguresK.t[ 3F 3   LL//2  r(ct|jj||jjd||S)z.Set the current Axes to be *a* and return *a*.rH)r.r=rIrJr7s r&r/zFigureBase.scas0 Q !!"6=r(c^|jj}||S|jS)a 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.) )r.rEr$rFs r&r}zFigureBase.gcas.]] " " $^r;)9)9);;r(c|jj}|y|j}||St|jD]}|j}||cSy)a> Get the current colorable artist. Specifically, returns the current `.ScalarMappable` instance (`.Image` created by `imshow` or `figimage`, `.Collection` created by `pcolor` or `scatter`, etc.), or *None* if no such instance has been defined. The current image is an attribute of the current Axes, or the nearest earlier Axes in the current figure that contains an image. Notes ----- Historically, the only colorable artists were images; hence the name ``gci`` (get current image). N)r.rE_gcireversedr)r#r}ims r&rzFigureBase._gcisg$]] " " $ : WWY >I499% BB~  r() axes_classpolar projectionc F||s| td|}||fS|r||dk7rtd|d|dd}t|ts|tj|}||fSt |dr)|j \}}|jdi|||fStd|) z Handle the args/kwargs to add_axes/add_subplot/gca, returning:: (axes_proj_class, proj_class_kwargs) which can be used for new Axes initialization/identification. z7Cannot combine 'axes_class' and 'projection' or 'polar'rzpolar=z, yet projection=z1. Only one of these arguments should be supplied. _as_mpl_axeszJprojection must be a string, None or implement a _as_mpl_axes method, not rS) r;rr,rget_projection_classr{rrKr)r#rrrrkr  extra_kwargss r&rz+FigureBase._process_projection_requirementss  ! . MOO) ( ''#)jG.C$ '8GJJ% *c*j.@#.#C#CJ#O  ''^41;1H1H1J. , - -  '' 00:~?@@r(c |jDcgc]$}|jr|jr|&}}|jD]2}|js|j |j 4|Scc}w)zU Return a list of Artists typically used in `.Figure.get_tightbbox`. )rwr get_in_layoutrextendget_default_bbox_extra_artists)r#rq bbox_artistsr}s r&rz)FigureBase.get_default_bbox_extra_artistss.2->->-@N6"..0V5I5I5KN N)) IB~~##B$E$E$GH I Ns)Bbbox_extra_artistsc| |jdj}g}|L|jDcgc]2}||jvr"|j r|j r|4}}n|}|D]'}|j |}||j|)|jD]8}|j s |j ||}|j|:|D cgc]`} tj| jr?tj| jr | jdk7s| jdk7r| b}} t|d} t|dk(r| r |jS|j g}t#j$|} | r$t'| |j(j+} | Scc}w#t$r|j |}YwxYwcc} w)aF 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. Parameters ---------- renderer : `.RendererBase` subclass Renderer that will be used to draw the figures (i.e. ``fig.canvas.get_renderer()``) bbox_extra_artists : list of `.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. Returns ------- `.BboxBase` containing the bounding box (in figure inches). Trrr bbox_inches)r!rrwrrr get_tightbboxr rrrwidthheightr{rrrrunionrdpi_scale_transinverted) r#r|rbbrqrbr8rr}risfigure_bboxs r&rzFigureBase.get_tightbboxs6  D1??AH   %,0,=,=,?8&!2v7I7I7K%3358G8)G A??8,D $ )) B~~6++ 5G,ID $ 8A++agg&2;;qxx+@ww!|qxx1}884/ r7a<'''ii[ 2 #E4+?+?+H+H+JKE O8$!6++H5D68s7GG ,A%G+ G('G(ci}|jD]M\}}t|tr |D]}||vrtd|d|||<6||vrtd|d|||<O|S)NzThe key z appears multiple times.)rrr)r;)per_subplot_kwexpandedrrsub_keys r&_norm_per_subplot_kwzFigureBase._norm_per_subplot_kwQs"((* DAq!U# *G(*(8G;>V)WXX()HW%* =$xu4L%MNN  r(cd|vr(|jdDcgc] }t|c}Stj|}|j djdDcgc] }t|c}Scc}wcc}w)N ;)splitlistinspectcleandocstrip)layoutlns r&_normalize_grid_stringz!FigureBase._normalize_grid_string`sn v '-||C'89DH9 9%%f-F'-||D'9'?'?'EFDHF F :Gs A9$A>.)r2r3r5r6empty_sentinelr7rr8cxsit| xsi} xsi|d| vr td|| d<|d| vr td|| d<t|tr>j |}j D cic]\} } t | | c} } jtjt||dfdfd|}|j\} } j| | fi| }||g|}tt|j}|jD]M}|r#|j!||j#d |s+|j%||j'd Ot)t)|z x}rtd |d |Scc} } w) a Build a layout of Axes based on ASCII art or nested lists. This is a helper function to build complex GridSpec layouts visually. See :ref:`mosaic` for an example and full API documentation Parameters ---------- mosaic : list of list of {hashable or nested} or str A visual layout of how you want your Axes to be arranged labeled as strings. For example :: x = [['A panel', 'A panel', 'edge'], ['C panel', '.', 'edge']] produces 4 Axes: - 'A panel' which is 1 row high and spans the first two columns - 'edge' which is 2 rows high and is on the right edge - 'C panel' which in 1 row and 1 column wide in the bottom left - a blank space 1 row and 1 column wide in the bottom center Any of the entries in the layout can be a list of lists of the same form to create nested layouts. If input is a str, then it can either be a multi-line string of the form :: ''' AAE C.E ''' where each character is a column and each line is a row. Or it can be a single-line string where rows are separated by ``;``:: 'AB;CC' The string notation allows only single character Axes labels and does not support nesting but is very terse. The Axes identifiers may be `str` or a non-iterable hashable object (e.g. `tuple` s may not be used). sharex, sharey : bool, default: False 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. width_ratios : array-like of length *ncols*, optional Defines the relative widths of the columns. Each column gets a relative width of ``width_ratios[i] / sum(width_ratios)``. If not given, all columns will have the same width. Equivalent to ``gridspec_kw={'width_ratios': [...]}``. In the case of nested layouts, this argument applies only to the outer layout. height_ratios : array-like of length *nrows*, optional Defines the relative heights of the rows. Each row gets a relative height of ``height_ratios[i] / sum(height_ratios)``. If not given, all rows will have the same height. Equivalent to ``gridspec_kw={'height_ratios': [...]}``. In the case of nested layouts, this argument applies only to the outer layout. subplot_kw : dict, optional Dictionary with keywords passed to the `.Figure.add_subplot` call used to create each subplot. These values may be overridden by values in *per_subplot_kw*. per_subplot_kw : dict, optional A dictionary mapping the Axes identifiers or tuples of identifiers to a dictionary of keyword arguments to be passed to the `.Figure.add_subplot` call used to create each subplot. The values in these dictionaries have precedence over the values in *subplot_kw*. If *mosaic* is a string, and thus all keys are single characters, it is possible to use a single string instead of a tuple as keys; i.e. ``"AB"`` is equivalent to ``("A", "B")``. .. versionadded:: 3.7 gridspec_kw : dict, optional Dictionary with keywords passed to the `.GridSpec` constructor used to create the grid the subplots are placed on. In the case of nested layouts, this argument applies only to the outer layout. For more complex layouts, users should use `.Figure.subfigures` to create the nesting. empty_sentinel : object, optional 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. Returns ------- dict[label, Axes] 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. r6r:r5r;)r2r3c|^}}t|tr tdt|dD]d\}}t|tr tdt |t |k7s9td|dt |d|d|dt |d t j t |t |ft }t|D]\}}t|D] \}}||||f<!|S) aJ Convert input into 2D array We need to have this internal function rather than ``np.asarray(..., dtype=object)`` so that a list of lists of lists does not get converted to an array of dimension > 2. Returns ------- 2D object array z$List mosaic specification must be 2Dr)rz@All of the rows must be the same length, however the first row (z ) has length z and row z (rr)rr,r; enumeraterrzerosr)inpr0restrroutrrs r& _make_arrayz.FigureBase.subplot_mosaic.._make_arraysIB"c" !GHH!$a0 1a%$%KLLr7c!f$$**,}SWIF##$#RuM#a&D  ((CHc"g.f=C!# "1%aL"DAq !C1I" "Jr(c tj}i}t|D]R\}}t|D]?\}}|k(r tj|s||||f</|j |ATt ||fS)ar Given a 2D object array, identify unique IDs and nested mosaics Parameters ---------- mosaic : 2D object array Returns ------- unique_ids : tuple The unique non-sub mosaic entries in this mosaic nested : dict[tuple[int, int], 2D object array] )r^ _OrderedSetris_scalar_or_stringr?r)) mosaic unique_idsnestedrrowrrr rs r&_identify_keys_and_nestedz._identify_keys_and_nesteds**,JF#F+ *3%cN*DAqN* "66q9)4Q1v"q) * *$f, ,r(c t}t}|D]}tj||k(}tj|d\}} tj|ddz\} } t || t | | f} || |k7j rtd|d|d|| df||| f<|jD]\\} }}d|d f|| |f<t|D]}||\}}}|dk(rR|} ||vrtd |d |j|| fid t|ij|i}|||<c|d k(rz|}|\} }|j\}}|| |fj|||g|}t|t|z}|rtd |d |d||j!|t#d|S)a< Recursively do the mosaic. Parameters ---------- gs : GridSpec mosaic : 2D object array The input converted to a 2D array for this level. unique_ids : tuple The identified scalar labels at this level of nesting. nested : dict[tuple[int, int]], 2D object array The identified nested mosaics, if any. Returns ------- dict[label, Axes] A flat dict of all of the Axes created. r)rtrzWhile trying to layout z we found that the label z4 specifies a non-rectangular or non-contiguous area.rNrzThere are duplicate keys z in the layout rz between the outer layout z and the nested layout zThis should never happen)r<rargwhereminrCsliceanyr;rryr$r,getshape subgridspecrjrK RuntimeError)rAr rroutput this_levelrindx start_row start_colend_rowend_colslcrr nested_mosaicrAargmethodr}rowscols nested_outputoverlap _do_layoutrrr#r7s r&r*z-FigureBase.subplot_mosaic.._do_layout-s&VFJ# I{{6T>2')vvd';$ 9#%66$Q#7!#; Y0% 72KL3K4',,.$26*=337(;BBCC 7;C5H Iy12 I$*0 E%A &*M8%D Aq6" E j)& C$.sO!c6V#Cv~(+DTFK;;A**FGG)))3#SY$($-00r:$B$&F4Lx'$'MDAq!.!4!4JD$$.1a4,,T48%%3=A%M "&kC ,>>G(7yA99? C66C_F MM-0&'ABBM& CNMr(T)skip_non_rectangular_axesz The keys z/ are in *per_subplot_kw* but not in the mosaic.)r<r;rr,rrr)rrcheck_isinstanceboolrr=r<iterrHr2_label_outer_xaxisr3_label_outer_yaxisrj)r#r r2r3r5r6rr7rr8rrr&r'rAretax0r}extrar*rr s` ``` @@@r&subplot_mosaiczFigureBase.subplot_mosaicjs\ %2 ;,"- '-2  $+- "IJJ+8K (  #, "IJJ*6K ' fc "008F(6(<(<(> $1a! N22>B d6&A < -8] ] ~V$\\ d T  tT 9[ 9VH&?&GH4 %&**, FB #%%%E #%%%E  F'#c(2 25 2E7#))  gsGc|||k7r|j|t|_|j|jyr,)rr'r1r rr7s r&_set_artist_propszFigureBase._set_artist_propss/ 9 LL 1 ++,r()g?rrr,F)rr)NNT)NNNNNN)rrTNNNN)DrOrPrQrRr2rrrwr!rproperty functoolspartialr#rrrr Substitutioncopyrrrrrrrrrrrrrrframeonrinterpdrr$rr>r0rEr_rcrlrrrrrrrr=rrr/r}rrrr staticmethodrrr4r6 __classcell__rls@r&rUrUvsB(>E+Z %N$$'i'' > :h (W6Z__Z 2!62? Z>f (W6Z__Z 2!62? **(,* (( {K0G!Fn/n/`}0}0~ H5D dHTG "$H!H9,uun//b<@uunGK,0*X<D|;Dz-D^$:-^48'+48CJ< <B>B48!(F GGR  GG05U$(&)"&tsj -r(rUceZdZdZdddddfd ZedZedZejdZd Z d Z d Z dd Z d Z ddZdZedZej"ZdZxZS)ra Logical figure that can be placed inside a figure. See :ref:`figure-api-subfigure` for an index of methods on this class. 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) See :doc:`/gallery/subplots_axes_and_figures/subfigures` N) facecolor edgecolorrr>c 4t|d i||d}|tjd}|tjd}||_||_|j |_|j|_|j|_|j|_ |j|_ |j|_ tj|_|j|j j |_t#|j|j j$|_t)|j&|_t+ddd||||d|j$ |_|j/|j,|j,j1dy) a Parameters ---------- parent : `.Figure` or `.SubFigure` Figure or subfigure that contains the SubFigure. SubFigures can be nested. subplotspec : `.gridspec.SubplotSpec` Defines the region in a parent gridspec where the subfigure will be placed. facecolor : default: ``"none"`` The figure patch face color; transparent by default. edgecolor : default: :rc:`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: :rc:`figure.frameon` If ``False``, suppress drawing the figure background patch. Other Parameters ---------------- **kwargs : `.SubFigure` properties, optional %(SubFigure:kwdoc)s Nnonefigure.edgecolorfigure.frameonrrrF) xyrrrsrErFr in_layoutrnrS)rZr2rr _subplotspecrrr.rrrI transFigurernull bbox_relativerfigbboxrrrrrrxr6set_antialiased) r#parentrrErFrr>rkrls r&r2zSubFigure.__init__sWH "6"  I   %78I ?ll#34G' "// !--%55"//!--!YY[ $$&||++ #D$6$6$(LL$?$?A -dii8Qq'9 t':': < tzz* ""5)r(c.|jjSr,)rrKr1s r&rKzSubFigure.canvass||"""r(c.|jjSr,rdpir1s r&rXz SubFigure.dpi s||r(c&||j_yr,rW)r#values r&rXz SubFigure.dpi s  r(c.|jjS)zY Return the resolution of the parent figure in dots-per-inch as a float. rWr1s r&get_dpizSubFigure.get_dpi s||r(c4||j_d|_y)z Set the resolution of parent figure in dots-per-inch. Parameters ---------- val : float TN)rrXr"r#r$s r&set_dpizSubFigure.set_dpi s  r(c6|jjSr,)rrr1s r&rzSubFigure._get_renderer s||))++r(c||7|j|j_|j|j_y|jj }t j |j}t j |j}||jjj|jz }||jjj|jz }|d|jjjj|jz }d|d|jjjj|jz z }||f|j_||z||zf|j_y)a Make the transSubfigure bbox relative to Figure transform. Parameters ---------- bbox : bbox or None If not None, then the bbox is used for relative bounding box. Otherwise, it is calculated from the subplotspec. Nr)p0rQp1rN get_gridspecrasarrayget_width_ratiosget_height_ratiosrsumrrr) r#rrAwrhrdxdyrrs r&rz!SubFigure._redo_transform_rel_fig s_  $(GGD   !$(GGD   !     + + - ZZ++- . ZZ,,. / !!)) * . . 02668 ; !!)) * . . 02668 ; 0""**00 1 5 5 7"&&( B 3T&&..33488:RVVXE E!#R!#b"r' 2r(c6|jjSzo Return whether constrained layout is being used. See :ref:`constrainedlayout_guide`. )rget_constrained_layoutr1s r&roz SubFigure.get_constrained_layout8 s ||2244r(c:|jj|S)ab Get padding for ``constrained_layout``. Returns a list of ``w_pad, h_pad`` in inches and ``wspace`` and ``hspace`` as fractions of the subplot. See :ref:`constrainedlayout_guide`. Parameters ---------- relative : bool If `True`, then convert from inches to figure relative. )relative)rget_constrained_layout_pads)r#rqs r&rrz%SubFigure.get_constrained_layout_pads@ s||777JJr(c6|jjSr,)rrr1s r&rzSubFigure.get_layout_engineP s||--//r(c |jddS)a List of Axes in the SubFigure. You can access and modify the Axes in the SubFigure through this list. Modifying this list has no effect. Instead, use `~.SubFigure.add_axes`, `~.SubFigure.add_subplot` or `~.SubFigure.delaxes` to add or remove an Axes. Note: The `.SubFigure.axes` property and `~.SubFigure.get_axes` method are equivalent. N)rar1s r&rzSubFigure.axesS sq!!r(cn|jsy|j|} |jd|j|jj |t j||||jdj|jdd|_ y#d|_ wxYw)N subfiguregidTrF) rr open_groupget_gidrxdrawmimage_draw_list_compositing_imagesr!ri close_groupr"r#r|rbs r&r{zSubFigure.drawd s! ((2       @ JJOOH %  0 0$d)C)U)U W   -DJDJs A?B++ B4r,r8)rOrPrQrRr2r9rKrXsetterr\r_rrrorrrrfgetget_axesr{rArBs@r&rrs&  C*J##   ZZ!! ,325K 0 " "yyHr(rc ,eZdZdZej ZdZdZ d>dddddddddfd Z fdZ d Z d?d Z d Z d Zd@dZedZej$ZedZej*dZdZdZd@dZeeedZdZej8ddd dZdZej8ddd dZej8ddd d Z ej8dd!d dAd"Z!d#Z"e#jH dBdd$d%Z%dCd&Z&d'Z'd(Z(d)Z)d*Z*d+Z+d@d,Z,d@d-Z-dAfd. Z.e/e0d/Z1d0Z2d1Z3fd2Z4d3Z5d4Z6dd5d6Z7d7d8d e8jre8jte8jvfd9ZxZ?S)EFigurea The top level container for all the plot elements. See `matplotlib.figure` for an index of class methods. Attributes ---------- patch The `.Rectangle` instance representing the figure background patch. suppressComposite For multiple images, the figure will make composite images depending on the renderer option_image_nocomposite function. If *suppressComposite* is a boolean, this will override the renderer. cFdt|jjzS)Nz Figure(%gx%g))r)rrr1s r&__str__zFigure.__str__ styy~~!666r(cdj|jj|jjd|jjdt |j S)Nz.<{clsname} size {h:g}x{w:g} with {naxes} Axes>rr)clsnamehwnaxes)formatrlrOrrrrr1s r&__repr__zFigure.__repr__ sR?FFNN++iinnQ499>>!#4dii.G  r(NrD)rErFrr>r tight_layoutconstrained_layoutrc Pt |di| ||_d|_| A|t j d| t j d|j | n|Z| t j d|j dt|tr|jjdi|nl| Xt| tr3|j d|jjdi| n'| r%|j dn|j | tjtj|_|jj } | d t"j$| d t"j$| d t"j$| d t"j&| d t"j&| d t"j&| dt"j&g|_| d |j*|_| d |j*|_|t0j2d}|t0j2d}|t0j2d}|t0j2d}|t0j2d}t5j6|j9r&t5j:|dkj=rt?d|tAjBddg||_"tGjI||_%||_&tO|jD|jJ|_(|jP|_)tU|jP|_+|jV|_,t[ddd||||d|_.|j_|j\|j\jadt|| tc}||_2tg|_4|jky)a Parameters ---------- figsize : 2-tuple of floats, default: :rc:`figure.figsize` Figure dimension ``(width, height)`` in inches. dpi : float, default: :rc:`figure.dpi` Dots per inch. facecolor : default: :rc:`figure.facecolor` The figure patch facecolor. edgecolor : default: :rc:`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: :rc:`figure.frameon` If ``False``, suppress drawing the figure background patch. subplotpars : `~matplotlib.gridspec.SubplotParams` Subplot parameters. If not given, the default subplot parameters :rc:`figure.subplot.*` are used. tight_layout : bool or dict, default: :rc:`figure.autolayout` Whether to use the tight layout mechanism. See `.set_tight_layout`. .. admonition:: 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. constrained_layout : bool, default: :rc:`figure.constrained_layout.use` This is equal to ``layout='constrained'``. .. admonition:: Discouraged The use of this parameter is discouraged. Please use ``layout='constrained'`` instead. layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None}, default: None The layout mechanism for positioning of plot elements to avoid overlapping Axes decorations (labels, ticks, etc). Note that layout managers can have significant performance penalties. - 'constrained': The constrained layout solver adjusts Axes sizes to avoid overlapping Axes decorations. Can handle complex plot layouts and colorbars, and is thus recommended. See :ref:`constrainedlayout_guide` for examples. - 'compressed': uses the same algorithm as 'constrained', but removes extra space between fixed-aspect-ratio Axes. Best for simple grids of Axes. - 'tight': Use the tight layout mechanism. This is a relatively simple algorithm that adjusts the subplot parameters so that decorations do not overlap. See :ref:`tight_layout_guide` for examples. - 'none': Do not use a layout engine. - A `.LayoutEngine` instance. Builtin layout classes are `.ConstrainedLayoutEngine` and `.TightLayoutEngine`, more easily accessible by 'constrained' and 'tight'. Passing an instance allows third parties to provide their own layout engine. If not given, fall back to using the parameters *tight_layout* and *constrained_layout*, including their config defaults :rc:`figure.autolayout` and :rc:`figure.constrained_layout.use`. Other Parameters ---------------- **kwargs : `.Figure` properties, optional %(Figure:kwdoc)s NzdThe Figure parameters 'layout' and 'tight_layout' cannot be used together. Please use 'layout' only.zjThe Figure parameters 'layout' and 'constrained_layout' cannot be used together. Please use 'layout' only.)rztThe Figure parameters 'tight_layout' and 'constrained_layout' cannot be used together. Please use 'layout' parametertight constrained)signalskey_press_eventkey_release_eventbutton_press_eventbutton_release_event scroll_eventmotion_notify_eventfigure.figsizez figure.dpizfigure.facecolorrIrJr(figure size must be positive finite not rKrF)rLrrrsrErFrrMrS)6rZr2r_layout_enginerrset_layout_enginerr<rrjr^r`r events_canvas_callbacks_connect_picklabler _key_handler_mouse_handler_mouse_key_idspick_button_pick_id_scroll_pick_idrrrrrarrayrr;r from_boundsrrscaler_dpirrrRrrOrrrxr6rSrrr*r.r_)r#figsizerXrErFrr>rrrrrkconnectrls r&r2zFigure.__init__ s@ "6" "  (""BC#.""IJ  " "& " 1  %!-"")*  " "' " 2,-,&&(,,<|<  +,d3&&m&<,&&(,,B/AB#&&m&<  " "& " 1 "'!7!7$++"-((;; %}'A'A B ')C)C D ')C)C D (-*F*F G *M,H,H I NM$@$@ A )=+G+G H  '';TYYG&~tyyA ?ll#34G ;,,|,C   %78I   %78I ?ll#34G{{7#'')bhhw.?!.C-H-H-JG 'y*+ +++Aq;7;'z//4 #D$4$4d6J6JK yy *4995"..Qq'9   tzz* ""5)  '/K&"   r(cn|jjjst||yyr,)rK widgetlocklockedrZr)r#rrls r&rz Figure.pick^ s*{{%%,,. GL $/r(c||y|j|jk(ry|jD]}t|dsyy)z Helper for set_layout engine If the figure has used the old engine and added a colorbar then the value of colorbar_gridspec must be the same on the new engine. T _colorbarF)r~rr{)r#oldnewr}s r&_check_layout_engines_compatz#Figure._check_layout_engines_compatb sN ;#+  C$9$9 9)) Br;' r(c |4tjdrd}ntjdrd}nd|_y|dk(r td i|}n|dk(r t d i|}n}|dk(rt d ddi|}nj|d k(rD|j5t |jj |jj}n$d}n!t|tr|}ntd ||j|j|r||_ytd ) a Set the layout engine for this figure. Parameters ---------- layout : {'constrained', 'compressed', 'tight', 'none', `.LayoutEngine`, None} - 'constrained' will use `~.ConstrainedLayoutEngine` - 'compressed' will also use `~.ConstrainedLayoutEngine`, but with a correction that attempts to make a good layout for fixed-aspect ratio Axes. - 'tight' uses `~.TightLayoutEngine` - 'none' removes layout engine. If a `.LayoutEngine` instance, that instance will be used. If `None`, the behavior is controlled by :rc:`figure.autolayout` (which if `True` behaves as if 'tight' was passed) and :rc:`figure.constrained_layout.use` (which if `True` behaves as if 'constrained' was passed). If both are `True`, :rc:`figure.autolayout` takes priority. Users and libraries can define their own layout engines and pass the instance directly as well. **kwargs The keyword arguments are passed to the layout engine to set things like padding and margin sizes. Only used if *layout* is a string. Nfigure.autolayoutrfigure.constrained_layout.user compressedcompressTrHzInvalid value for 'layout': zzColorbar layout of new layout engine not compatible with old engine, and a colorbar has been created. Engine not changed.rS) rrrrrrrr~rrr;rr)r#rrknew_layout_engines r&rzFigure.set_layout_engineu s(> >||/0 =>&&*# W  1 ;F ;  } $ 7 A& A  | # 7!B!B:@!B  v "".$;''99''99%! %)!  - & ;F:FG G  , ,T-@-@-> @"3D  HI Ir(c|jSr,)rr1s r&rzFigure.get_layout_engine s"""r(ctdt|jjvrddlm}|j |Sy)NWebAggr)backend_webagg)typerKrOmatplotlib.backendsripython_inline_display)r#rs r& _repr_html_zFigure._repr_html_ s4 tDKK(11 1 :!88> > 2r(Tc|jj td |jjjy#t$r/}|r#t j t|Yd}~yYd}~yd}~wwxYw)a If using a GUI backend with pyplot, display the figure window. If the figure was not created using `~.pyplot.figure`, it will lack a `~.backend_bases.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. Use cases for `.Figure.show` include running this from a GUI application (where there is persistently an event loop running) or from a shell, like IPython, that install an input hook to allow the interactive shell to accept input while the figure is also being shown and interactive. Some, but not all, GUI toolkits will register an input hook on import. See :ref:`cp_integration` for more details. If you're in a shell without input hook integration or executing a python script, you should use `matplotlib.pyplot.show` with ``block=True`` instead, which takes care of starting and running the event loop for you. Parameters ---------- warn : bool, default: True 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. NzYFigure.show works only for figures managed by pyplot, normally created by pyplot.figure())rKmanagerAttributeErrorshowrrrr,)r#warnexcs r&rz Figure.show soD ;;   & 67 7 - KK   $ $ & -""3s8,, -s$A B A;;Bc6|jjS)as 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 `~Figure.add_axes`, `~.Figure.add_subplot` or `~.Figure.delaxes` to add or remove an Axes. Note: The `.Figure.axes` property and `~.Figure.get_axes` method are equivalent. )r.r4r1s r&rz Figure.axes s}}$$&&r(cHt|dr |jStd)z5The figure id, used to identify figures in `.pyplot`._numberze'Figure' object has no attribute 'number'. In the future thiswill change to returning 'None' instead.)r{rrr1s r&numberz Figure.number s* 4 #<<  ;< t|jtS)z=Return whether `.Figure.tight_layout` is called when drawing.)rrrr1s r&get_tight_layoutzFigure.get_tight_layout< s$0024EFFr(z3.6r) alternativependingc|tjd}t|rdnd}t|tr|ni}|j |fi|d|_y)a Set whether and how `.Figure.tight_layout` is 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 `.Figure.tight_layout` upon drawing. If ``None``, use :rc:`figure.autolayout` instead. If a dict, pass it as kwargs to `.Figure.tight_layout`, overriding the default paddings. NrrrHTrrr-rr<rr")r#r_tight_tight_parameterss r&set_tight_layoutzFigure.set_tight_layout@ sS =LL!45E KV%/t%t|jtSrn)rrrr1s r&rozFigure.get_constrained_layoutU s $0024KLLr(z set_layout_engine('constrained')c|tjd}t|rdnd}t|tr|ni}|j |fi|d|_y)a Set whether ``constrained_layout`` is used upon drawing. If None, :rc:`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 ---------- constrained : bool or dict or None NrrrHTr)r#r _constrained _parameterss r&set_constrained_layoutzFigure.set_constrained_layout] sS"  ,,'FGK(,[(9}v %/ T%Bk |;{; r(z figure.get_layout_engine().set()c t|jtr!|jjdi|yy)aS Set padding for ``constrained_layout``. Tip: The parameters can be passed from a dictionary by using ``fig.set_constrained_layout(**pad_dict)``. See :ref:`constrainedlayout_guide`. Parameters ---------- w_pad : float, default: :rc:`figure.constrained_layout.w_pad` 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 : float, default: :rc:`figure.constrained_layout.h_pad` Height padding in inches. Defaults to 3 pts. wspace : float, default: :rc:`figure.constrained_layout.wspace` Width padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being w_pad + wspace. hspace : float, default: :rc:`figure.constrained_layout.hspace` Height padding between subplots, expressed as a fraction of the subplot width. The total padding ends up being h_pad + hspace. NrS)rrrrj)r#rks r&set_constrained_layout_padsz"Figure.set_constrained_layout_padsu s:> d,,.0G H (D " " $ ( ( 26 2 Ir(zfig.get_layout_engine().get()c<t|jtsy|jj}|d}|d}|d}|d}|rD||@|j }|j }||z|j z }||z|jz }||||fS)a Get padding for ``constrained_layout``. Returns a list of ``w_pad, h_pad`` in inches and ``wspace`` and ``hspace`` as fractions of the subplot. All values are None if ``constrained_layout`` is not used. See :ref:`constrainedlayout_guide`. Parameters ---------- relative : bool If `True`, then convert from inches to figure relative. )NNNNw_padh_padrr)rrrrrrXrr) r#rqrrrrrr|rXs r&rrz"Figure.get_constrained_layout_pads s"$0024KL)%%'++-W W hh *e.?))+H,,CCK(..0ECK(//1EeVV++r(c||_y)z~ Set the canvas that contains the figure Parameters ---------- canvas : FigureCanvas N)rK)r#rKs r& set_canvaszFigure.set_canvas s  r() colorizerc  | rQ|j} |jd|jdfDcgc]}|| z  }}|j|dtj|f||| ||| d| }t |_|j||j||&|j| |||j|||jj||jj|_d|_|Scc}w)ai Add a non-resampled image to the figure. The image is attached to the lower or upper left corner depending on *origin*. Parameters ---------- X The image data. This is an array of one of the following shapes: - (M, N): an image with scalar data. Color-mapping is controlled by *cmap*, *norm*, *vmin*, and *vmax*. - (M, N, 3): an image with RGB values (0-1 float or 0-255 int). - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int), i.e. including transparency. xo, yo : int The *x*/*y* image offset in pixels. alpha : None or float The alpha blending value. %(cmap_doc)s This parameter is ignored if *X* is RGB(A). %(norm_doc)s This parameter is ignored if *X* is RGB(A). %(vmin_vmax_doc)s This parameter is ignored if *X* is RGB(A). origin : {'upper', 'lower'}, default: :rc:`image.origin` Indicates where the [0, 0] index of the array is in the upper left or lower left corner of the Axes. resize : bool If *True*, resize the figure to match the given image size. %(colorizer_doc)s This parameter is ignored if *X* is RGB(A). Returns ------- `matplotlib.image.FigureImage` Other Parameters ---------------- **kwargs Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`. Notes ----- figimage complements the Axes image (`~matplotlib.axes.Axes.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 `~matplotlib.axes.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() rrTr)cmapnormroffsetxoffsetyorigin)vminvmax)r\rrr| FigureImager'r1 set_array set_alpha_check_exclusionary_keywordsset_climrfr r9r r")r#XxoyoalpharrrrrresizerrkrXrWrrs r&figimagezFigure.figimage sZ ,,.C)*QWWQZ(@A1q3wAGA  $ 7   94d*3(*B'-92893 Q U <  + +IDt + L KKd # 2 KK..  #Bs Dc||\}}tj||g}tj|jr|dkj rt d|||j _|rG|jj}|/|j||jzjtd|_y)aH Set the figure size in inches. Call signatures:: fig.set_size_inches(w, h) # OR fig.set_size_inches((w, h)) Parameters ---------- w : (float, float) or float Width and height in inches (if height not specified as a separate argument) or width. h : float Height in inches. forward : bool, default: True If ``True``, the canvas size is automatically updated, e.g., you can resize the figure window from the shell. See Also -------- matplotlib.figure.Figure.get_size_inches matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_figheight Notes ----- To transform from pixels to inches divide by `Figure.dpi`. NrrT)rrrrrr;rrcrKrrrXastyper+r")r#rrrrrs r&rzFigure.set_size_inches$ s< 9DAqxxA{{4 $$&4!8..*:GvNO O" kk))G" 8 8 => r(cTtj|jjS)a Return the current size of the figure in inches. Returns ------- ndarray The size (width, height) of the figure in inches. See Also -------- matplotlib.figure.Figure.set_size_inches matplotlib.figure.Figure.get_figwidth matplotlib.figure.Figure.get_figheight Notes ----- The size in pixels can be obtained by multiplying with `Figure.dpi`. )rrrrcr1s r&rzFigure.get_size_inchesN s&xx((++,,r(c.|jjS)z"Return the figure width in inches.)rrr1s r& get_figwidthzFigure.get_figwidthc s%%%r(c.|jjS)z#Return the figure height in inches.)rrr1s r& get_figheightzFigure.get_figheightg s&&&r(c|jS)z2Return the resolution in dots per inch as a float.)rXr1s r&r\zFigure.get_dpik s xxr(c ||_d|_y)z Set the resolution of the figure in dots-per-inch. Parameters ---------- val : float TN)rXr"r^s r&r_zFigure.set_dpio s r(cH|j||j|y)a0 Set the width of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figheight matplotlib.figure.Figure.set_size_inches rN)rrr#r$rs r& set_figwidthzFigure.set_figwidthz s" S$"4"4"6Hr(cH|j|j||y)a0 Set the height of the figure in inches. Parameters ---------- val : float forward : bool See `set_size_inches`. See Also -------- matplotlib.figure.Figure.set_figwidth matplotlib.figure.Figure.set_size_inches rN)rrr s r& set_figheightzFigure.set_figheight s" T..0#wGr(cxt|||jj}||j yy)Nr])rZr_rKtoolbarrK)r#r^rrls r&r_z Figure.clear s7  ^ 4++%%   NN  r(cp|jsy|j5|j|} |jd|j |j r0|j |j j||jj|tj||||j|jdd|_t!d|j"|j%dddy#t$rYwxYw#d|_wxYw#1swYyxYw)Nr#rwF draw_event)r _render_lockrryrzrrexecuter;rxr{r|r}rir~r"r rK_processrs r&r{z Figure.draw s!     F,,X6G ###H$,,.#A99!7!7!9!E..088>  )44dGT-C-CE$$X." lDKK : C C E) F F&# % F FsGD,=D /DAD ,D, DD DD  D))D,,D5ct|}|j5|j|dddy#1swYyxYw)z 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). N)r_draw_disabledr{rs r&draw_without_renderingzFigure.draw_without_rendering s; !&  $ $ & IIh    s 7AcV|j|jjy)z* Draw `.Artist` *a* only. N)r{rKrr7s r& draw_artistzFigure.draw_artist s t{{'')*r(c&t|}|jd|jd|d|d<tj |d<ddlm}|jj|jjjvrd|d<|S) NrK _original_dpir__mpl_version__r)_pylab_helpersT_restore_to_pylab) rZrIr6rr __version__ matplotlibrrKrGcffigsrH)r#rLrrls r&rIzFigure.__getstate__ s$&  ( /5=Af $'??  . ;;  ."4"4"9"9"@"@"B B)-E% & r(c|jd}|jdd}|tjk7r*tjd|dtjd||_t ||r{ddlm}ddl m }|j}|rt|dznd}|j}|j||} |jj!| |j#d |_y) Nrr Fz.This figure was saved with matplotlib version z and loaded with z so may not function correctly.rrT)r6rr!rr__dict__r matplotlib.pyplotpyplotmatplotlib._pylab_helpersr get_fignumsrC_get_backend_modnew_figure_manager_given_figurer#_set_new_active_managerdraw_if_interactiver") r#rLversionrestore_to_pylabplt pylab_helpersallnumsrbackendmgrs r&rNzFigure.__setstate__ s))-. 99%8%@ coo %   @ J"//NP     + =oo'G&-#g,"1C**,G99#tDC    5 5c :  # # % r(cD|jjdfdy)z>Whenever the Axes state change, ``func(self)`` will be called.rHc|Sr,rS)r$funcs r&ruz'Figure.add_axobserver.. s DIr(N)rIr)r#r8s `r&add_axobserverzFigure.add_axobserver s !!"68MNr() transparentc |jdtjd|tjd}t5}|rbfdfd|jdd|jd d|jD] }|| |j D] }|| |j j|fi|dddy#1swYyxYw) a Save the current figure as an image or vector graphic to a file. Call signature:: savefig(fname, *, transparent=None, 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. Parameters ---------- fname : str or path-like or binary file-like 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 :rc:`savefig.format` and the appropriate extension is appended to *fname*. Other Parameters ---------------- transparent : bool, default: :rc:`savefig.transparent` 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. dpi : float or 'figure', default: :rc:`savefig.dpi` The resolution in dots per inch. If 'figure', use the figure's dpi value. format : str The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this is unset is documented under *fname*. metadata : dict, optional Key/value pairs to store in the image metadata. The supported keys and defaults depend on the image format and backend: - 'png' with Agg backend: See the parameter ``metadata`` of `~.FigureCanvasAgg.print_png`. - 'pdf' with pdf backend: See the parameter ``metadata`` of `~.backend_pdf.PdfPages`. - 'svg' with svg backend: See the parameter ``metadata`` of `~.FigureCanvasSVG.print_svg`. - 'eps' and 'ps' with PS backend: Only 'Creator' is supported. Not supported for 'pgf', 'raw', and 'rgba' as those formats do not support embedding metadata. Does not currently support 'jpg', 'tiff', or 'webp', but may include embedding EXIF metadata in the future. bbox_inches : str or `.Bbox`, default: :rc:`savefig.bbox` 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. pad_inches : float or 'layout', default: :rc:`savefig.pad_inches` Amount of padding in inches around the figure when bbox_inches is 'tight'. If 'layout' use the padding from the constrained or compressed layout engine; ignored if one of those engines is not in use. facecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.facecolor` The facecolor of the figure. If 'auto', use the current figure facecolor. edgecolor : :mpltype:`color` or 'auto', default: :rc:`savefig.edgecolor` The edgecolor of the figure. If 'auto', use the current figure edgecolor. backend : str, optional 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 :ref:`the-builtin-backends` for a list of valid backends for each file format. Custom backends can be referenced as "module://...". orientation : {'landscape', 'portrait'} Currently only supported by the postscript backend. papertype : str One of 'letter', 'legal', 'executive', 'ledger', 'a0' through 'a10', 'b0' through 'b10'. Only supported for postscript output. bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional A list of extra artists that will be considered when the tight bbox is calculated. pil_kwargs : dict, optional Additional keyword arguments that are passed to `PIL.Image.Image.save` when saving the figure. rXz savefig.dpiNzsavefig.transparentc |j|jjdd|jD].}|j|jjdd0|jD] }|| yNrH)rErF) enter_contextrx_cm_setrrh) exit_stackrar} sub_subfig$_recursively_make_subfig_transparents r&rBz._recursively_make_subfig_transparent s,, ,,&,-@A%kkE"00HH,,*0F-DEE'-nn4 <& 44r(c |j|jjdd|jD].}|j|jjdd0|jD] }|| yr=)r>rxr? child_axes)r@r}child_ax child_childax"_recursively_make_axes_transparents r&rGz:Figure.savefig.._recursively_make_axes_transparent s,,((6V(LN$&MME"00$NN22*0F3DEE*,7 :& 77r(rErHrF)rrrrrhrrK print_figure) r#fnamer:rkstackrar}rGrBs @@r&savefigzFigure.savefig sn %m!<=  ,,'<=K [! 6E 4 7!!+v6!!+v6"llHF8GH))BB6ubAB $DKK $ $U 5f 5C! 6! 6! 6s BCCrr7c g g fd}tjddg|| D]}|jjj  S)a Blocking call to interact with a figure. Wait until the user clicks *n* times on the figure, and return the coordinates of each click in a list. There are three possible interactions: - Add a point. - Remove the most recently added point. - Stop the interaction and return the points added so far. The actions are assigned to mouse buttons via the arguments *mouse_add*, *mouse_pop* and *mouse_stop*. Parameters ---------- n : int, default: 1 Number of mouse clicks to accumulate. If negative, accumulate clicks until the input is terminated manually. timeout : float, default: 30 seconds Number of seconds to wait before timing out. If zero or negative will never time out. show_clicks : bool, default: True If True, show a red cross at the location of each click. mouse_add : `.MouseButton` or None, default: `.MouseButton.LEFT` Mouse button used to add points. mouse_pop : `.MouseButton` or None, default: `.MouseButton.RIGHT` Mouse button used to remove the most recently added point. mouse_stop : `.MouseButton` or None, default: `.MouseButton.MIDDLE` Mouse button used to stop input. Returns ------- 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. c |jdk(}|jdk(}|r|jk(s|r*|jdvr jj ny|r|jk(s|r^|jdvrPrUj  rBj j  jjn|r|jk(s|r|j|jr݉j|j|jftjdt|j|j rtj j#|jg|jgdd}|jj%|j| jjt k(r! d kDr jj yyy) Nrr)escapeenter) backspacedeletezinput %i: %f, %f+r)markerrr)rbuttonrArKstop_event_loopr6r9r{inaxesr xdataydatarrrrrcLine2Dadd_line) event is_buttonis_keylineclicksmarks mouse_add mouse_pop mouse_stopnr# show_clickss r&handlerzFigure.ginput..handler s &::IZZ#44Fellj8%))/B"B ++- 9 -D DJJL" **, ((* 9 5<<MM5;; "<=II0!&k5;; E""yy//  }7:# 0 G --d3 T* ((*6{aAE ++-%*r(rr)rblocking_input_loopr9rKr{) r#rdtimeoutrerarbrcrfmarkr_r`s `` ```` @@r&ginputz Figure.ginput skb . .D ++ '):;Wg O D KKM   r(cpdfd}tjddg||dSjdk(S)a 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*. Nc>|jjyr,)rKrU)evr[r#s r&rfz*Figure.waitforbuttonpress..handlersE KK ' ' )r(rr)rrgr)r#rhrfr[s` @r&waitforbuttonpresszFigure.waitforbuttonpresssK * ++ '):;Wg O}tI%**8I*IIr(gHzG?rvrrrc0t||||} |j}|j||j||+t |tt fst jd|jdy#|jdwxYw)a 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. Parameters ---------- pad : float, default: 1.08 Padding between the figure edge and the edges of subplots, as a fraction of the font size. h_pad, w_pad : float, default: *pad* Padding (height/width) between edges of adjacent subplots, as a fraction of the font size. rect : tuple (left, bottom, right, top), default: (0, 0, 1, 1) A rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. See Also -------- .Figure.set_layout_engine .pyplot.tight_layout roNz&The figure layout has changed to tightrH)rrrrrrrr)r#rvrrrrprevious_engines r&rzFigure.tight_layouts8#s%u4P +"446O  " "6 * NN4 *:"35L!M4""#KL  " "6 *D " "6 *s ABB)NNr,)Tr8) rrNNNNNNF)NT))@rOrPrQrR threadingRLockrrrr2rrrrrrr9rrrrrrrrrXrr deprecatedrrorrrrrrr?rrrrrr\r_r rr_r r r{rrrIrNr9rKrLEFTRIGHTMIDDLErjrnrrArBs@r&rrx sp4#9??$L7 | !"$(||%&AIF#?*-X ' 'yyH <<* ]]' 4" 8X+M NCGT__U(;!##&MT__U(J!##,T__ >33>T__U(G!#,#,>BF;@___B(T-*&' I"H"FF6 + (6O -1\6|"$$))$**%,,^@J(#'d$T&+&+r(rct|dxrtj| }tjd}tjd}|r|jdd\}}||z }n|}t j dd}tj||z |f}|tdg||z z}|tdg||z z}tj|||}|S) a Calculate the width and height for a figure with a specified aspect ratio. While the height is taken from :rc:`figure.figsize`, 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. Parameters ---------- arg : float or 2D array 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. Returns ------- size : (2,) array The width and height of the figure in inches. Notes ----- If you want to create an Axes within the figure, that still preserves the aspect ratio, be sure to create it with equal width and height. See examples below. Thanks to Fernando Perez for this function. Examples -------- Make a figure twice as tall as it is wide:: w, h = figaspect(2.) fig = Figure(figsize=(w, h)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.imshow(A, **kwargs) Make a figure with the proper aspect for an array:: A = rand(5, 3) w, h = figaspect(A) fig = Figure(figsize=(w, h)) ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) ax.imshow(A, **kwargs) r)g@g@)0@rzNrrg?) r{risscalarrrrrrrCr) r$isarray figsize_min figsize_maxnrnc arr_ratio fig_heightnewsizes r& figaspectrAs`c7#rs8!NN::NN "! 7$( 44w" -6-6`m -m -`A N NNb E+ZE+E+P&Mr(