
    \cg*                       d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	Z	ddl
ZddlZddlmZmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZ ddlmZ ddlmZ ddl m!Z" ddl#m$Z% ddl&m'Z' dd	l(m)Z)m*Z* dd
l+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;  ejx                  e=      Z>d Z? G d d      Z@ G d de      ZAej                   G d deA             ZCej                   G d deA             ZDd ZEy)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)Artistallow_rasterization_finalize_rasterization)	DrawEventFigureCanvasBaseNonGuiExceptionMouseButton_get_renderer)Axes)GridSpecSubplotParams)ConstrainedLayoutEngineTightLayoutEngineLayoutEnginePlaceHolderLayoutEngine)	Rectangle)Text)Affine2DBboxBboxTransformToTransformedBboxc                 <    | j                  d      x}||_        y y )NFroot)
get_figurestale)selfvalfigs      L/var/www/html/bid-api/venv/lib/python3.12/site-packages/matplotlib/figure.py_stale_figure_callbackr'   A   s$    E**7	 8    c                   @    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
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).
    c                 D    i | _         t        j                         | _        y N)_axes	itertoolscount_counterr#   s    r&   __init__z_AxesStack.__init__O   s    
!)r(   c                     g | j                   S )z1List the Axes that have been added to the figure.)r-   r1   s    r&   as_listz_AxesStack.as_listS   s    }r(   c                 :    | j                   j                  |       y)zRemove the Axes from the stack.N)r-   popr#   as     r&   removez_AxesStack.removeW   s    

qr(   c                 z    || j                   vrt        d      t        | j                        | j                   |<   y)z@Move an Axes, which must already exist in the stack, to the top.zAxes has not been added yetN)r-   
ValueErrornextr0   r7   s     r&   bubblez_AxesStack.bubble[   s0    DJJ:;;T]]+

1r(   c                 f    || j                   vr#t        | j                        | j                   |<   yy)z9Add an Axes to the stack, ignoring it if already present.N)r-   r<   r0   r7   s     r&   addz_AxesStack.adda   s)    DJJ /DJJqM r(   c                 Z    t        | j                  | j                  j                  d      S )z6Return the active Axes, or None if the stack is empty.N)keydefault)maxr-   __getitem__r1   s    r&   currentz_AxesStack.currentf   s    4::4::#9#94HHr(   c                 j    i t        |       dt        | j                  j                         d      iS )Nr0   r   )rB   )varsrC   r-   valuesr1   s    r&   __getstate__z_AxesStack.__getstate__j   s6    
4j
DJJ--/;
 	
r(   c                     |j                  d      }t        |       j                  |       t        j                  |      | _        y )Nr0   )r6   rG   updater.   r/   r0   )r#   statenext_counters      r&   __setstate__z_AxesStack.__setstate__p   s2    yy,T
% !5r(   N)__name__
__module____qualname____doc__r2   r4   r9   r=   r?   rE   rI   rN    r(   r&   r*   r*   F   s0    *,0
I
6r(   r*   c            	           e Zd ZdZ fdZd Z	 dPdZd ZdQdZd Z	 e
 ej                  ed	
      e	d      Zd ZdQdZd Z ej$                  dddddd       ej&                  e      d               Zd Z ej$                  dddddd       ej&                  e      d               Zd Z ej$                  ddd d!dd       ej&                  e      d"               Zd# Zd$ Zd% Zd& Zd' Zd( Zd) Zd* Z d+ Z! e
ee!      Z"dRd-Z#ejH                  d.        Z%ejH                  d/        Z&d0 Z'dSd,d,d	ddddd1d2Z(d3 Z)d4 Z*dRd5Z+dRd6Z,ejH                  d7        Z-ejH                  dQd8       Z.ejH                  	 dTd9       Z/	 	 dUd:Z0dQd;Z1dQd<Z2dQd=Z3dQd>Z4dSd?Z5	 	 	 dVd@Z6dA Z7dB Z8dC Z9dD Z:dd,ddEdFZ;dG Z<dQddHdIZ=e>dJ        Z?e>dK        Z@d,d,dddLddddMdNZAdO ZB xZCS )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        j                         t        j                         t        j                         d| _        g | _	        g | _
        g | _        g | _        g | _        g | _        g | _        g | _        d| _        d | _         | j&                  di | y )N)xytitleTrS   )superr2   r-   	_suptitle
_supxlabel
_supylabelcbookGrouper_align_label_groups
_localaxesartistslinespatchestextsimageslegendssubfigsr"   suppressCompositeset)r#   kwargs	__class__s     r&   r2   zFigureBase.__init__{   s    
 J ]]_$
  


!%6r(   c                    | j                         }|j                  | j                         t        d |D        d       }| j                  D ]|  }|j                         }|j                  |r	 |||      nd       |j                         D ];  }t        |d      s|j                         }|j                  |r	 |||      nd       = ~ |S )zAlso runs apply_aspectc              3   B   K   | ]  }|j                         r|  y wr,   )get_animated).0artists     r&   	<genexpr>z/FigureBase._get_draw_artists.<locals>.<genexpr>   s     G'1D1D1FV's   c                 "    | j                         S r,   )
get_zorder)rq   s    r&   <lambda>z.FigureBase._get_draw_artists.<locals>.<lambda>   s    v002r(   )rA   Napply_aspect)get_childrenr9   patchsortedra   get_axes_locatorrv   hasattr)r#   rendererrb   axlocatorchilds         r&   _get_draw_artistszFigureBase._get_draw_artists   s    ##%tzz"G'G24 //B))+GOOWGB1$G*5.1#446G&&4;x0G +	 " r(   c                    t        j                  g d|       | j                  D cg c]  }|j                  dk7  s| }}t	        d |D              }t        |      dk(  rG| j                  d   j                  |      D ]$  }|j                  |       |j                  |       & n|r|D ]  }|j                         j                         r:|j                  |      D ]$  }|j                  |       |j                  |       & [|j                  |      D ]  }|j                  d        |j                  d        | j                         }	|r |	|	j                  r| j                  |
       d| _        y	c c}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.
        )majorminorboth)whichz
<colorbar>c              3   <   K   | ]  }|j                           y wr,   )get_subplotspec)rp   r}   s     r&   rr   z+FigureBase.autofmt_xdate.<locals>.<genexpr>   s     >2",,.s      r   F N)bottomT)_apicheck_in_listaxes_labelalllenget_xticklabelsset_haset_rotationr   is_last_rowset_visible
set_xlabelget_layout_engineadjust_compatiblesubplots_adjustr"   )
r#   r   rotationhar   r}   r   allsubplotslabelengines
             r&   autofmt_xdatezFigureBase.autofmt_xdate   sW   * 	5UC!YYDYr"))|*CYD>>>t9>155E5BR ""8, C B))+779%'%7%7e%7%DE!LL,!..x8 &E &(%7%7e%7%DE!--e4 &Eb)  '')FNf.F.F   /
+ Es
   E>E>c                     | j                   g| j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  S )z.Get a list of artists contained in the figure.)	rx   rb   ra   rc   rd   re   rf   rg   rh   r1   s    r&   rw   zFigureBase.get_children   s    

   	
     	r(   Nc                     | j                   | u r| S | j                  | j                   u r| j                  S |d}t        j                  d|       d}|r| j                   S | j                  S )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.10messageT)_root_figure_parentr   warn_deprecated)r#   r    r   s      r&   r!   zFigureBase.get_figure   sq     $K<<4,,, <<<.G
   9D$$$||r(   c                 n    d}|| j                   u rt        j                  d| d       yt        |      )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.r   z= From Matplotlib 3.12 this operation will raise an exception.r   N)r   r   r   r;   )r#   r%   	no_switchs      r&   
set_figurezFigureBase.set_figure  sG    <	$###  %; ') )+ ##r(   Tr   zTThe root `Figure`.  To get the parent of a `SubFigure`, use the `get_figure` method.docc                     | j                  |      rdi fS | j                  j                  |j                  |j                        }|i fS )z|
        Test whether the mouse event occurred on the figure.

        Returns
        -------
            bool, {}
        F)_different_canvasbboxcontainsrW   rX   )r#   
mouseeventinsides      r&   r   zFigureBase.contains%  sD     !!*-"9##JLL*,,?rzr(   c                     | j                   S r,   r   r#   r|   s     r&   get_window_extentzFigureBase.get_window_extent2  s    yyr(   c                    |j                  dd      }|j                  dd      }|d   dv r|du }n|d   dk(  r|du }||d   }||d   }t        j                  |t              }|j	                  d	|d
          |j	                  d|d          |j	                  d|d          d|vrL|j	                  dt
        j                  |d             |j	                  dt
        j                  |d             t        | |d         }|7|j                  |       |j                  ||f        |j                  di | n% | j                  |||fi |}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.
        rW   NrX   name)r\   r[   r]   x0y0horizontalalignmentr   verticalalignmentvar   fontpropertiesfontsizesize
fontweightweightTrS   )r6   r^   normalize_kwargsr   
setdefaultmplrcParamsgetattrset_textset_positionrj   textsetattr_autoposr"   )r#   tinfork   rW   rX   autopossuplabs           r&   
_suplabelszFigureBase._suplabels6  s   R JJsD!JJsD!<664iG&\\)4iG9T
A9T
A''5/d<-tDz:*d:&676)j#,,tF|*DElCLLh,HItF|,OOAA'FJJ  TYYq!Q1&1FD$v,/!
r(         ?\(\?zsuper titlecentertoprY   )r   r   r   r   r   rcc           	      @    ddddddddd	} | j                   ||fi |S )
Nr[   r   r   r   r   r   zfigure.titlesizezfigure.titleweightr   r   r   r   r   r   r   r   r   r#   r   rk   r   s       r&   suptitlezFigureBase.suptitle  s:    
 $3de*6JL tq$1&11r(   c                 B    | j                   }|dS |j                         S )z<Return the suptitle as string or an empty string if not set.r   )r[   get_textr#   text_objs     r&   get_suptitlezFigureBase.get_suptitle  s$    >>%r>8+<+<+>>r(   {Gz?zsuper xlabelr   r   c           	      @    ddddddddd	} | j                   ||fi |S )
Nr\   r   r   r   r   r   figure.labelsizefigure.labelweightr   r   r   s       r&   	supxlabelzFigureBase.supxlabel  s:    
 %CthA*6JL tq$1&11r(   c                 B    | j                   }|dS |j                         S )z=Return the supxlabel as string or an empty string if not set.r   )r\   r   r   s     r&   get_supxlabelzFigureBase.get_supxlabel  $    ??%r>8+<+<+>>r(   {Gz?zsuper ylabelleftc           
      B    ddddddddd	d
	} | j                   ||fi |S )Nr]   r   r   r   r   verticalanchorr   r   )	r   r   r   r   r   r   rotation_moder   r   r   r   s       r&   	supylabelzFigureBase.supylabel  s<    
 %DH*!)3E.0 tq$1&11r(   c                 B    | j                   }|dS |j                         S )z=Return the supylabel as string or an empty string if not set.r   )r]   r   r   s     r&   get_supylabelzFigureBase.get_supylabel  r   r(   c                 6    | j                   j                         S )z+Get the edge color of the Figure rectangle.)rx   get_edgecolorr1   s    r&   r   zFigureBase.get_edgecolor      zz''))r(   c                 6    | j                   j                         S )z+Get the face color of the Figure rectangle.)rx   get_facecolorr1   s    r&   r   zFigureBase.get_facecolor  r   r(   c                 6    | j                   j                         S )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_visibler1   s    r&   get_frameonzFigureBase.get_frameon  s     zz%%''r(   c                 :    | j                   j                  |       y)z
        Set the line width of the Figure rectangle.

        Parameters
        ----------
        linewidth : number
        N)rx   set_linewidth)r#   	linewidths     r&   r   zFigureBase.set_linewidth  s     	

  +r(   c                 6    | j                   j                         S )z=
        Get the line width of the Figure rectangle.
        )rx   get_linewidthr1   s    r&   r   zFigureBase.get_linewidth  s     zz''))r(   c                 :    | j                   j                  |       y)z
        Set the edge color of the Figure rectangle.

        Parameters
        ----------
        color : :mpltype:`color`
        N)rx   set_edgecolorr#   colors     r&   r   zFigureBase.set_edgecolor       	

  'r(   c                 :    | j                   j                  |       y)z
        Set the face color of the Figure rectangle.

        Parameters
        ----------
        color : :mpltype:`color`
        N)rx   set_facecolorr  s     r&   r  zFigureBase.set_facecolor  r  r(   c                 H    | j                   j                  |       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)rx   r   r"   )r#   bs     r&   set_frameonzFigureBase.set_frameon  s     	

q!
r(   Fc                 R   |j                  |        | j                  j                  |       | j                  j                  |_        |j                         s|j                  | j                         |r+|j                         |j                  | j                         d| _        |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)r   rb   appendr9   _remove_methodis_transform_setset_transformtransSubfigureget_clip_pathset_clip_pathrx   r"   )r#   rq   clips      r&   
add_artistzFigureBase.add_artist  s    , 	$F# $ 3 3&&(  !4!45F((*2  ,
r(   c                 B   t        |      sd|vrt        d      d|v r(t        |      rt        d      |j                  d      f}t        |      dk7  r t        j                  ddt        |            t        |d   t              r/|\  }|j                  }|j                  d      | urct        d	      |\  }t        j                  |      j                         st        d
|        | j                  di |\  }} || |fi |}||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'r   add_axesr   Fr   5The Axes must have been created in the present figurez'all entries in rect must be finite not rS   )r   	TypeErrorr6   r   nargs_error
isinstancer   _projection_initr!   r;   npisfiniter    _process_projection_requirements_add_axes_internal)r#   argsrk   r8   rA   r  projection_classpkws           r&   r  zFigureBase.add_axes  s0   l 4yV61WXXv4y TUUJJv&)Dt9>"":q#d)<<d1gt$BA$$C|||'t3 KM M ED;;t$((* #J4&!QRR$ID$I$I$SF$S!c !t3s3A#S)C&&q#..r(   c           	      ^   d|v rt        j                  dd      t        |      dk(  rtt        |d   t        j
                  j                  j                        rC|d   j                         r0|d   }|j                  }|j                  d      | urt        d      |sd}t        |      dk(  rIt        |d   t              r6d	|d   cxk  rd
k  r(n n%t        t        t        t!        |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_subplotr   r   Fr   r  )r   r   r   d   i  rS   )r   kwarg_errorr   r  r   r   _base	_AxesBaser   r  r!   r;   r   tuplemapintstrr  r  )r#   r  rk   r}   rA   r   r!  s          r&   r$  zFigureBase.add_subplot  s,   J v ""=(;;INtAw(@(@AG++-aB%%C}}%}(4  "6 7 7   D	Q:d1gx#@tAw-#-Sc$q'l34$ID$I$I$SF$S!c!$555B#S)C&&r3//r(   c                    | j                   j                  |       || j                  vr| j                  j                  |       | j	                  |       | j
                  |_        ||_        d| _        t        |_
        |S )z0Private helper for `add_axes` and `add_subplot`.T)_axstackr?   ra   r
  scadelaxesr  r  r"   r'   stale_callback)r#   r}   rA   s      r&   r  zFigureBase._add_axes_internal  se    "T__$OO""2& LL!
2	r(   )sharexshareysqueezewidth_ratiosheight_ratios
subplot_kwgridspec_kwc                    t        |	xs i       }	|d|	v rt        d      ||	d<   |d|	v rt        d      ||	d<    | j                  ||fd| 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)
        r6  Q'height_ratios' must not be defined both as parameter and as key in 'gridspec_kw'r5  P'width_ratios' must not be defined both as parameter and as key in 'gridspec_kw'r#  )r2  r3  r4  r7  )dictr;   add_gridspecsubplots)r#   nrowsncolsr2  r3  r4  r5  r6  r7  r8  gsaxss               r&   r>  zFigureBase.subplots  s    r ;,"-$+-  "I J J+8K(#,  "I J J*6K'TueHDHKHkk%/  1
r(   c                 V    | j                  || j                  | j                  g       y)zY
        Remove the `~.axes.Axes` *ax* from the figure; update the current Axes.
        )ownersN)_remove_axesr.  ra   r#   r}   s     r&   r0  zFigureBase.delaxes  s$     	"dmmT__%EFr(   c                    |D ]  }|j                  |        | j                  j                  d|        d| _        | j                  j
                  j                  |       |j                  D ]  }|j                  |   }|j                  |      D cg c]	  }||us| }}|s8|j                  |       |d   j                  |   }|j                         j                  |       |j                         j                  |       |j                         j                  |       |j                         j                  |        |j                   j                  |       yc c}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_eventTr   N)r9   _axobserversprocessr"   r   canvasrelease_mouse_axis_names_shared_axesget_siblings	_axis_mapget_major_formatterset_axisget_major_locatorget_minor_formatterget_minor_locator_twinned_axes)	r#   r}   rD  ownerr   grouperothersiblingsremaining_axiss	            r&   rE  zFigureBase._remove_axes  s8    ELL  	!!"6=
  ..r2NNDood+G+2+?+?+CW+C%uTV+CHWNN2 &a[2248N..099.I,,.77G..099.I,,.77G # 	# Xs   	E"E"c                    d| _         | j                  D ]  }|j                  |        g | _        t        | j                        D ]#  }|j                          | j                  |       % g | _        g | _        g | _        g | _	        g | _
        g | _        |st        j                         | _        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.
        Nkeep_observersT)ri   rh   clearr)  r   r0  rb   rc   rd   re   rf   rg   r^   CallbackRegistryrI  r[   r\   r]   r"   )r#   r^  subfigr}   s       r&   r_  zFigureBase.clear  s     "& llFLLL7 #		"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&   clfzFigureBase.clf  s     zzz88r(   c                 6   t        j                  | j                  g|i |\  }}}|j                  d| j                         t        j
                  | ||fi |}| 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_argsr   r   r  Legendrg   r
  r9   r  r"   )r#   r  rk   handleslabelsls         r&   legendzFigureBase.legend  s    ^ #*"<"<TYY"X"XQW"X*D,?,?@NN4&;F;A<<..
r(   c                    d| j                   i||ni |}t        d|||d|}|j                  |        t        |_        | j
                  j                  |       | j
                  j                  |_        d| _	        |S )a  
        Add text to figure.

        Parameters
        ----------
        x, y : float
            The position to place the text. By default, this is in figure
            coordinates, floats in [0, 1]. The coordinate system can be changed
            using the *transform* keyword.

        s : str
            The text string.

        fontdict : dict, optional
            A dictionary to override the default text properties. If not given,
            the defaults are determined by :rc:`font.*`. Properties passed as
            *kwargs* override the corresponding ones given in *fontdict*.

        Returns
        -------
        `~.text.Text`

        Other Parameters
        ----------------
        **kwargs : `~matplotlib.text.Text` properties
            Other miscellaneous text parameters.

            %(Text:kwdoc)s

        See Also
        --------
        .Axes.text
        .pyplot.text
        	transform)rW   rX   r   TrS   )
r  r   r   r'   r1  re   r
  r9   r  r"   )r#   rW   rX   sfontdictrk   effective_kwargsr   s           r&   r   zFigureBase.textw  s    J ,,
#/xR
 

 9a119(894

$"jj//
r(   c           
      $   |t        |dd      }|8|t        d      t        |t        j                        rg |j
                  nt        j                  |      rg |n|gd   j                  d      }|j                         }|j                         |j                         j                  sd}|rXt        |t        j                  j                  j                        r*|j                         rt!        j"                  |fi |\  }}nt!        j$                  |fi |\  }}|j'                  |       |j)                  ddd       t+        |d	      rZ|j                  d
      x}F|| j,                  ur8t/        j0                  dt3        |       dt3        | j,                         d       g d}	t!        j4                  ||fi |j7                         D 
ci c]  \  }
}|
|	vs|
| c}}
}d
|j                  d      _        |S c c}}
w )aP  
        Add a colorbar to a plot.

        Parameters
        ----------
        mappable
            The `matplotlib.cm.ScalarMappable` (i.e., `.AxesImage`,
            `.ContourSet`, etc.) described by this colorbar.  This argument is
            mandatory for the `.Figure.colorbar` method but optional for the
            `.pyplot.colorbar` function, which sets the default to the current
            image.

            Note that one can create a `.ScalarMappable` "on-the-fly" to
            generate colorbars not attached to a previously drawn artist, e.g.
            ::

                fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)

        cax : `~matplotlib.axes.Axes`, optional
            Axes into which the colorbar will be drawn.  If `None`, then a new
            Axes is created and the space for it will be stolen from the Axes(s)
            specified in *ax*.

        ax : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of Axes, optional
            The one or more parent Axes from which space for a new colorbar Axes
            will be stolen. This parameter is only used if *cax* is not set.

            Defaults to the Axes that contains the mappable used to create the
            colorbar.

        use_gridspec : bool, optional
            If *cax* is ``None``, a new *cax* is created as an instance of
            Axes.  If *ax* is positioned with a subplotspec and *use_gridspec*
            is ``True``, then *cax* is also positioned with a subplotspec.

        Returns
        -------
        colorbar : `~matplotlib.colorbar.Colorbar`

        Other Parameters
        ----------------
        %(_make_axes_kw_doc)s
        %(_colormap_kw_doc)s

        Notes
        -----
        If *mappable* is a `~.contour.ContourSet`, its *extend* kwarg is
        included automatically.

        The *shrink* kwarg provides a simple way to scale the colorbar with
        respect to the Axes. Note that if *cax* is specified, it determines the
        size of the colorbar, and *shrink* and *aspect* are ignored.

        For more precise control, you can manually specify the positions of the
        axes objects in which the mappable and the colorbar are drawn.  In this
        case, do not use any of the Axes properties kwargs.

        It is known that some vector graphics viewers (svg and pdf) render
        white gaps between segments of the colorbar.  This is due to bugs in
        the viewers, not Matplotlib.  As a workaround, the colorbar can be
        rendered with overlapping segments::

            cbar = colorbar()
            cbar.solids.set_edgecolor("face")
            draw()

        However, this has negative consequences in other circumstances, e.g.
        with semi-transparent images (alpha < 1) and colorbar extensions;
        therefore, this workaround is not used by default (see issue #1188).

        Nr   zUnable to determine Axes to steal space for Colorbar. Either provide the *cax* argument to use as the Axes for the Colorbar, provide the *ax* argument to steal space from it, or add *mappable* to an Axes.r   Fr   r   )visibler   axisr!   Tz&Adding colorbar to a different Figure z than z! which fig.colorbar is called on.)fractionpadshrinkaspectr   panchor)r   r;   r  r  ndarrayflatiterabler!   gcar   colorbar_gridspecr   r   r'  r(  r   cbarmake_axes_gridspec	make_axesr/  gridr{   r   r   warn_externalreprColorbaritemsr"   )r#   mappablecaxr}   use_gridspecrk   r%   
current_axmappable_host_figNON_COLORBAR_KEYSkvcbs                r&   colorbarzFigureBase.colorbar  s   V :640B;z => > )RZZ8
"''
 kk"oUrUT1 )jej4  J%%'3--/AA$"2sxx~~'?'?@**,"55bCFCV"nnR:6:VGGJHHU&vH>Hl+&.&9&9t&9&DD"Q (9(99""@ 1236 1 123 4567H]]3 L#\\^-K+TQq8I/IAqD^-K L+/E"(	-Ks   H(Hc                 r   | j                         0| j                         j                  st        j                  d       y| j                  j                  ||||||       | j                  D ]A  }|j                         |j                  |j                         j                  |              C d| _
        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)r   r   r   r  subplotparsrK   r   r   _set_positionget_positionr"   )r#   r   r   rightr   wspacehspacer}   s           r&   r   zFigureBase.subplots_adjust!  s    > ""$0**,>>/0 feS&&I))B!!#/  !3!3!5!B!B4!HI  
r(   c                    || j                   }t        j                  |      D cg c]  }|j                         | }}|D ]  }t        j                  d|j                                |j                         j                  }|j                  j                         }|D ]  }|j                  j                         |k(  s!|j                         j                  }|dk(  r|j                  |j                  k(  s |dk(  s_|j                  |j                  k(  sy| j                  d   j                  ||         yc c}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: %sr   r   rW   )r   r  ravelr   _logdebug
get_xlabelrowspanxaxisget_label_positionstartstopr`   join)r#   rB  r}   r  posaxcrowspancs          r&   align_xlabelszFigureBase.align_xlabelsM  s   T ;))CHHSMNMbR-?-?-A-MrMNBJJ("--/:((*22G((--/C 99//1S8"224<<Hu(..)H8O0M005::2sC   O
   D>D>c                    || j                   }t        j                  |      D cg c]  }|j                         | }}|D ]  }t        j                  d|j                                |j                         j                  }|j                  j                         }|D ]  }|j                  j                         |k(  s!|j                         j                  }|dk(  r|j                  |j                  k(  s |dk(  s_|j                  |j                  k(  sy| j                  d   j                  ||         yc c}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()
        Nr  r   r  rX   )r   r  r  r   r  r  
get_ylabelcolspanyaxisr  r  r  r`   r  )r#   rB  r}   r  r  r  colspancs          r&   align_ylabelszFigureBase.align_ylabels  s   R ;))CHHSMNMbR-?-?-A-MrMNBJJ("--/:((*22G((--/C 99//1S8"224<<Hv'--8>>*I7Nw||x}}/L005::2sC   Or  c                    || j                   }t        j                  |      D cg c]  }|j                         | }}|D ]  }t        j                  d|j                                |j                         j                  }|D ]U  }|j                         j                  }|j                  |j                  k(  s7| j                  d   j                  ||       W  yc c}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()
        Nr  rY   )r   r  r  r   r  r  	get_titler  r  r`   r  )r#   rB  r}   r  r  r  s         r&   align_titleszFigureBase.align_titles  s    H ;))CHHSMNMbR-?-?-A-MrMNBJJ(",,.9((*22G..088MMX^^3,,W5::2sC   Os
   C"C"c                 L    | 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.
        )rB  N)r  r  )r#   rB  s     r&   align_labelszFigureBase.align_labels  s&    4 	s#s#r(   c                 H    |j                  dd      }t        d||| 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   )r6   r   )r#   r?  r@  rk   _rA  s         r&   r=  zFigureBase.add_gridspec  s0    V JJx&FEtFvF	r(   c                 H   t        ||| ||||dddd      }	t        j                  ||ft              }
t	        |      D ]/  }t	        |      D ]  } | j
                  |	||f   fi ||
||f<   ! 1 | j                         p||l|	j                  |       \  }}}}t        |
||      D ]F  \  }}}t        |||      D ]0  \  }}}t        j                  ||||      }|j                  |       2 H |r/|
j                  dk(  r|
j                         S |
j                         S |
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.
        r   r   )r?  r@  r#  r  r  r5  r6  r   r  r   r   dtyper   )r   r  emptyobjectrangeadd_subfigurer   get_grid_positionszipr   from_extents_redo_transform_rel_figr   itemr4  )r#   r?  r@  r4  r  r  r5  r6  rk   rA  sfarrijbottomstopsleftsrightssfrowr   r   sfr   r  r   s                           r&   
subfigureszFigureBase.subfiguresC  sD   P Et#F#/$1AaQ	8 %v6uA5\0d00AqDDVDad "  !!#+1C171C ,.+@+@+F(GT5&&)%$&?"vs'*5%'@OBe,,T65#FD..D.9 (A '@
  $)::?5::<GG Lr(   c                     t        | |fi |}| xj                  |gz  c_        | j                  j                  |_        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)	SubFigurerh   r9   r  r'   r1  r"   )r#   subplotspecrk   r  s       r&   r  zFigureBase.add_subfigure  sK    . t[3F3 LL//2
	r(   c                 t    | j                   j                  |       | j                  j                  d|        |S )z.Set the current Axes to be *a* and return *a*.rH  )r.  r=   rI  rJ  r7   s     r&   r/  zFigureBase.sca  s0    Q!!"6=r(   c                 ^    | j                   j                         }||S | j                         S )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.  rE   r$  rF  s     r&   r}  zFigureBase.gca  s.     ]]""$^r;)9)9);;r(   c                     | j                   j                         }|y|j                         }||S t        | j                        D ]  }|j                         }||c S  y)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   _gcireversedr   )r#   r}   ims      r&   r  zFigureBase._gci  sb    $ ]]""$:WWY>I 499%BB~	 & r(   )
axes_classpolar
projectionc                F   ||s|t        d      |}||fS |r||dk7  rt        d| d|d      d}t        |t              s|t        j                  |      }||fS t        |d      r)|j                         \  }} |j                  di | ||fS t        d|      )	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'r  zpolar=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;   r  r,  r   get_projection_classr{   r  rK   r  )r#   r  r  r  rk   r   extra_kwargss          r&   r  z+FigureBase._process_projection_requirements  s    !
. MO O)(  ''# )jG.C$ '8 GJ J  %
*c*j.@#.#C#CJ#O   '' ^41;1H1H1J. ,--
  ''  00:~?@ @r(   c                    | j                         D cg c]$  }|j                         r|j                         r|& }}| j                  D ]2  }|j                         s|j	                  |j                                4 |S c c}w )zU
        Return a list of Artists typically used in `.Figure.get_tightbbox`.
        )rw   r   get_in_layoutr   extendget_default_bbox_extra_artists)r#   rq   bbox_artistsr}   s       r&   r  z)FigureBase.get_default_bbox_extra_artists  s     .2->->-@ N-@6"..0V5I5I5K -@ N))B~~##B$E$E$GH  Ns   )Bbbox_extra_artistsc                   | | j                  d      j                         }g }|L| j                         D cg c]2  }|| j                  vr"|j	                         r|j                         r|4 }}n|}|D ]'  }|j                  |      }||j                  |       ) | j                  D ]8  }|j	                         s	 |j                  ||      }|j                  |       : |D 	cg c]`  }	t        j                  |	j                        r?t        j                  |	j                        r |	j                  dk7  s|	j                  dk7  r|	b }}	t        | d      }
t        |      dk(  r|
r| j                  S | j                   g}t#        j$                  |      }|
r$t'        || j(                  j+                               }|S c c}w # t        $ r |j                  |      }Y w xY wc c}	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).
        Tr   r  r   bbox_inches)r!   r   rw   r   r   r  get_tightbboxr
  r  r  r  widthheightr{   r   r  r   r   unionr   dpi_scale_transinverted)r#   r|   r  bbrq   rb   r8   r   r}   r  isfigure_bboxs               r&   r  zFigureBase.get_tightbbox  s   6 D1??AH%,0,=,=,? 8,?&!2v7I7I7K%335 ,?G 8 )GA??8,D		$ 
 ))B~~6++ 5G , ID 		$   8A++agg&2;;qxx+@ww!|qxx1}  8 4/r7a<''' ii[

2#E4+?+?+H+H+JKEO8$ ! 6++H5D68s   7GG
,A%G+
G('G(c                     i }| j                         D ]M  \  }}t        |t              r |D ]  }||v rt        d|d      |||<    6||v rt        d|d      |||<   O |S )NzThe key z appears multiple times.)r  r  r)  r;   )per_subplot_kwexpandedr  r  sub_keys        r&   _norm_per_subplot_kwzFigureBase._norm_per_subplot_kwQ  s    "((*DAq!U# G(*(8G;>V)WXX()HW%  !
 =$xu4L%MNN + r(   c                    d| vr(| j                  d      D cg c]  }t        |       c}S t        j                  |       } | j	                  d      j                  d      D cg c]  }t        |       c}S c c}w c c}w )N
;)splitlistinspectcleandocstrip)layoutlns     r&   _normalize_grid_stringz!FigureBase._normalize_grid_string`  sz    v'-||C'89'8DH'899 %%f-F'-||D'9'?'?'EF'EDH'EFF	 : Gs   A9$A>.)r2  r3  r5  r6  empty_sentinelr7  r  r8  c                    xs i t        |	xs i       }	xs i |d|	v rt        d      ||	d<   |d|	v rt        d      ||	d<   t        |t              r> j	                  |      }j                         D 
ci c]  \  }
}t        |
      | c}}
 j                        t        j                  t        ||       d fd fd |      }|j                  \  }}  j                  ||fi |	} ||g |       }t        t        |j                                     }|j                         D ]M  }|r#|j!                  |       |j#                  d	
       |s+|j%                  |       |j'                  d	
       O t)              t)        |      z
  x}rt        d| d      |S c c}}
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.

        r6  r:  r5  r;  )r2  r3  c                    | ^}}t        |t              rt        d      t        |d      D ]d  \  }}t        |t              rt        d      t	        |      t	        |      k7  s9t        d|dt	        |       d| d|dt	        |       d       t        j                  t	        |       t	        |      ft        	      }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   )r  z@All of the rows must be the same length, however the first row (z) has length z	 and row z (r  r  )r  r,  r;   	enumerater   r  zerosr  )inpr0restr  routr  r  s           r&   _make_arrayz.FigureBase.subplot_mosaic.<locals>._make_array  s     IB"c" !GHH!$a01a%$%KLLr7c!f$$**,}SWI F##$#RuM#a&D 	 1 ((CHc"g.f=C!#1%aLDAq !C1I ) ' Jr(   c                 
   t        j                         }i }t        |       D ]R  \  }}t        |      D ]?  \  }}|k(  rt        j                  |      s |      |||f<   /|j	                  |       A T t        |      |fS )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^   _OrderedSetr  is_scalar_or_stringr?   r)  )	mosaic
unique_idsnestedr  rowr  r  r	  r  s	          r&   _identify_keys_and_nestedz<FigureBase.subplot_mosaic.<locals>._identify_keys_and_nested  s     **,JF#F+3%cNDAqN* "66q9)4Q1v"q) + , $f,,r(   c           
         t               }t               }|D ]  }t        j                  ||k(        }t        j                  |d      \  }}	t        j                  |d      dz   \  }
}t        ||
      t        |	|      f}||   |k7  j                         rt        d|d|d      ||df|||	f<    |j                         D ]  \  \  }}}d|d	f|||f<    t        |      D ]  }||   \  }}}|dk(  rR|}||v rt        d
| d|       j                  | |   fi dt        |      ij                  |i       }|||<   c|d	k(  rz|}|\  }}|j                  \  }} | ||f   j                  ||      |g |       }t        |      t        |      z  }|rt        d
| 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   )rt  r   zWhile trying to layout
z
we found that the label z4 specifies a non-rectangular or non-contiguous area.r   Nr  zThere are duplicate keys z in the layout
r   z between the outer layout
z
and the nested layout
zThis should never happen)r<  r  argwhereminrC   sliceanyr;   r  ry   r$  r,  getshapesubgridspecrj   rK   RuntimeError)rA  r  r  r  output
this_levelr   indx	start_row	start_colend_rowend_colslcr  r  nested_mosaicrA   argmethodr}   rowscolsnested_outputoverlap
_do_layoutr  r  r#   r7  s                           r&   r*  z-FigureBase.subplot_mosaic.<locals>._do_layout-  s{   & VF J #{{6T>2')vvd';$	9#%66$Q#7!#; Y0%	72KL3K4',,.$26* =337( ;BBC C
 7;C5H
Iy12 #$ *0%A&*M8%D
Aq6" *8
 j)$.sO!c6 V#Cv~(+DTF K;;A**F G G)))3#SY$($ -00r:$B $&F4Lx'$'MDAq!.!4!4JD$$.1a4,,T48%% 3=A%M
 "&kC,>>G(7y A99?
 C66C_F 
 MM-0&'ABBM *N Mr(   T)skip_non_rectangular_axesz	The keys z/ are in *per_subplot_kw* but not in the mosaic.)r<  r;   r  r,  r  r  r)  r  r   check_isinstanceboolr  r=  r<   iterrH   r2  _label_outer_xaxisr3  _label_outer_yaxisrj   )r#   r  r2  r3  r5  r6  r  r7  r  r8  r  r  r&  r'  rA  retax0r}   extrar*  r  r	  s   `     ```          @@@r&   subplot_mosaiczFigureBase.subplot_mosaicj  s   \  %2
;,"-'-2$+-  "I J J+8K(#,  "I J J*6K' fc"008F(6(<(<(>(>1a!(>N 22>B 	d6&A	<	-8]	 ]	~ V$\\
dTtT9[9VH&?&GH4

%&**,B		#%%%E		#%%%E  '#c(2252E7 #) )  
gs   Gc                 |    || k7  r|j                  |        t        |_        |j                  | j                         y r,   )r   r'   r1  r  r  r7   s     r&   _set_artist_propszFigureBase._set_artist_props  s/    9LL1	++,r(   )g?   r  r   r,   F)r   r   )NNT)NNNNNN)r   r   TNNNN)DrO   rP   rQ   rR   r2   r   r   rw   r!   r   property	functoolspartialr#  r   r   r   r   Substitutioncopyr   r   r   r   r   r   r   r   r   r   r   r   r  r  frameonr  interpdr  r$  r  r>  r0  rE  r_  rc  rl  r   r  r   r  r  r  r  r=  r  r  r/  r}  r  r  r  r  staticmethodr  r  r4  r6  __classcell__rl   s   @r&   rU   rU   v   s   B( >E+Z
%N$$ 'i''
>
:<FGR Z=X %'3Z__Z 2 !32?
 Z>h (W6Z__Z 2 !62?
 Z>f (W6Z__Z 2 !62?
**(,*(( {K0G!F n/ n/` }0 }0~H5D dHTG"$H!H9, u un / /b <@u un GK,0*X<D|;Dz-D^$:-^ 48'+48CJ<<B >B48!(F	G GR   G G 05U$(&)"&tsj	-r(   rU   c                        e Zd ZdZddddd fd
Zed        Zed        Zej                  d        Zd	 Z	d
 Z
d ZddZd ZddZd Zed        Zej"                  Zd Z xZS )r  a  
    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	edgecolorr   r>  c                4   t        |   d	i | |d}|t        j                  d   }|t        j                  d   }|| _        || _        |j                  | _        |j                  | _        |j                  | _        |j                  | _	        |j                  | _
        |j                  | _        t        j                         | _        | j                          | j
                  j                   | _        t#        | j                  | j
                  j$                        | _        t)        | j&                        | _        t+        ddd||||d| j$                  	      | _        | j/                  | j,                         | j,                  j1                  d       y)
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
        Nnonefigure.edgecolorfigure.frameonr   r   r   F)	xyr  r  rs  rE  rF  r   	in_layoutrn  rS   )rZ   r2   r   r   _subplotspecr   r   r.  r  r  rI  transFigurer   nullbbox_relativer  figbboxr   r  r   r   r   rx   r6  set_antialiased)	r#   parentr  rE  rF  r   r>  rk   rl   s	           r&   r2   zSubFigure.__init__  sW   H 	"6"I%78I?ll#34G'"// !--%55"//!--!YY[$$&||++#D$6$6$(LL$?$?A	-dii8Qq'9	t':':	<

 	tzz*

""5)r(   c                 .    | j                   j                  S r,   )r   rK  r1   s    r&   rK  zSubFigure.canvas  s    ||"""r(   c                 .    | j                   j                  S r,   r   dpir1   s    r&   rX  zSubFigure.dpi	  s    ||r(   c                 &    || j                   _        y r,   rW  )r#   values     r&   rX  zSubFigure.dpi	  s     r(   c                 .    | j                   j                  S )zY
        Return the resolution of the parent figure in dots-per-inch as a float.
        rW  r1   s    r&   get_dpizSubFigure.get_dpi	  s     ||r(   c                 4    || j                   _        d| _        y)z
        Set the resolution of parent figure in dots-per-inch.

        Parameters
        ----------
        val : float
        TN)r   rX  r"   r#   r$   s     r&   set_dpizSubFigure.set_dpi	  s     
r(   c                 6    | j                   j                         S r,   )r   r   r1   s    r&   r   zSubFigure._get_renderer	  s    ||))++r(   c                 |   |7|j                   | j                  _         |j                  | j                  _        y| j                  j	                         }t        j                  |j                               }t        j                  |j                               }|| j                  j                     j                         |j                         z  }|| j                  j                     j                         |j                         z  }|d| j                  j                  j                   j                         |j                         z  }d|d| j                  j                  j                   j                         |j                         z  z
  }||f| j                  _         ||z   ||z   f| 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   )p0rQ  p1rN  get_gridspecr  asarrayget_width_ratiosget_height_ratiosr  sumr  r  r  )	r#   r   rA  wrhrdxdyr   r   s	            r&   r  z!SubFigure._redo_transform_rel_fig	  s_    $(GGD!$(GGD!++-ZZ++-.ZZ,,./!!))*..02668;!!))*..02668;0""**001557"&&(B3T&&..33488:RVVXEE!#R!#b"r' 2r(   c                 6    | j                   j                         S zo
        Return whether constrained layout is being used.

        See :ref:`constrainedlayout_guide`.
        )r   get_constrained_layoutr1   s    r&   ro  z SubFigure.get_constrained_layout8	  s     ||2244r(   c                 :    | j                   j                  |      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)r   get_constrained_layout_pads)r#   rq  s     r&   rr  z%SubFigure.get_constrained_layout_pads@	  s     ||777JJr(   c                 6    | j                   j                         S r,   )r   r   r1   s    r&   r   zSubFigure.get_layout_engineP	  s    ||--//r(   c                      | j                   dd S )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)ra   r1   s    r&   r   zSubFigure.axesS	  s     q!!r(   c                 n   | j                         sy | j                  |      }	 |j                  d| j                                | j                  j                  |       t        j                  || || j                  d      j                         |j                  d       d| _        y # d| _        w xY w)N	subfiguregidTr   F)r   r   
open_groupget_gidrx   drawmimage_draw_list_compositing_imagesr!   ri   close_groupr"   r#   r|   rb   s      r&   r{  zSubFigure.drawd	  s     !((2	@JJOOH%00$d)C)U)UW  - DJDJs   A?B+ +	B4r,   r8  )rO   rP   rQ   rR   r2   r9  rK  rX  setterr\  r_  r   r  ro  rr  r   r   fgetget_axesr{  rA  rB  s   @r&   r  r    s    &  	C*J # #     	ZZ! ! 	,325K 0 " " yyHr(   r  c            
       ,    e Zd ZdZ ej
                         Zd Zd Z	 	 d>ddddddddd fdZ	 fdZ
d	 Zd?d
Zd Zd Zd@dZed        Zej$                  Zed        Zej*                  d        Zd Zd Zd@dZ eeed      Zd Z ej8                  ddd      d        Zd Z ej8                  ddd      d        Z ej8                  ddd      d         Z  ej8                  dd!d      dAd"       Z!d# Z"e#jH                  	 	 dBdd$d%       Z%dCd&Z&d' Z'd( Z(d) Z)d* Z*d+ Z+d@d,Z,d@d-Z-dA fd.	Z.e/e0d/               Z1d0 Z2d1 Z3 fd2Z4d3 Z5d4 Z6dd5d6Z7d7d8de8jr                  e8jt                  e8jv                  fd9Z<dDd:Z=d;dddd<d=Z> xZ?S )EFigurea  
    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.
    c                 F    dt        | j                  j                        z  S )NzFigure(%gx%g))r)  r   r   r1   s    r&   __str__zFigure.__str__	  s    tyy~~!666r(   c                     dj                  | j                  j                  | j                  j                  d   | j                  j                  d   t        | j                              S )Nz.<{clsname} size {h:g}x{w:g} with {naxes} Axes>r   r   )clsnamehwnaxes)formatrl   rO   r   r   r   r   r1   s    r&   __repr__zFigure.__repr__	  sR    ?FFNN++iinnQ499>>!#4dii. G 
 	
r(   NrD  )rE  rF  r   r>  r  tight_layoutconstrained_layoutr  c          
      P   t        |   di | | | _        d| _        |
A|t	        j
                  d       |	t	        j
                  d       | j                  |
       n|Z|	t	        j
                  d       | j                  d       t        |t              r | j                         j                  di | nl|	Xt        |	t              r3| j                  d        | j                         j                  di |	 n'|	r%| j                  d       n| j                  |
       t        j                  t        j                        | _        | j                  j                   } |d	t"        j$                         |d
t"        j$                         |d
t"        j$                         |dt"        j&                         |dt"        j&                         |dt"        j&                         |dt"        j&                        g| _         |d| j*                        | _         |d| j*                        | _        |t0        j2                  d   }|t0        j2                  d   }|t0        j2                  d   }|t0        j2                  d   }|t0        j2                  d   }t5        j6                  |      j9                         r&t5        j:                  |      dk  j=                         rt?        d|       tA        jB                  ddg| | _"        tG               jI                  |      | _%        || _&        tO        | jD                  | jJ                        | _(        | jP                  | _)        tU        | jP                        | _+        | jV                  | _,        t[        ddd||||d      | _.        | j_                  | j\                         | j\                  ja                  d       t        |        |
tc               }|| _2        tg               | _4        | jk                          y)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.)r  ztThe Figure parameters 'tight_layout' and 'constrained_layout' cannot be used together. Please use 'layout' parametertightconstrained)signalskey_press_eventkey_release_eventbutton_press_eventbutton_release_eventscroll_eventmotion_notify_eventfigure.figsizez
figure.dpizfigure.facecolorrI  rJ  r   (figure size must be positive finite not rK  r   F)rL  r  r  rs  rE  rF  r   rM  rS   )6rZ   r2   r   _layout_enginer   r  set_layout_enginer  r<  r   rj   r^   r`  r   events_canvas_callbacks_connect_picklabler   _key_handler_mouse_handler_mouse_key_idspick_button_pick_id_scroll_pick_idr   r   r  r  r   arrayr  r;   r   from_boundsr  r   scaler  _dpir   r   rR  r   rO  r  r   rx   r6  rS  r   r  r*   r.  r_  )r#   figsizerX  rE  rF  r   r>  r  r  r  r  rk   connectrl   s                r&   r2   zFigure.__init__	  s   @ 	"6" "(""BC #.""IJ ""&"1%!-"")* ""'"2,-,&&(,,<|<+,d3&&m&<,&&(,,B/AB#&&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
  '';TYYG&~tyyA?ll#34G;,,|,C%78I%78I?ll#34G{{7#'')bhhw.?!.C-H-H-JG 'y* + +++Aq;7;'z//4	#D$4$4d6J6JK	yy*4995"..Qq'9		

 	tzz*

""5)'/K&"

r(   c                 n    | j                   j                  j                         st        |   |       y y r,   )rK  
widgetlocklockedrZ   r  )r#   r   rl   s     r&   r  zFigure.pick^
  s*    {{%%,,.GL$ /r(   c                     ||y|j                   |j                   k(  ry| j                  D ]  }t        |d      s y y)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~  r   r{   )r#   oldnewr}   s       r&   _check_layout_engines_compatz#Figure._check_layout_engines_compatb
  sI     ;#+  C$9$99 ))Br;'  r(   c                 
   |4t         j                  d   rd}nt         j                  d   rd}nd| _        y|dk(  rt        di |}n|dk(  rt	        di |}n}|dk(  rt	        dddi|}nj|d	k(  rD| j                  5t        | j                  j                  | j                  j                        }n$d}n!t        |t              r|}nt        d
|      | j                  | j                  |      r|| _        yt        d      )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.

        Nfigure.autolayoutr  figure.constrained_layout.user  
compressedcompressTrH  zInvalid value for 'layout': zzColorbar layout of new layout engine not compatible with old engine, and a colorbar has been created.  Engine not changed.rS   )r   r   r  r   r   r   r   r~  r  r   r;   r  r  )r#   r  rk   new_layout_engines       r&   r  zFigure.set_layout_engineu
  s(   > >||/0 =>&&*#W 1 ;F ;}$ 7 A& A|# 7 !B !B:@!Bv"".$;''99''99%!
 %)!- &;F:FGG,,T-@-@->@"3D  H I Ir(   c                     | j                   S r,   )r  r1   s    r&   r   zFigure.get_layout_engine
  s    """r(   c                 t    dt        | j                        j                  v rddlm} |j                  |       S y )NWebAggr   )backend_webagg)typerK  rO   matplotlib.backendsr  ipython_inline_display)r#   r  s     r&   _repr_html_zFigure._repr_html_
  s4     tDKK(111:!88>> 2r(   Tc                    | j                   j                  t        d      	 | j                   j                  j                          y# t        $ r/}|r#t        j                  t        |             Y d}~yY d}~yd}~ww xY w)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())rK  managerAttributeErrorshowr   r   r  r,  )r#   warnexcs      r&   r  zFigure.show
  so    D ;;& 67 7	-KK$$& 	-""3s8,, 	-s   $A 	B  A;;B c                 6    | j                   j                         S )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.  r4   r1   s    r&   r   zFigure.axes
  s     }}$$&&r(   c                 H    t        | d      r| j                  S t        d      )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{   r  r  r1   s    r&   numberzFigure.number  s*     4#<< ;< <r(   c                 @    t        j                  dd       || _        y )Nr   zcChanging 'Figure.number' is deprecated since %(since)s and will raise an error starting %(removal)sr   )r   r   r  )r#   nums     r&   r  zFigure.number  s"    ?	@ r(   c                 x    t        | j                  d      r| j                  j                         S t        |       S )Nget_renderer)r{   rK  r  r   r1   s    r&   r   zFigure._get_renderer   s.    4;;/;;++-- &&r(   c                     | j                   S r,   )r  r1   s    r&   _get_dpizFigure._get_dpi&  s    yyr(   c                     || j                   k(  ry|| _         | j                  j                         j                  |       | j	                         \  }}| j                  |||       y)z
        Parameters
        ----------
        dpi : float

        forward : bool
            Passed on to `~.Figure.set_size_inches`
        Nforward)r  r  r_  r  get_size_inchesset_size_inches)r#   rX  r  r  r  s        r&   _set_dpizFigure._set_dpi)  s^     $))	""$**3/##%1Q73r(   z The resolution in dots per inch.r   c                 >    t        | j                         t              S )z=Return whether `.Figure.tight_layout` is called when drawing.)r  r   r   r1   s    r&   get_tight_layoutzFigure.get_tight_layout<  s    $0024EFFr(   z3.6r  )alternativependingc                     |t         j                  d   }t        |      rdnd}t        |t              r|ni } | j
                  |fi | 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.
        Nr  r  rH  Tr   r   r-  r  r<  r  r"   )r#   r  _tight_tight_parameterss       r&   set_tight_layoutzFigure.set_tight_layout@  sS     =LL!45E KV%/t%<E"v;):;
r(   c                 >    t        | j                         t              S rn  )r  r   r   r1   s    r&   ro  zFigure.get_constrained_layoutU  s     $0024KLLr(   z set_layout_engine('constrained')c                     |t         j                  d   }t        |      rdnd}t        |t              r|ni } | j
                  |fi | 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
        Nr  r  rH  Tr  )r#   r  _constrained_parameterss       r&   set_constrained_layoutzFigure.set_constrained_layout]  sS    " ,,'FGK(,[(9}v%/T%Bk|;{;
r(   z figure.get_layout_engine().set()c                     t        | j                         t              r! | j                         j                  di | yy)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   )r  r   r   rj   )r#   rk   s     r&   set_constrained_layout_padsz"Figure.set_constrained_layout_padsu  s:    > d,,.0GH(D""$((262 Ir(   zfig.get_layout_engine().get()c                 <   t        | j                         t              sy| j                         j                         }|d   }|d   }|d   }|d   }|rD||@| j	                         }|j
                  }||z  |j                  z  }||z  |j                  z  }||||fS )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.
        )NNNNw_padh_padr  r  )r  r   r   r  r   rX  r  r  )	r#   rq  r   r  r  r  r  r|   rX  s	            r&   rr  z"Figure.get_constrained_layout_pads  s    " $0024KL)%%'++-WWhh*e.?))+H,,CCK(..0ECK(//1EeVV++r(   c                     || _         y)z~
        Set the canvas that contains the figure

        Parameters
        ----------
        canvas : FigureCanvas
        N)rK  )r#   rK  s     r&   
set_canvaszFigure.set_canvas  s     r(   )	colorizerc          
         |
rQ| j                         }|j                  d   |j                  d   fD cg c]  }||z  	 }}| j                  |d       t        j                  | f||||||	d|}t
        |_        |j                  |       |j                  |       |&|j                  |||       |j                  ||       | j                  j                  |       | j                  j                  |_        d| _        |S c c}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()
        r   r   Tr  )cmapnormr  offsetxoffsetyorigin)vminvmax)r\  r  r  r|  FigureImager'   r1  	set_array	set_alpha_check_exclusionary_keywordsset_climrf   r
  r9   r  r"   )r#   Xxoyoalphar  r  r  r  r  resizer  rk   rX  rW   r  r  s                    r&   figimagezFigure.figimage  s   Z ,,.C)*QWWQZ(@A(@1q3w(@GA  $ 7 94d*3(*B'-9 289 3
Q
U<++IDt+LKKd#2 KK..
	# Bs   Dc                    ||\  }}t        j                  ||g      }t        j                  |      j                         r|dk  j	                         rt        d|       || j                  _        |rG| j                  j                  }|/ |j                  || j                  z  j                  t                d| _        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`.
        Nr   r  T)r  r  r  r   r  r;   r  rc  rK  r  r   rX  astyper+  r"   )r#   r  r  r  r   r  s         r&   r  zFigure.set_size_inches$  s    < 9DAqxxA{{4 $$&4!8..*:GvNOO"kk))G" 8 8 =>
r(   c                 T    t        j                  | j                  j                        S )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`.
        )r  r  r  rc  r1   s    r&   r  zFigure.get_size_inchesN  s    & xx((++,,r(   c                 .    | j                   j                  S )z"Return the figure width in inches.)r  r  r1   s    r&   get_figwidthzFigure.get_figwidthc  s    %%%r(   c                 .    | j                   j                  S )z#Return the figure height in inches.)r  r  r1   s    r&   get_figheightzFigure.get_figheightg  s    &&&r(   c                     | j                   S )z2Return the resolution in dots per inch as a float.)rX  r1   s    r&   r\  zFigure.get_dpik  s    xxr(   c                      || _         d| _        y)z
        Set the resolution of the figure in dots-per-inch.

        Parameters
        ----------
        val : float
        TN)rX  r"   r^  s     r&   r_  zFigure.set_dpio  s     
r(   c                 H    | 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
        r  N)r  r  r#   r$   r  s      r&   set_figwidthzFigure.set_figwidthz  s"     	S$"4"4"6Hr(   c                 H    | 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
        r  N)r  r  r  s      r&   set_figheightzFigure.set_figheight  s"     	T..0#wGr(   c                 x    t         |   |       | j                  j                  }||j	                          y y )Nr]  )rZ   r_  rK  toolbarrK   )r#   r^  r  rl   s      r&   r_  zFigure.clear  s7    ^4 ++%%NN r(   c                 p   | j                         sy | j                  5  | j                  |      }	 |j                  d| j	                                | j
                  r0| j                          	 | j                         j                  |        | j                  j                  |       t        j                  || || j                         |j                  d       d| _        t!        d| j"                  |      j%                          d d d        y # t        $ r Y w xY w# d| _        w xY w# 1 sw Y   y xY w)Nr#  rw  F
draw_event)r   _render_lockr   ry  rz  r   r   executer;   rx   r{  r|  r}  ri   r~  r"   r   rK  _processr  s      r&   r{  zFigure.draw  s
    !,,X6G###H$,,.#A99!7!7!9!E..088>
 

)44dGT-C-CE $$X."
lDKK:CCE)  &  #
% sG   D,=D /DAD ,D,	DD DD  	D))D,,D5c                     t        |       }|j                         5  | j                  |       ddd       y# 1 sw Y   yxY w)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{  r   s     r&   draw_without_renderingzFigure.draw_without_rendering  s2    
 !&$$&IIh '&&s	   7A c                 V    |j                  | j                  j                                y)z*
        Draw `.Artist` *a* only.
        N)r{  rK  r  r7   s     r&   draw_artistzFigure.draw_artist  s     	
t{{'')*r(   c                 &   t         |          }|j                  d       |j                  d|d         |d<   t        j
                  |d<   ddlm} | j                  j                  |j                  j                  j                         v rd|d<   |S )	NrK  _original_dpir  __mpl_version__r   )_pylab_helpersT_restore_to_pylab)rZ   rI   r6   r  r   __version__
matplotlibr  rK  r  GcffigsrH   )r#   rL   r  rl   s      r&   rI   zFigure.__getstate__  s    $&
 			( 		/5=Af $'??  	.;;."4"4"9"9"@"@"BB)-E%&r(   c                    |j                  d      }|j                  dd      }|t        j                  k7  r*t        j                  d| dt        j                   d       || _        t        |        |r{dd lm} dd l	m
} |j                         }|rt        |      dz   nd}|j                         }|j                  ||       }	|j                  j!                  |	       |j#                          d	| _        y )
Nr  r   Fz.This figure was saved with matplotlib version z and loaded with z so may not function correctly.r   r   T)r6   r   r!  r   r  __dict__r   matplotlib.pyplotpyplotmatplotlib._pylab_helpersr  get_fignumsrC   _get_backend_modnew_figure_manager_given_figurer#  _set_new_active_managerdraw_if_interactiver"   )
r#   rL   versionrestore_to_pylabpltpylab_helpersallnumsr  backendmgrs
             r&   rN   zFigure.__setstate__  s    ))-. 99%8%@coo%@	 J"//NP  	+=oo'G&-#g,"1C**,G99#tDC55c:##%
r(   c                 D    | j                   j                  dfd       y)z>Whenever the Axes state change, ``func(self)`` will be called.rH  c                      |       S r,   rS   )r$  funcs    r&   ru   z'Figure.add_axobserver.<locals>.<lambda>  s	    DIr(   N)rI  r  )r#   r8  s    `r&   add_axobserverzFigure.add_axobserver   s     	!!"68MNr(   )transparentc                   |j                  dt        j                  d          |t        j                  d   }t               5 }|rbfdfd|j                  dd       |j                  d	d       | j                  D ]  } ||        | j
                  D ]  } ||         | j                  j                  |fi | ddd       y# 1 sw Y   yxY w)
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.

        rX  zsavefig.dpiNzsavefig.transparentc                    | j                  |j                  j                  dd             |j                  D ].  }| j                  |j                  j                  dd             0 |j                  D ]  } | |        y NrH  )rE  rF  )enter_contextrx   _cm_setr   rh   )
exit_stackra  r}   
sub_subfig$_recursively_make_subfig_transparents       r&   rB  z<Figure.savefig.<locals>._recursively_make_subfig_transparent  s    ,,,,&, - @A %kk"00HH,,*0F - DE * '-nn
<&
4 '5r(   c                    | j                  |j                  j                  dd             |j                  D ].  }| j                  |j                  j                  dd             0 |j                  D ]  } | |        y r=  )r>  rx   r?  
child_axes)r@  r}   child_axchild_childax"_recursively_make_axes_transparents       r&   rG  z:Figure.savefig.<locals>._recursively_make_axes_transparent  s    ,,((6V(LN$&MM"00$NN22*0F 3 DE %2 *,:&7 *7r(   rE  rH  rF  )r   r   r   r   rh   r   rK  print_figure)	r#   fnamer:  rk   stackra  r}   rG  rB  s	          @@r&   savefigzFigure.savefig  s    n 	%m!<=,,'<=K[E
4	7 !!+v6!!+v6"llF8G + ))B6ubA $$DKK$$U5f5C [[s   BCCr   r7  c                     	
 g 	g 
	
 fd}t        j                   ddg||       
D ]  }|j                            j                  j	                          	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                    | j                   dk(  }| j                   dk(  }|r| j                  k(  s|r*| j                  dv r
j                  j	                          ny|r| j                  k(  s|r^| j                  dv rPrUj                          rBj                         j                          
j                  j                          n|r| j                  k(  s|r| j                  | j                  r݉j                  | j                  | j                  f       t        j                  dt              | j                  | j                         rt        j                   j#                  | j                  g| j                  gdd      }| j                  j%                  |       j                  |       
j                  j                          t              	k(  r!	d	kD  r
j                  j	                          y y y )
Nr  r  )escapeenter)	backspacedeletezinput %i: %f, %f+r  )markerr  r   )r   buttonrA   rK  stop_event_loopr6   r9   r{  inaxesr
  xdataydatar  r   r   r   rc   Line2Dadd_line)event	is_buttonis_keylineclicksmarks	mouse_add	mouse_pop
mouse_stopnr#   show_clickss       r&   handlerzFigure.ginput.<locals>.handler  s   

&::IZZ#44F ellj8%))/B"B++-	 9		-D DJJL"		**,((*	 9		 5<<MM5;;"<=II0!&k5;;E""yy//}7:#  0  G--d3T*((*6{aAE++- %*r(   r  r  )r   blocking_input_loopr9   rK  r{  )r#   rd  timeoutre  ra  rb  rc  rf  markr_  r`  s   `` ````  @@r&   ginputzFigure.ginput  sf    b  	.  	.D 	++'):;Wg	O DKKM r(   c                 p     d fd}t        j                   ddg||       dS j                  dk(  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                 >    | j                   j                          y r,   )rK  rU  )evr[  r#   s    r&   rf  z*Figure.waitforbuttonpress.<locals>.handler  s    EKK'')r(   r  r  )r   rg  r   )r#   rh  rf  r[  s   `  @r&   waitforbuttonpresszFigure.waitforbuttonpress  sK     	*
 	++'):;Wg	O }tI%**8I*IIr(   gHzG?rv  r  r  r  c                0   t        ||||      }	 | j                         }| j                  |       |j                  |        |+t	        |t         t
        f      st        j                  d       | j                  d       y# | j                  d       w xY w)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
        ro  Nz&The figure layout has changed to tightrH  )r   r   r  r  r  r   r   r  )r#   rv  r  r  r  r   previous_engines          r&   r  zFigure.tight_layout  s    8 #s%u4P		+"446O""6*NN4 *:"35L!M4 ""#KL""6*D""6*s   AB B)NNr,   )Tr8  )	r   r   NNNNNNF)NT))@rO   rP   rQ   rR   	threadingRLockr  r  r  r2   r  r  r  r   r  r  r9  r   r  r  r  r  r   r  r  rX  r  r   
deprecatedr  ro  r  r  rr  r  r   r?  r  r  r  r  r  r\  r_  r  r  r_  r   r
   r{  r  r  rI   rN   r9  rK  r   LEFTRIGHTMIDDLErj  rn  r  rA  rB  s   @r&   r  r  x	  sp   4 #9??$L7
 |  !"$(||%&AIF#?*-X ' ' yyH< <* ]] '4" 8X+M
NCG T__U(;!##&M T__U(J!##, T__	>33> T__U(G!#,#,> BF;@__ _B(T-*&'	I"H" F  F6 +(6O -1 \6| "$$))$**%,,^@J( #'d$T &+ &+r(   r  c                    t        | d      xr t        j                  |        }t        j                  d      }t        j                  d      }|r| j                  dd \  }}||z  }n| }t
        j                  d   d   }t        j                  ||z  |f      }|t        dg||z   z  }|t        dg||z   z  }t        j                  |||      }|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
    -------
    width, height : float
        The figure size 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@rz  N   r  r   g      ?)
r{   r  isscalarr  r  r   r   r  rC   r  )	r$  isarrayfigsize_minfigsize_maxnrnc	arr_ratio
fig_heightnewsizes	            r&   	figaspectr  A  s    ` c7#<BKK,<(<G ((:&K((<(K 2ABG		 ./2J hh
Y.
;<G s31'K/11G s31'K/11G ggg{K8GNr(   )FrR   
contextlibr   r  r.   r:  loggingnumbersr   rs  numpyr  r"  r   r   r   r   r   matplotlib.artistr	   r
   r   matplotlib.backend_basesr   r   r   r   r   matplotlib._apir   matplotlib.cbookr^   matplotlib.colorbarr  r  matplotlib.imageimager|  matplotlib.axesr   matplotlib.gridspecr   r   matplotlib.layout_enginer   r   r   r   matplotlib.legendrl  rf  matplotlib.patchesr   matplotlib.textr   matplotlib.transformsr   r   r   r   	getLoggerrO   r  r'   r*   rU   r?  r  r  r  rS   r(   r&   <module>r     s   8 !         N N: :N N    " !   7  $ (  4 4 w"
-6 -6`m - m -`A N
 N Nb E+Z E+ E+P&Mr(   