B
    ]”t\yu ã               @   sÂ  d Z ddlZddlmZ ddlZddlZddlmZ ddlm	Z	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 dd	lmZmZ dd
lmZ ddlmZ ddlmZ ddlmZm Z m!Z! ddl"m#Z#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/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z9 ddl:m;Z; e <e=¡Z>e
j?j@e-ƒ d dd„ ZAG dd„ deƒZBG dd„ deCƒZDG dd„ deƒZEdd„ ZFe
j?j@e GeE¡d dS ) a5  
The figure module provides the top-level
:class:`~matplotlib.artist.Artist`, the :class:`Figure`, which
contains all the plot elements.  The following classes are defined

:class:`SubplotParams`
    control the default spacing of the subplots

:class:`Figure`
    Top level container for all plot elements.

é    N)ÚIntegral)ÚrcParams)ÚbackendsÚ	docstring)Ú__version__)Úget_backend)ÚArtistÚallow_rasterization)ÚStackÚiterable)Úimage)ÚFigureImage)ÚAxesÚSubplotBaseÚsubplot_class_factory)ÚBlockingMouseInputÚBlockingKeyMouseInput)ÚGridSpec)Ú	Rectangle)Úget_projection_namesÚprocess_projection_requirements)ÚTextÚTextWithDash)ÚAffine2DÚBboxÚBboxTransformToÚTransformedBbox)ÚNonGuiException)Zprojection_namesc             C   s   | j r|| j _d S )N)ÚfigureÚstale)ÚselfÚval© r"   ú0lib/python3.7/site-packages/matplotlib/figure.pyÚ_stale_figure_callback7   s    r$   c               @   s`   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ ZdS )Ú	AxesStacka  
    Specialization of the `.Stack` to handle all tracking of
    `~matplotlib.axes.Axes` in a `.Figure`.
    This stack stores ``key, (ind, axes)`` pairs, where:

        * **key** should be a hash of the args and kwargs
          used in generating the Axes.
        * **ind** is a serial number for tracking the order
          in which axes were added.

    The AxesStack is a callable, where ``ax_stack()`` returns
    the current axes. Alternatively the :meth:`current_key_axes` will
    return the current key and associated axes.

    c             C   s   t  | ¡ d| _d S )Nr   )r
   Ú__init__Ú_ind)r    r"   r"   r#   r&   L   s    
zAxesStack.__init__c             C   s&   dd„ | j D ƒ}| ¡  dd„ |D ƒS )zY
        Return a list of the Axes instances that have been added to the figure.
        c             S   s   g | ]\}}|‘qS r"   r"   )Ú.0ÚkÚar"   r"   r#   ú
<listcomp>T   s    z%AxesStack.as_list.<locals>.<listcomp>c             S   s   g | ]\}}|‘qS r"   r"   )r(   Úir*   r"   r"   r#   r+   V   s    )Ú	_elementsÚsort)r    Zia_listr"   r"   r#   Úas_listP   s    zAxesStack.as_listc             C   s0   t | jƒ |¡}|dkrdS t dd¡ |d S )zr
        Return the Axes instance that was added with *key*.
        If it is not present, return *None*.
        Nz2.1a)  Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.é   )Údictr-   ÚgetÚcbookZwarn_deprecated)r    ÚkeyÚitemr"   r"   r#   r2   X   s    zAxesStack.getc             C   s$   dd„ | j D ƒ| \}}|||ffS )Nc             S   s   i | ]\}\}}||f|“qS r"   r"   )r(   r)   Úindr*   r"   r"   r#   ú
<dictcomp>j   s    z.AxesStack._entry_from_axes.<locals>.<dictcomp>)r-   )r    Úer6   r)   r"   r"   r#   Ú_entry_from_axesi   s    zAxesStack._entry_from_axesc             C   s   t  | |  |¡¡ dS )zRemove the axes from the stack.N)r
   Úremover9   )r    r*   r"   r"   r#   r:   m   s    zAxesStack.removec             C   s   t  | |  |¡¡S )za
        Move the given axes, which must already exist in the
        stack, to the top.
        )r
   Úbubbler9   )r    r*   r"   r"   r#   r;   q   s    zAxesStack.bubblec             C   s¢   t |tƒstd |¡ƒ‚yt|ƒ W n tk
r>   tƒ }Y nX |  |¡}|dk	rrt 	| ||f¡ t
 d |¡¡ || kr~dS |  jd7  _t | || j|ff¡S )zö
        Add Axes *a*, with key *key*, to the stack, and return the stack.

        If *key* is unhashable, replace it by a unique, arbitrary object.

        If *a* is already on the stack, don't add it again, but
        return *None*.
        z%second argument, {!r}, is not an AxesNz0key {!r} already existed; Axes is being replacedr0   )Ú
isinstancer   Ú
ValueErrorÚformatÚhashÚ	TypeErrorÚobjectr2   r
   r:   ÚwarningsÚwarnr'   Úpush)r    r4   r*   Z
a_existingr"   r"   r#   Úaddx   s    

zAxesStack.addc             C   s6   t | jƒs| j| jfS | j| j \}\}}||fS dS )z
        Return a tuple of ``(key, axes)`` for the active axes.

        If no axes exists on the stack, then returns ``(None, None)``.
        N)Úlenr-   Z_defaultZ_pos)r    r4   ÚindexÚaxesr"   r"   r#   Úcurrent_key_axes–   s    
zAxesStack.current_key_axesc             C   s   |   ¡ d S )Nr0   )rI   )r    r"   r"   r#   Ú__call__¢   s    zAxesStack.__call__c             C   s   ||   ¡ kS )N)r/   )r    r*   r"   r"   r#   Ú__contains__¥   s    zAxesStack.__contains__N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r&   r/   r2   r9   r:   r;   rE   rI   rJ   rK   r"   r"   r"   r#   r%   <   s   r%   c               @   s,   e Zd ZdZd	dd„Zd
dd„Zdd„ ZdS )ÚSubplotParamsz7
    A class to hold the parameters for a subplot.
    Nc             C   s   d| _ |  ||||||¡ dS )a  
        All dimensions are fractions of the figure width or height.
        Defaults are given by :rc:`figure.subplot.[name]`.

        Parameters
        ----------
        left : float
            The left side of the subplots of the figure.

        right : float
            The right side of the subplots of the figure.

        bottom : float
            The bottom of the subplots of the figure.

        top : float
            The top of the subplots of the figure.

        wspace : float
            The amount of width reserved for space between subplots,
            expressed as a fraction of the average axis width.

        hspace : float
            The amount of height reserved for space between subplots,
            expressed as a fraction of the average axis height.
        TN)ÚvalidateÚupdate)r    ÚleftÚbottomÚrightÚtopÚwspaceÚhspacer"   r"   r#   r&   ­   s    zSubplotParams.__init__c                sæ   t ˆ ddƒ‰t ˆ ddƒ‰t ˆ ddƒ‰t ˆ ddƒ‰t ˆ ddƒ‰t ˆ ddƒ‰ˆ  d|¡ ˆ  d|¡ ˆ  d|¡ ˆ  d|¡ ˆ  d|¡ ˆ  d|¡ ‡ ‡‡‡‡‡‡fdd	„}ˆ jrâˆ jˆ jkrÈ|ƒ  td
ƒ‚ˆ jˆ jkrâ|ƒ  tdƒ‚dS )zY
        Update the dimensions of the passed parameters. *None* means unchanged.
        rS   NrU   rV   rT   rW   rX   c                  s(   ˆˆ _ ˆˆ _ˆˆ _ˆˆ _ˆˆ _ˆˆ _d S )N)rS   rU   rV   rT   rW   rX   r"   )r    Ú
thisbottomÚ
thishspaceÚthisleftÚ	thisrightÚthistopÚ
thiswspacer"   r#   Úresetß   s    z#SubplotParams.update.<locals>.resetzleft cannot be >= rightzbottom cannot be >= top)ÚgetattrÚ_update_thisrQ   rS   rU   r=   rT   rV   )r    rS   rT   rU   rV   rW   rX   r_   r"   )r    rY   rZ   r[   r\   r]   r^   r#   rR   Ì   s(    zSubplotParams.updatec             C   s<   |d kr,t | |d ƒ}|d kr,d| }t| }t| ||ƒ d S )Nzfigure.subplot.)r`   r   Úsetattr)r    Úsr!   r4   r"   r"   r#   ra   ð   s    zSubplotParams._update_this)NNNNNN)NNNNNN)rL   rM   rN   rO   r&   rR   ra   r"   r"   r"   r#   rP   ©   s    
 
#rP   c            	       sÂ  e Zd ZdZdd„ Zdd„ Zd dd	„Zd
d„ Zd¡dd„Zdd„ Z	e
e	ddZdd„ Zd¢dd„Ze
eeddZdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd£d$d%„Zd¤d)d*„Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd¥d6d7„Zd¦d8d9„Zd:d;„ Zd<d=„ Zd>d?„ Zd@dA„ Z dBdC„ Z!dDdE„ Z"dFdG„ Z#dHdI„ Z$dJdK„ Z%dLdM„ Z&d§dNdO„Z'd¨dPdQ„Z(dRdS„ Z)dTdU„ Z*dVdW„ Z+d©dXdY„Z,e-j.dZd[„ ƒZ/e-j.d\d]„ ƒZ0dªd_d`„Z1dadb„ Z2d«dcdd„Z3d¬dedf„Z4e5dgdh„ ƒZ6didj„ Z7dkdl„ Z8e-j.dmdn„ ƒZ9e-j.d­dodp„ƒZ:dqdr„ Z;e-j.dsdt„ ƒZ<dudv„ Z=dwdx„ Z>‡ fdydz„Z?d{d|„ Z@d}d~„ ZAdddœd€d„ZBe-j.d®d‚dƒ„ƒZCd¯d„d…„ZDd°dˆd‰„ZEd±d‹dŒ„ZFddŽ„ ZGd²dd„ZHd‘d’„ ZId³d“d”„ZJd´d–d—„ZKdµd˜d™„ZLd¶dšd›„ZMd·dœd„ZNdždŸ„ ZO‡  ZPS )¸ÚFigurea¥  
    The top level container for all the plot elements.

    The Figure instance supports callbacks through a *callbacks* attribute
    which is a `.CallbackRegistry` instance.  The events you can connect to
    are 'dpi_changed', and the callback will be called with ``func(fig)`` where
    fig is the `Figure` instance.

    Attributes
    ----------
    patch
        The `.Rectangle` instance representing the figure patch.

    suppressComposite
        For multiple figure images, the figure will make composite images
        depending on the renderer option_image_nocomposite function.  If
        *suppressComposite* is a boolean, this will override the renderer.
    c             C   s   dt | jjƒ S )NzFigure(%gx%g))ÚtupleÚbboxÚsize)r    r"   r"   r#   Ú__str__  s    zFigure.__str__c             C   s,   dj | jj| jjd | jjd t| jƒdS )Nz.<{clsname} size {h:g}x{w:g} with {naxes} Axes>r   r0   )ZclsnameÚhÚwZnaxes)r>   Ú	__class__rL   rf   rg   rF   rH   )r    r"   r"   r#   Ú__repr__  s    zFigure.__repr__Nç        c
       
      C   sj  t  | ¡ | `t ¡ | _|dkr(td }|dkr8td }|dkrHtd }|dkrXtd }|dkrhtd }t |¡ 	¡ s„t
d |¡ƒ‚tjd|žŽ | _tƒ  ||¡| _|| _t| j| jƒ| _|| _t| jƒ| _td	d
d
|||d| _|  | j¡ | j d¡ d| _d| _|dkrtƒ }|| _d| _ |  !|	¡ |  "|¡ t#ƒ | _$|  %¡  d| _&t '¡ | _(t '¡ | _)g | _*dS )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 frame.

        subplotpars : :class:`SubplotParams`
            Subplot parameters. If not given, the default subplot
            parameters :rc:`figure.subplot.*` are used.

        tight_layout : bool or dict, default: :rc:`figure.autolayout`
            If ``False`` use *subplotpars*. If ``True`` adjust subplot
            parameters using `.tight_layout` with default padding.
            When providing a dict containing the keys ``pad``, ``w_pad``,
            ``h_pad``, and ``rect``, the default `.tight_layout` paddings
            will be overridden.

        constrained_layout : bool
            If ``True`` use constrained layout to adjust positioning of plot
            elements.  Like ``tight_layout``, but designed to be more
            flexible.  See
            :doc:`/tutorials/intermediate/constrainedlayout_guide`
            for examples.  (Note: does not work with :meth:`.subplot` or
            :meth:`.subplot2grid`.)
            Defaults to :rc:`figure.constrained_layout.use`.
        Nzfigure.figsizez
figure.dpizfigure.facecolorzfigure.edgecolorzfigure.frameonz!figure size must be finite not {}r   )r   r   r0   )ZxyÚwidthÚheightÚ	facecolorÚ	edgecolorÚ	linewidthF)r   r   )+r   r&   Z_axesr3   ÚCallbackRegistryÚ	callbacksr   ÚnpÚisfiniteÚallr=   r>   r   Zfrom_boundsÚbbox_inchesr   ÚscaleÚdpi_scale_transÚ_dpir   rf   Úframeonr   ÚtransFigurer   ÚpatchÚ_set_artist_propsZset_aaÚcanvasÚ	_suptitlerP   ÚsubplotparsÚ
_layoutboxÚset_constrained_layoutÚset_tight_layoutr%   Ú_axstackÚclfÚ_cachedRendererZGrouperÚ_align_xlabel_grpÚ_align_ylabel_grpÚ
_gridspecs)
r    ÚfigsizeÚdpirp   rq   rr   r|   r‚   Útight_layoutZconstrained_layoutr"   r"   r#   r&     sR    6






zFigure.__init__c             C   s2   | j d k	r.d| j jjkr.ddlm} | | ¡S d S )NZWebAggr   )Úbackend_webagg)r€   rk   rL   Zmatplotlib.backendsr   Zipython_inline_display)r    r   r"   r"   r#   Ú_repr_html_”  s    
zFigure._repr_html_Tc          
   C   sŽ   yt | jdƒ}W n. tk
r> } ztd| ƒ‚W dd}~X Y nX |dk	rjy| ¡  dS  tk
rh   Y nX t ¡ dkrŠ|rŠt dt	ƒ  ¡ dS )aõ  
        If using a GUI backend with pyplot, display the figure window.

        If the figure was not created using
        :func:`~matplotlib.pyplot.figure`, it will lack a
        :class:`~matplotlib.backend_bases.FigureManagerBase`, and
        will raise an AttributeError.

        Parameters
        ----------
        warn : bool
            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.
        Úmanagerz]%s
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().NZheadlesszXMatplotlib is currently using %s, which is a non-GUI backend, so cannot show the figure.)
r`   r€   ÚAttributeErrorÚshowr   r   Z"_get_running_interactive_frameworkrB   rC   r   )r    rC   r‘   Úerrr"   r"   r#   r“   œ  s    zFigure.showc             C   s
   | j  ¡ S )N)r†   r/   )r    r"   r"   r#   Ú	_get_axes¿  s    zFigure._get_axesz×List of axes in the Figure. You can access the axes in the Figure through this list. Do not modify the list itself. Instead, use `~Figure.add_axes`, `~.Figure.subplot` or `~.Figure.delaxes` to add or remove an axes.)ÚfgetÚdocc             C   s   | j S )N)r{   )r    r"   r"   r#   Ú_get_dpiÉ  s    zFigure._get_dpic             C   sF   || _ | j ¡  ||¡ |  ¡ \}}| j|||d | j d| ¡ dS )z
        Parameters
        ----------
        dpi : float

        forward : bool
            Passed on to `~.Figure.set_size_inches`
        )ÚforwardZdpi_changedN)r{   rz   Úclearry   Úget_size_inchesÚset_size_inchesrt   Zprocess)r    r   r™   rj   ri   r"   r"   r#   Ú_set_dpiÌ  s
    	zFigure._set_dpiz The resolution in dots per inch.)r—   c             C   s   | j S )z6Return whether `.tight_layout` is called when drawing.)Ú_tight)r    r"   r"   r#   Úget_tight_layoutÝ  s    zFigure.get_tight_layoutc             C   s8   |dkrt d }t|ƒ| _t|tƒr(|ni | _d| _dS )a¿  
        Set whether and how `.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 `.tight_layout` upon drawing.
            If ``None``, use the ``figure.autolayout`` rcparam instead.
            If a dict, pass it as kwargs to `.tight_layout`, overriding the
            default paddings.
        Nzfigure.autolayoutT)r   Úboolrž   r<   r1   Ú_tight_parametersr   )r    Ztightr"   r"   r#   r…   á  s
    
zFigure.set_tight_layoutc             C   s   | j S )z•
        Return a boolean: True means constrained layout is being used.

        See :doc:`/tutorials/intermediate/constrainedlayout_guide`.
        )Ú_constrained)r    r"   r"   r#   Úget_constrained_layoutó  s    zFigure.get_constrained_layoutc             C   st   t ƒ | _d| jd< d| jd< d| jd< d| jd< |dkr@td }t|ƒ| _t|t ƒrb| jf |Ž n|  ¡  d| _dS )aG  
        Set whether ``constrained_layout`` is used upon drawing. If None,
        the rcParams['figure.constrained_layout.use'] value will be used.

        When providing a dict containing the keys `w_pad`, `h_pad`
        the default ``constrained_layout`` paddings will be
        overridden.  These pads are in inches and default to 3.0/72.0.
        ``w_pad`` is the width padding and ``h_pad`` is the height padding.

        See :doc:`/tutorials/intermediate/constrainedlayout_guide`.

        Parameters
        ----------
        constrained : bool or dict or None
        NÚw_padÚh_padrW   rX   zfigure.constrained_layout.useT)r1   Ú_constrained_layout_padsr   r    r¢   r<   Úset_constrained_layout_padsr   )r    Zconstrainedr"   r"   r#   r„   û  s    





zFigure.set_constrained_layoutc             K   sT   ddddg}xB|D ]:}||kr:|| dk	r:|| | j |< qtd|  | j |< qW dS )a”  
        Set padding for ``constrained_layout``.  Note the kwargs can be passed
        as a dictionary ``fig.set_constrained_layout(**paddict)``.

        See :doc:`/tutorials/intermediate/constrainedlayout_guide`.

        Parameters
        ----------

        w_pad : scalar
            Width padding in inches.  This is the pad around axes
            and is meant to make sure there is enough room for fonts to
            look good.  Defaults to 3 pts = 0.04167 inches

        h_pad : scalar
            Height padding in inches. Defaults to 3 pts.

        wspace: scalar
            Width padding between subplots, expressed as a fraction of the
            subplot width.  The total padding ends up being w_pad + wspace.

        hspace: scalar
            Height padding between subplots, expressed as a fraction of the
            subplot width. The total padding ends up being h_pad + hspace.

        r¤   r¥   rW   rX   Nzfigure.constrained_layout.)r¦   r   )r    ÚkwargsZtodoZtdr"   r"   r#   r§     s
    
z"Figure.set_constrained_layout_padsFc             C   st   | j d }| j d }| j d }| j d }|rh|dk	s<|dk	rht | ¡}|j}|| |j }|| |j }||||fS )ax  
        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 :doc:`/tutorials/intermediate/constrainedlayout_guide`.

        Parameters
        ----------

        relative : boolean
            If `True`, then convert from inches to figure relative.
        r¤   r¥   rW   rX   N)r¦   Ú	layoutboxÚget_rendererr   rn   ro   )r    Úrelativer¤   r¥   rW   rX   Z	renderer0r   r"   r"   r#   Úget_constrained_layout_pads>  s    




z"Figure.get_constrained_layout_padsçš™™™™™É?é   rU   c             C   sâ   t dd„ | jD ƒƒ}t| jƒdkrTx¤| jd j|dD ]}| |¡ | |¡ q6W nt|rÈxn|  ¡ D ]b}| ¡ ršxT|j|dD ]}| |¡ | |¡ q|W qbx|j|dD ]}| d¡ q¨W | 	d¡ qbW |rØ| j
|d d	| _d
S )aD  
        Date ticklabels often overlap, so it is useful to rotate them
        and right align them.  Also, a common use case is a number of
        subplots with shared xaxes where the x-axis is date data.  The
        ticklabels are often long, and it helps to rotate them on the
        bottom subplot and turn them off on other subplots, as well as
        turn off xlabels.

        Parameters
        ----------
        bottom : scalar
            The bottom of the subplots for :meth:`subplots_adjust`.

        rotation : angle in degrees
            The rotation of the xtick labels.

        ha : string
            The horizontal alignment of the xticklabels.

        which : {None, 'major', 'minor', 'both'}
            Selects which ticklabels to rotate. Default is None which works
            the same as major.
        c             s   s   | ]}t |d ƒV  qdS )Úis_last_rowN)Úhasattr)r(   Úaxr"   r"   r#   ú	<genexpr>r  s    z'Figure.autofmt_xdate.<locals>.<genexpr>r0   r   )ÚwhichFÚ )rT   TN)rw   rH   rF   Zget_xticklabelsZset_haZset_rotationÚget_axesr¯   Úset_visibleZ
set_xlabelÚsubplots_adjustr   )r    rT   ZrotationÚhar³   ZallsubplotsZlabelr±   r"   r"   r#   Úautofmt_xdateZ  s"    

zFigure.autofmt_xdatec             C   s`   | j g}| | j¡ | | j¡ | | j¡ | | j¡ | | j¡ | | j¡ | | j¡ |S )z.Get a list of artists contained in the figure.)	r~   ÚextendÚartistsrH   ÚlinesÚpatchesÚtextsÚimagesÚlegends)r    Úchildrenr"   r"   r#   Úget_children‡  s    zFigure.get_childrenc             C   s0   t | jƒr|  | |¡S | j |j|j¡}|i fS )z|
        Test whether the mouse event occurred on the figure.

        Returns
        -------
            bool, {}
        )ÚcallableZ	_containsrf   ÚcontainsÚxÚy)r    Z
mouseeventZinsider"   r"   r#   rÄ   “  s    
zFigure.containsc             O   s   | j S )zY
        Return the figure bounding box in display space. Arguments are ignored.
        )rf   )r    Úargsr¨   r"   r"   r#   Úget_window_extent   s    zFigure.get_window_extentc             K   s„  d|kpd|k}|  dd¡}|  dd¡}d|kr@d|kr@d|d< d|krXd	|krXd
|d< d|kr˜d|kr|d|kr|td |d< d|kr˜d|kr˜td |d< | j|||f|Ž}| jdk	ræ| j |¡ | j ||f¡ | j |¡ | ¡  n’|| _d| j_| jdk	rx|sx| j	dd\}}}	}
| j}t
j|| j|jd d| j_x:|jD ]0}|| jjk	rDt
j| jj|g|d dd qDW d| _| jS )aV  
        Add a centered title to the figure.

        Parameters
        ----------
        t : str
            The title text.

        x : float, default 0.5
            The x location of the text in figure coordinates.

        y : float, default 0.98
            The y location of the text in figure coordinates.

        horizontalalignment, ha : {'center', 'left', right'}, default: 'center'
            The horizontal alignment of the text relative to (*x*, *y*).

        verticalalignment, va : {'top', 'center', 'bottom', 'baseline'}, default: 'top'
            The vertical alignment of the text relative to (*x*, *y*).

        fontsize, size : default: :rc:`figure.titlesize`
            The font size of the text. See `.Text.set_size` for possible
            values.

        fontweight, weight : default: :rc:`figure.titleweight`
            The font weight of the text. See `.Text.set_weight` for possible
            values.


        Returns
        -------
            text
                The `.Text` instance of the title.


        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.titlesize` and
            :rc:`figure.titleweight` are ignored in this case.

        **kwargs
            Additional kwargs are :class:`matplotlib.text.Text` properties.


        Examples
        --------

        >>> fig.suptitle('This is the figure title', fontsize=12)
        rÅ   rÆ   g      à?g\Âõ(\ï?Zhorizontalalignmentr¸   ÚcenterZverticalalignmentZvarV   ZfontpropertiesZfontsizerg   zfigure.titlesizeZ
fontweightZweightzfigure.titleweightNT)r«   z	.suptitle)ÚparentÚartistÚnameg       @Zrequired)ZpaddingZstrength)Úpopr   Útextr   Zset_textÚset_positionZupdate_fromr:   rƒ   r¬   r©   Ú	LayoutBoxrÌ   rÁ   Zvstackr   )r    Útr¨   Zmanual_positionrÅ   rÆ   Zsupr¤   r¥   rW   rX   ÚfiglbZchildr"   r"   r#   Úsuptitle¦  sB    6


zFigure.suptitlec             C   s
   || _ dS )z~
        Set the canvas that contains the figure

        Parameters
        ----------
        canvas : FigureCanvas
        N)r€   )r    r€   r"   r"   r#   Ú
set_canvas  s    zFigure.set_canvasr   c                s    |
r<|   ¡ ‰ ‡ fdd„|jd |jd fD ƒ}| j|dd t| |||||	f|Ž}t|_| |¡ | |¡ |dkr€| ||¡ | j	 
|¡ | j	j|_d| _|S )aá  
        Add a non-resampled image to the figure.

        The image is attached to the lower or upper left corner depending on
        *origin*.

        Parameters
        ----------
        X
            The image data. This is an array of one of the following shapes:

            - MxN: luminance (grayscale) values
            - MxNx3: RGB values
            - MxNx4: RGBA values

        xo, yo : int
            The *x*/*y* image offset in pixels.

        alpha : None or float
            The alpha blending value.

        norm : :class:`matplotlib.colors.Normalize`
            A :class:`.Normalize` instance to map the luminance to the
            interval [0, 1].

        cmap : str or :class:`matplotlib.colors.Colormap`
            The colormap to use. Default: :rc:`image.cmap`.

        vmin, vmax : scalar
            If *norm* is not given, these values set the data limits for the
            colormap.

        origin : {'upper', 'lower'}
            Indicates where the [0, 0] index of the array is in the upper left
            or lower left corner of the axes. Defaults to :rc:`image.origin`.

        resize : bool
            If *True*, resize the figure to match the given image size.

        Returns
        -------
        :class:`matplotlib.image.FigureImage`

        Other Parameters
        ----------------
        **kwargs
            Additional kwargs are `.Artist` kwargs passed on to `.FigureImage`.

        Notes
        -----
        figimage complements the axes image
        (:meth:`~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
        :class:`~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()

        c                s   g | ]}|ˆ  ‘qS r"   r"   )r(   rÅ   )r   r"   r#   r+   X  s    z#Figure.figimage.<locals>.<listcomp>r0   r   T)r™   N)Úget_dpiÚshaperœ   r   r$   Ústale_callbackZ	set_arrayZ	set_alphaZset_climr¿   Úappendr:   Ú_remove_methodr   )r    ÚXZxoZyoZalphaZnormZcmapZvminZvmaxÚoriginÚresizer¨   rŒ   Úimr"   )r   r#   Úfigimage  s    E"


zFigure.figimagec       
      C   s´   |dkr|\}}t dd„ ||fD ƒƒs6td ||¡ƒ‚||f| j_|rªt| dƒ}|dk	rªt| jddƒ}| j| }|| }|| }t| jddƒ}	|	dk	rª|	 t	|ƒt	|ƒ¡ d	| _
dS )
aÀ  Set the figure size in inches.

        Call signatures::

             fig.set_size_inches(w, h)  # OR
             fig.set_size_inches((w, h))

        optional kwarg *forward=True* will cause the canvas size to be
        automatically updated; e.g., you can resize the figure window
        from the shell

        ACCEPTS: a (w, h) tuple with w, h in inches

        See Also
        --------
        matplotlib.Figure.get_size_inches
        Nc             s   s   | ]}t  |¡V  qd S )N)ru   rv   )r(   Ú_r"   r"   r#   r²   ~  s    z)Figure.set_size_inches.<locals>.<genexpr>z'figure size must be finite not ({}, {})r€   Z
_dpi_ratior0   r‘   T)rw   r=   r>   rx   Úp1r`   r€   r   rÜ   Úintr   )
r    rj   ri   r™   r€   ZratioZdpivalZcanvaswZcanvashr‘   r"   r"   r#   rœ   g  s"    


zFigure.set_size_inchesc             C   s   t  | jj¡S )a  
        Returns the current size of the figure in inches.

        Returns
        -------
        size : ndarray
           The size (width, height) of the figure in inches.

        See Also
        --------
        matplotlib.Figure.set_size_inches
        )ru   Úarrayrx   rà   )r    r"   r"   r#   r›     s    zFigure.get_size_inchesc             C   s
   | j  ¡ S )z+Get the edge color of the Figure rectangle.)r~   Úget_edgecolor)r    r"   r"   r#   rã   ž  s    zFigure.get_edgecolorc             C   s
   | j  ¡ S )z+Get the face color of the Figure rectangle.)r~   Úget_facecolor)r    r"   r"   r#   rä   ¢  s    zFigure.get_facecolorc             C   s   | j jS )z#Return the figure width as a float.)rx   rn   )r    r"   r"   r#   Úget_figwidth¦  s    zFigure.get_figwidthc             C   s   | j jS )z$Return the figure height as a float.)rx   ro   )r    r"   r"   r#   Úget_figheightª  s    zFigure.get_figheightc             C   s   | j S )z2Return the resolution in dots per inch as a float.)r   )r    r"   r"   r#   rÕ   ®  s    zFigure.get_dpic             C   s   | j S )z.Return whether the figure frame will be drawn.)r|   )r    r"   r"   r#   Úget_frameon²  s    zFigure.get_frameonc             C   s   | j  |¡ dS )zz
        Set the edge color of the Figure rectangle.

        Parameters
        ----------
        color : color
        N)r~   Úset_edgecolor)r    Úcolorr"   r"   r#   rè   ¶  s    zFigure.set_edgecolorc             C   s   | j  |¡ dS )zz
        Set the face color of the Figure rectangle.

        Parameters
        ----------
        color : color
        N)r~   Úset_facecolor)r    ré   r"   r"   r#   rê   À  s    zFigure.set_facecolorc             C   s   || _ d| _dS )z
        Set the resolution of the figure in dots-per-inch.

        Parameters
        ----------
        val : float
        TN)r   r   )r    r!   r"   r"   r#   Úset_dpiÊ  s    zFigure.set_dpic             C   s   | j ||  ¡ |d dS )zS
        Set the width of the figure in inches.

        .. ACCEPTS: float
        )r™   N)rœ   ræ   )r    r!   r™   r"   r"   r#   Úset_figwidthÕ  s    zFigure.set_figwidthc             C   s   | j |  ¡ ||d dS )zT
        Set the height of the figure in inches.

        .. ACCEPTS: float
        )r™   N)rœ   rå   )r    r!   r™   r"   r"   r#   Úset_figheightÝ  s    zFigure.set_figheightc             C   s   || _ d| _dS )zŽ
        Set whether the figure frame (background) is displayed or invisible.

        Parameters
        ----------
        b : bool
        TN)r|   r   )r    Úbr"   r"   r#   Úset_frameonå  s    zFigure.set_frameonc             C   s.   | j  |¡ x| jD ]}|| ƒ qW d| _dS )zn
        Remove the `~matplotlib.axes.Axes` *ax* from the figure and update the
        current axes.
        TN)r†   r:   Ú_axobserversr   )r    r±   Úfuncr"   r"   r#   Údelaxesð  s    zFigure.delaxesc             O   s(   dd„ }dd„ }||ƒ||  ¡ ƒf}|S )z+Make a hashable key out of args and kwargs.c          	   S   sN   g }x@| D ]8\}}yt |ƒ}W n tk
r2   Y nX | ||f¡ q
W t |ƒS )N)re   Ú	ExceptionrØ   )ÚitemsÚretr)   Úvr"   r"   r#   Úfixitemsý  s    z"Figure._make_key.<locals>.fixitemsc             S   s4   g }x&| D ]}t |ƒrt|ƒ}| |¡ q
W t|ƒS )N)r   re   rØ   )rÇ   rõ   r*   r"   r"   r#   Úfixlist  s    
z!Figure._make_key.<locals>.fixlist)rô   )r    rÇ   r¨   r÷   rø   r4   r"   r"   r#   Ú	_make_keyú  s    zFigure._make_keyc             C   sN   |  | ¡ | j |¡ | jj|_| ¡ s4| | j¡ |rD| | j	¡ d| _
|S )aT  
        Add any :class:`~matplotlib.artist.Artist` to the figure.

        Usually artists are added to axes objects using
        :meth:`matplotlib.axes.Axes.add_artist`, but use this method in the
        rare cases that adding directly to the figure is necessary.

        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.transFigure``.
        clip : bool, optional, default ``False``
            An optional parameter ``clip`` determines whether the added artist
            should be clipped by the figure patch. Default is *False*,
            i.e. no clipping.

        Returns
        -------
        artist : The added `~matplotlib.artist.Artist`
        T)Ú
set_figurer»   rØ   r:   rÙ   Zis_transform_setÚset_transformr}   Zset_clip_pathr~   r   )r    rË   Úclipr"   r"   r#   Ú
add_artist  s    

zFigure.add_artistc             O   s  t |ƒsdS | j||Ž}| j |¡}|dk	r:|  |¡ |S t|d tƒrf|d }| ¡ | k	rÒtdƒ‚nl|d }t	 
|¡ ¡ sŠtd |¡ƒ‚t| f|ž|Ž\}}}| j |¡}t||ƒrÄ|  |¡ |S || |f|Ž}| j ||¡ |  |¡ | j|_d| _t|_|S )a  
        Add an axes to the figure.

        Call signatures::

            add_axes(rect, projection=None, polar=False, **kwargs)
            add_axes(ax)

        Parameters
        ----------

        rect : sequence of float
            The dimensions [left, bottom, width, height] of the new axes. All
            quantities are in fractions of figure width and height.

        projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear', 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 : boolean, optional
            If True, equivalent to projection='polar'.

        sharex, sharey : `~.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.

        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)s

        Returns
        -------
        axes : `~.axes.Axes` (or a subclass of `~.axes.Axes`)
            The returned axes class depends on the projection used. It is
            `~.axes.Axes` if rectilinear projection are used and
            `.projections.polar.PolarAxes` if polar projection
            are used.

        Notes
        -----
        If the figure already has an axes with key (*args*,
        *kwargs*) then it will simply make that axes current and
        return it.  This behavior is deprecated. Meanwhile, if you do
        not want this behavior (i.e., you want to force the creation of a
        new axes), you must use a unique set of args and kwargs.  The axes
        *label* attribute has been exposed for this purpose: if you want
        two axes that are otherwise identical to be added to the figure,
        make sure you give them unique labels.

        In rare circumstances, `.add_axes` may be called with a single
        argument, a axes instance already created in the present figure but
        not in the figure's list of axes.

        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(1)
            fig.add_axes(rect,label=label1)
            fig.add_axes(rect,label=label2)
            fig.add_axes(rect, frameon=False, facecolor='g')
            fig.add_axes(rect, polar=True)
            ax=fig.add_axes(rect, projection='polar')
            fig.delaxes(ax)
            fig.add_axes(ax)
        Nr   z5The Axes must have been created in the present figurez)all entries in rect must be finite not {}T)rF   rù   r†   r2   Úscar<   r   Ú
get_figurer=   ru   rv   rw   r>   r   rE   Ú
_remove_axrÙ   r   r$   r×   )r    rÇ   r¨   r4   r±   r*   ÚrectÚprojection_classr"   r"   r#   Úadd_axes<  s:    [



zFigure.add_axesc             O   s2  t |ƒsdS t |ƒdkrht|d tƒrhd|d   kr>dksRn td |d ¡ƒ‚tttt|d ƒƒƒ}t|d t	ƒr |d }| 
¡ | k	r’tdƒ‚| j||Ž}nbt| f|ž|Ž\}}}| j |¡}|dk	rît||ƒrâ|  |¡ |S | j |¡ t|ƒ| f|ž|Ž}| j ||¡ |  |¡ | j|_d| _t|_|S )	aq  
        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)

        Parameters
        ----------
        *args
            Either a 3-digit integer or three separate integers
            describing the position of the subplot. If the three
            integers are *nrows*, *ncols*, and *index* in order, 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.

            *pos* is a three digit integer, where the first digit is the
            number of rows, the second the number of columns, and the third
            the index of the subplot. i.e. fig.add_subplot(235) is the same as
            fig.add_subplot(2, 3, 5). Note that all integers must be less than
            10 for this form to work.

        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 : boolean, optional
            If True, equivalent to projection='polar'.

        sharex, sharey : `~.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.

        Other Parameters
        ----------------
        **kwargs
            This method also takes the keyword arguments for
            the returned axes base class. 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)s

        Returns
        -------
        axes : an `.axes.SubplotBase` subclass of `~.axes.Axes` (or a                subclass of `~.axes.Axes`)

            The axes of the subplot. The returned axes base class depends on
            the projection used. It is `~.axes.Axes` if rectilinear projection
            are used and `.projections.polar.PolarAxes` if polar projection
            are used. The returned axes is then a subplot subclass of the
            base class.

        Notes
        -----
        If the figure already has a subplot with key (*args*,
        *kwargs*) then it will simply make that subplot current and
        return it.  This behavior is deprecated. Meanwhile, if you do
        not want this behavior (i.e., you want to force the creation of a
        new suplot), you must use a unique set of args and kwargs.  The axes
        *label* attribute has been exposed for this purpose: if you want
        two subplots that are otherwise identical to be added to the figure,
        make sure you give them unique labels.

        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.

        See Also
        --------
        .Figure.add_axes
        .pyplot.subplot
        .pyplot.axes
        .Figure.subplots
        .pyplot.subplots

        Examples
        --------
        ::

            fig=plt.figure(1)
            fig.add_subplot(221)

            # equivalent but more general
            ax1=fig.add_subplot(2, 2, 1)

            # add a subplot with no frame
            ax2=fig.add_subplot(222, frameon=False)

            # add a polar subplot
            fig.add_subplot(223, projection='polar')

            # add a red subplot that share the x-axis with ax1
            fig.add_subplot(224, sharex=ax1, facecolor='red')

            #delete x2 from the figure
            fig.delaxes(ax2)

            #add x2 to the figure again
            fig.add_subplot(ax2)
        Nr0   r   éd   iç  zBInteger subplot specification must be a three-digit number, not {}z8The Subplot must have been created in the present figureT)rF   r<   r   r=   r>   re   Úmaprá   Ústrr   rÿ   rù   r   r†   r2   rþ   r:   r   rE   r   rÙ   r   r$   r×   )r    rÇ   r¨   r*   r4   r  r±   r"   r"   r#   Úadd_subplotÀ  s8    q


zFigure.add_subplotr0   c             C   s:  t |tƒr|rdnd}t |tƒr,|r(dnd}ddddg}||krdt |tƒrTt d¡ td||f ƒ‚||kr|td||f ƒ‚|dkrˆi }|dkr”i }| ¡ }| ¡ }|  ¡ rÄt||fd	| i|—Ž}	nt||fd	di|—Ž}	| j	 
|	¡ tj||ftd
}
x~t|ƒD ]r}xjt|ƒD ]^}d|
d |
|df |
d|f dœ}|| |d< || |d< | j|	||f f|Ž|
||f< qW qW |dkrÄx@|
dd…dd…f jD ]&}|jjdddd |jj d¡ qšW |dkrx@|
dd…dd…f jD ]&}|jjdddd |jj d¡ qæW |r2|
jdkr*|
 ¡ S |
 ¡ S |
S dS )aÛ  
        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, optional, default: 1
            Number of rows/columns of the subplot grid.

        sharex, sharey : bool or {'none', 'all', 'row', 'col'}, default: False
            Controls sharing of properties among x (`sharex`) or y (`sharey`)
            axes:

                - True or 'all': x- or y-axis will be shared among all
                  subplots.
                - False or 'none': each subplot x- or y-axis will be
                  independent.
                - 'row': each subplot row will share an x- or y-axis.
                - 'col': each subplot column will share an x- or y-axis.

            When subplots have a shared x-axis along a column, only the x tick
            labels of the bottom subplot are created. Similarly, when subplots
            have a shared y-axis along a row, only the y tick labels of the
            first column subplot are created. To later turn other subplots'
            ticklabels on, use `~matplotlib.axes.Axes.tick_params`.

        squeeze : bool, optional, default: True
            - If True, extra dimensions are squeezed out from the returned
              array of Axes:

                - if only one subplot is constructed (nrows=ncols=1), the
                  resulting single Axes object is returned as a scalar.
                - for Nx1 or 1xM subplots, the returned object is a 1D numpy
                  object array of Axes objects.
                - for NxM, subplots with N>1 and M>1 are returned
                  as a 2D array.

            - If False, no squeezing at all is done: the returned Axes object
              is always a 2D array containing Axes instances, even if it ends
              up being 1x1.

        subplot_kw : dict, optional
            Dict with keywords passed to the
            :meth:`~matplotlib.figure.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
        -------
        ax : `~.axes.Axes` object or array of Axes objects.
            *ax* can be 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.

        Examples
        --------
        ::

            # First create some toy data:
            x = np.linspace(0, 2*np.pi, 400)
            y = np.sin(x**2)

            # Create a figure
            plt.figure(1, clear=True)

            # Creates a subplot
            ax = fig.subplots()
            ax.plot(x, y)
            ax.set_title('Simple plot')

            # Creates two subplots and unpacks the output array immediately
            ax1, ax2 = fig.subplots(1, 2, sharey=True)
            ax1.plot(x, y)
            ax1.set_title('Sharing Y axis')
            ax2.scatter(x, y)

            # Creates four polar axes, and accesses them through the
            # returned array
            axes = fig.subplots(2, 2, subplot_kw=dict(polar=True))
            axes[0, 0].plot(x, y)
            axes[1, 1].scatter(x, y)

            # Share a X axis with each column of subplots
            fig.subplots(2, 2, sharex='col')

            # Share a Y axis with each row of subplots
            fig.subplots(2, 2, sharey='row')

            # Share both X and Y axes with all subplots
            fig.subplots(2, 2, sharex='all', sharey='all')

            # Note that this is the same as
            fig.subplots(2, 2, sharex=True, sharey=True)

            See Also
            --------
            .pyplot.subplots
            .Figure.add_subplot
            .pyplot.subplot
            rw   ÚnoneÚrowÚcolz\sharex argument to subplots() was an integer. Did you intend to use subplot() (without 's')?zsharex [%s] must be one of %szsharey [%s] must be one of %sNr   )Zdtype)r   r   r   )r  rw   r	  r
  ÚsharexÚsharey)r
  rw   éÿÿÿÿZbothF)r³   ZlabelbottomZlabeltop)r	  rw   r0   )r³   Z	labelleftZ
labelright)r<   r    r   rB   rC   r=   Úcopyr£   r   r‹   rØ   ru   ÚemptyrA   Úranger  ZflatÚxaxisZset_tick_paramsZ
offsetTextr¶   Úyaxisrg   r5   Úsqueeze)r    ÚnrowsÚncolsr  r  r  Z
subplot_kwZgridspec_kwZshare_valuesÚgsZaxarrr	  r
  Zshared_withr±   r"   r"   r#   Úsubplots_  sZ    n


*



zFigure.subplotsc             C   sZ   dd„ }dd„ }|   |¡ |||jƒ}|d k	r8||jƒ |||jƒ}|d k	rV||jƒ d S )Nc             S   s<   |   |  ¡ ¡ |  |  ¡ ¡ |  |  ¡ ¡ |  |  ¡ ¡ d S )N)Zset_major_formatterZget_major_formatterZset_major_locatorZget_major_locatorZset_minor_formatterZget_minor_formatterZset_minor_locatorZget_minor_locator)Zaxisr"   r"   r#   Ú_reset_loc_form  s    z*Figure._remove_ax.<locals>._reset_loc_formc             S   s>   |  | ¡}t|ƒdkr:| | ¡ x|D ]}| |k	r&|S q&W d S )Nr0   )Zget_siblingsrF   r:   )r±   ZgrouperZsiblingsÚlast_axr"   r"   r#   Ú_break_share_link  s    


z,Figure._remove_ax.<locals>._break_share_link)rò   Z_shared_y_axesr  Z_shared_x_axesr  )r    r±   r  r  r  r"   r"   r#   r     s    	

zFigure._remove_axc             C   s°   d| _ t ¡ | _x$t| jƒD ]}| ¡  |  |¡ qW t| j	ddƒ}|dk	rT| 
¡  | j ¡  g | _g | _g | _g | _g | _g | _|sŒg | _d| _|  ¡ r¦t | j¡ d| _dS )z“
        Clear the figure.

        Set *keep_observers* to True if, for example,
        a gui widget is tracking the axes in the figure.
        NÚtoolbarT)ÚsuppressCompositer3   rs   rt   re   rH   Zclarò   r`   r€   rR   r†   rš   r»   r¼   r½   r¾   r¿   rÀ   rð   r   r£   r©   Znonetreerƒ   r   )r    Úkeep_observersr±   r  r"   r"   r#   r‡   *  s*    

z
Figure.clfc             C   s   | j |d dS )z>
        Clear the figure -- synonym for :meth:`clf`.
        )r  N)r‡   )r    r  r"   r"   r#   rš   I  s    zFigure.clearc             C   sø   |   ¡ sdS tdd„ | j| j | j | j | j | j | j D ƒdd„ d}zŒ| 	d¡ |  
¡ rp| jrp|  |¡ |  ¡ r¨| jr¨y| j|f| jŽ W n tk
r¦   Y nX | jrº| j |¡ t || || j¡ | d¡ W dd| _X || _| j |¡ dS )	zu
        Render the figure using :class:`matplotlib.backend_bases.RendererBase`
        instance *renderer*.
        Nc             s   s   | ]}|  ¡ s|V  qd S )N)Zget_animated)r(   rË   r"   r"   r#   r²   [  s    zFigure.draw.<locals>.<genexpr>c             S   s   |   ¡ S )N)Z
get_zorder)rË   r"   r"   r#   Ú<lambda>_  s    zFigure.draw.<locals>.<lambda>)r4   r   F)Úget_visibleÚsortedr½   r¼   r»   r¿   rH   r¾   rÀ   Z
open_groupr£   Úexecute_constrained_layoutrŸ   rŽ   r¡   r=   r|   r~   ÚdrawÚmimageZ_draw_list_compositing_imagesr  Zclose_groupr   rˆ   r€   Z
draw_event)r    Úrendererr»   r"   r"   r#   r"  O  s0    ,

zFigure.drawc             C   s"   | j dkrtdƒ‚| | j ¡ dS )z…
        Draw :class:`matplotlib.artist.Artist` instance *a* only.
        This is available only after the figure is drawn.
        NzLdraw_artist can only be used after an initial draw which caches the renderer)rˆ   r’   r"  )r    r*   r"   r"   r#   Údraw_artistz  s    
zFigure.draw_artistc             C   s   | j S )aY  
        Return a list of axes in the Figure. You can access and modify the
        axes in the Figure through this list.

        Do not modify the list itself. Instead, use `~Figure.add_axes`,
        `~.Figure.subplot` or `~.Figure.delaxes` to add or remove an axes.

        Note: This is equivalent to the property `~.Figure.axes`.
        )rH   )r    r"   r"   r#   rµ   „  s    
zFigure.get_axesc             O   sZ   t j| jf|ž|Ž\}}}}t|ƒr$t j| ||f|ž|Ž}| j |¡ | jj|_d| _	|S )ac  
        Place a legend on the figure.

        To make a legend from existing artists on every axes::

          legend()

        To make a legend for a list of lines and labels::

          legend( (line1, line2, line3),
                  ('label1', 'label2', 'label3'),
                  loc='upper right')

        These can also be specified by keyword::

          legend(handles=(line1, line2, line3),
                labels=('label1', 'label2', 'label3'),
                loc='upper right')

        Parameters
        ----------

        handles : sequence of `.Artist`, optional
            A list of Artists (lines, patches) to be added to the legend.
            Use this together with *labels*, if you need full control on what
            is shown in the legend and the automatic mechanism described above
            is not sufficient.

            The length of handles and labels should be the same in this
            case. If they are not, they are truncated to the smaller length.

        labels : sequence of strings, optional
            A list of labels to show next to the artists.
            Use this together with *handles*, if you need full control on what
            is shown in the legend and the automatic mechanism described above
            is not sufficient.

        Other Parameters
        ----------------

        %(_legend_kw_doc)s

        Returns
        -------
        :class:`matplotlib.legend.Legend` instance

        Notes
        -----
        Not all kinds of artist are supported by the legend command. See
        :doc:`/tutorials/intermediate/legend_guide` for details.
        T)
ÚmlegendZ_parse_legend_argsrH   rF   ZLegendrÀ   rØ   r:   rÙ   r   )r    rÇ   r¨   ZhandlesÚlabelsZ
extra_argsÚlr"   r"   r#   Úlegend  s    6

zFigure.legendc       	      K   s„   t | jd}|r t|||d}nt|||d}| |¡ |dk	rJ| |¡ | |¡ | | ¡ t|_| j 	|¡ | jj
|_d| _|S )aU  
        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 : dictionary, optional, default: None
            A dictionary to override the default text properties. If fontdict
            is None, the defaults are determined by your rc parameters. A
            property in *kwargs* override the same property in fontdict.

        withdash : boolean, optional, default: False
            Creates a `~matplotlib.text.TextWithDash` instance instead of a
            `~matplotlib.text.Text` instance.

        Other Parameters
        ----------------
        **kwargs : `~matplotlib.text.Text` properties
            Other miscellaneous text parameters.
            %(Text)s

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

        See Also
        --------
        .Axes.text
        .pyplot.text
        )Z	transform)rÅ   rÆ   rÎ   NT)r1   r}   r   r   rR   rú   r$   r×   r¾   rØ   r:   rÙ   r   )	r    rÅ   rÆ   rc   ZfontdictZwithdashr¨   ÚdefaultrÎ   r"   r"   r#   rÎ   Û  s    '




zFigure.textc             C   s(   || kr|  | ¡ t|_| | j¡ d S )N)rú   r$   r×   rû   r}   )r    r*   r"   r"   r#   r     s    
zFigure._set_artist_propsc             K   sx   | j  ¡ \}}|dk	rl|s|S t| f|Ž\}}}|dd… }|dd… }||kr^t||ƒr^|S tjddd | jd|ŽS )a  
        Get the current axes, creating one if necessary.

        The following kwargs are supported for ensuring the returned axes
        adheres to the given projection etc., and for axes creation if
        the active axes does not exist:

        %(Axes)s

        Nr0   zlRequested projection is different from current axis projection, creating new axis with requested projection.é   )Ú
stacklevel)r0   r0   r0   )r†   rI   r   r<   rB   rC   r  )r    r¨   ZckeyÚcaxr  rß   r4   r"   r"   r#   Úgca  s    z
Figure.gcac             C   s(   | j  |¡ x| jD ]}|| ƒ qW |S )z*Set the current axes to be a and return a.)r†   r;   rð   )r    r*   rñ   r"   r"   r#   rþ   I  s    z
Figure.scac             C   sZ   | j  ¡ d }|dkrdS | ¡ }|dk	r.|S x&t| jƒD ]}| ¡ }|dk	r:|S q:W dS )zR
        Helper for :func:`~matplotlib.pyplot.gci`. Do not use elsewhere.
        r0   N)r†   rI   Ú_gciÚreversedrH   )r    r-  rÝ   r±   r"   r"   r#   r/  P  s    zFigure._gcic                s|   t ƒ  ¡ }xdD ]}| |d ¡ qW t|d< ddlm} t| jdd ƒ|jj	 
¡ krZd|d< | dd ¡ | jd k	rxd | j_|S )	N)rð   r“   r€   rˆ   Ú__mpl_version__r   )Ú_pylab_helpersr‘   TÚ_restore_to_pylabrƒ   )ÚsuperÚ__getstate__rÍ   Ú_mpl_versionÚ
matplotlibr2  r`   r€   ÚGcfZfigsÚvaluesr   rƒ   )r    ÚstateZattr_to_popr2  )rk   r"   r#   r5  e  s    


zFigure.__getstate__c       	         sì   |  d¡}|  dd¡}|tkr6dd l}| d|f ¡ || _g | _d | _d | _|râdd lm	} dd l
m‰ | ¡ }|r‚t|ƒd nd}|j || ¡‰ |  ¡ rªˆ  |  ¡ ¡ ‡ ‡fdd„}ˆ j d	|¡ˆ _ˆj ˆ ¡ || _| ¡  d
| _d S )Nr1  r3  Fr   zWThis figure was saved with matplotlib version %s and is unlikely to function correctly.r0   c                s   ˆj  ˆ ¡ d S )N)r8  Ú
set_active)Zevent)ÚmgrÚpylab_helpersr"   r#   Úmake_active¢  s    z(Figure.__setstate__.<locals>.make_activeZbutton_press_eventT)rÍ   r6  rB   rC   Ú__dict__rð   r€   rƒ   Zmatplotlib.pyplotZpyplotZmatplotlib._pylab_helpersr2  Zget_fignumsÚmaxZ_backend_modZnew_figure_manager_given_figureZ	get_labelZset_window_titleZmpl_connectZ_cidgcfr8  r;  ZnumberZdraw_if_interactiver   )	r    r:  ÚversionZrestore_to_pylabrB   ZpltZallnumsZnumr>  r"   )r<  r=  r#   Ú__setstate__‚  s2    

zFigure.__setstate__c             C   s   | j  |¡ dS )z>Whenever the axes state change, ``func(self)`` will be called.N)rð   rØ   )r    rñ   r"   r"   r#   Úadd_axobserver®  s    zFigure.add_axobserver)r|   Útransparentc      
      K   s*  |  dtd ¡ |dkr td }|dkr0td }|r’|  dd¡ |  dd¡ g }x`| jD ]4}|j}| | ¡ | ¡ f¡ | d¡ | d¡ qXW n |  dtd	 ¡ |  dtd
 ¡ |rÈ|  	¡ }|  
|¡ | jj|f|Ž |ræ|  
|¡ |r&x8t| j|ƒD ](\}}	|j |	d ¡ |j |	d ¡ qúW dS )a\  
        Save the current figure.

        Call signature::

          savefig(fname, dpi=None, facecolor='w', edgecolor='w',
                  orientation='portrait', papertype=None, format=None,
                  transparent=False, bbox_inches=None, pad_inches=0.1,
                  frameon=None, metadata=None)

        The output formats available depend on the backend being used.

        Parameters
        ----------

        fname : str or file-like object
            A string containing a path to a filename, or a Python
            file-like object, or possibly some backend-dependent object
            such as :class:`~matplotlib.backends.backend_pdf.PdfPages`.

            If *format* is *None* and *fname* is a string, the output
            format is deduced from the extension of the filename. If
            the filename has no extension, :rc:`savefig.format` is used.

            If *fname* is not a string, remember to specify *format* to
            ensure that the correct backend is used.

        Other Parameters
        ----------------

        dpi : [ *None* | scalar > 0 | 'figure' ]
            The resolution in dots per inch.  If *None*, defaults to
            :rc:`savefig.dpi`.  If 'figure', uses the figure's dpi value.

        quality : [ *None* | 1 <= scalar <= 100 ]
            The image quality, on a scale from 1 (worst) to 95 (best).
            Applicable only if *format* is jpg or jpeg, ignored otherwise.
            If *None*, defaults to :rc:`savefig.jpeg_quality` (95 by default).
            Values above 95 should be avoided; 100 completely disables the
            JPEG quantization stage.

        facecolor : color spec or None, optional
            The facecolor of the figure; if *None*, defaults to
            :rc:`savefig.facecolor`.

        edgecolor : color spec or None, optional
            The edgecolor of the figure; if *None*, defaults to
            :rc:`savefig.edgecolor`

        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.

        format : str
            One of the file extensions supported by the active
            backend.  Most backends support png, pdf, ps, eps and svg.

        transparent : bool
            If *True*, the axes patches will all be transparent; the
            figure patch will also be transparent unless facecolor
            and/or edgecolor are specified via kwargs.
            This is useful, for example, for displaying
            a plot on top of a colored background on a web page.  The
            transparency of these patches will be restored to their
            original values upon exit of this function.

        frameon : bool
            If *True*, the figure patch will be colored, if *False*, the
            figure background will be transparent.  If not provided, the
            rcParam 'savefig.frameon' will be used.

        bbox_inches : str or `~matplotlib.transforms.Bbox`, optional
            Bbox in inches. Only the given portion of the figure is
            saved. If 'tight', try to figure out the tight bbox of
            the figure. If None, use savefig.bbox

        pad_inches : scalar, optional
            Amount of padding around the figure when bbox_inches is
            'tight'. If None, use savefig.pad_inches

        bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
            A list of extra artists that will be considered when the
            tight bbox is calculated.

        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`.
            - 'eps' and 'ps' with PS backend: Only 'Creator' is supported.

        r   zsavefig.dpiNzsavefig.frameonzsavefig.transparentrp   r  rq   zsavefig.facecolorzsavefig.edgecolorr   r0   )Ú
setdefaultr   rH   r~   rØ   rä   rã   rê   rè   rç   rï   r€   Zprint_figureÚzip)
r    Úfnamer|   rD  r¨   Zoriginal_axes_colorsr±   r~   Zoriginal_frameonZccr"   r"   r#   Úsavefig²  s6    d



zFigure.savefigc       	         s¦   |dkr|   ¡ }|   ¡ }|dkr\|rJt|tƒrJ|  ¡ sJtj|f|Ž\}}ntj|f|Ž\}}ddddddg‰ ‡ fdd	„| ¡ D ƒ}tj||f|Ž}|  	|¡ d
| _
|S )z›
        Create a colorbar for a ScalarMappable instance, *mappable*.

        Documentation for the pyplot thin wrapper:
        %(colorbar_doc)s
        NZfractionÚpadZshrinkZaspectZanchorZpanchorc                s   i | ]\}}|ˆ kr||“qS r"   r"   )r(   r)   rö   )ÚNON_COLORBAR_KEYSr"   r#   r7   P  s    z#Figure.colorbar.<locals>.<dictcomp>T)r.  r<   r   r£   ÚcbarZmake_axes_gridspecZ	make_axesrô   Zcolorbar_factoryrþ   r   )	r    Zmappabler-  r±   Zuse_gridspecÚkwZ
current_axZcb_kwÚcbr"   )rJ  r#   Úcolorbar8  s    

zFigure.colorbarc             C   s¶   |   ¡ r|  d¡ t d¡ | j ||||||¡ xx| jD ]n}t|tƒs”t|j	tƒrn|j	 
¡  | |j	j¡ q¨t|jtƒr¨|j 
¡  | |jj¡ q:| 
¡  | |j¡ q:W d| _dS )z‹
        Update the :class:`SubplotParams` with *kwargs* (defaulting to rc when
        *None*) and update the subplot locations.

        Fz–This figure was using constrained_layout==True, but that is incompatible with subplots_adjust and or tight_layout: setting constrained_layout==False. TN)r£   r„   rB   rC   r‚   rR   rH   r<   r   Z_sharexZupdate_paramsrÏ   ZfigboxZ_shareyr   )r    rS   rT   rU   rV   rW   rX   r±   r"   r"   r#   r·   W  s    




zFigure.subplots_adjusté   r+  c             C   s   t | |||d}||||dS )a5  
        Blocking call to interact with a figure.

        Wait until the user clicks *n* times on the figure, and return the
        coordinates of each click in a list.

        The buttons used for the various actions (adding points, removing
        points, terminating the inputs) can be overridden via the
        arguments *mouse_add*, *mouse_pop* and *mouse_stop*, that give
        the associated mouse button: 1 for left, 2 for middle, 3 for
        right.

        Parameters
        ----------
        n : int, optional, default: 1
            Number of mouse clicks to accumulate. If negative, accumulate
            clicks until the input is terminated manually.
        timeout : scalar, optional, default: 30
            Number of seconds to wait before timing out. If zero or negative
            will never timeout.
        show_clicks : bool, optional, default: False
            If True, show a red cross at the location of each click.
        mouse_add : int, one of (1, 2, 3), optional, default: 1 (left click)
            Mouse button used to add points.
        mouse_pop : int, one of (1, 2, 3), optional, default: 3 (right click)
            Mouse button used to remove the most recently added point.
        mouse_stop : int, one of (1, 2, 3), optional, default: 2 (middle click)
            Mouse button used to stop input.

        Returns
        -------
        points : list of tuples
            A list of the clicked (x, y) coordinates.

        Notes
        -----
        The keyboard can also be used to select points in case your mouse
        does not have one or more of the buttons.  The delete and backspace
        keys act like right clicking (i.e., remove last point), the enter key
        terminates input and any other key (not already used by the window
        manager) selects a point.
        )Ú	mouse_addÚ	mouse_popÚ
mouse_stop)ÚnÚtimeoutÚshow_clicks)r   )r    rS  rT  rU  rP  rQ  rR  Zblocking_mouse_inputr"   r"   r#   Úginputs  s    -zFigure.ginputr  c             C   s   t | ƒ}||dS )a  
        Blocking call to interact with the figure.

        This will return True is a key was pressed, False if a mouse
        button was pressed and None if *timeout* was reached without
        either being pressed.

        If *timeout* is negative, does not timeout.
        )rT  )r   )r    rT  Zblocking_inputr"   r"   r#   Úwaitforbuttonpress§  s    zFigure.waitforbuttonpressc             C   sH   dd„ |   ¡ D ƒ}x$| jD ]}| ¡ r| | ¡ ¡ qW | | j¡ |S )Nc             S   s    g | ]}|  ¡ r| ¡ r|‘qS r"   )r  Zget_in_layout)r(   rË   r"   r"   r#   r+   ¶  s    z9Figure.get_default_bbox_extra_artists.<locals>.<listcomp>)rÂ   rH   r  rº   Úget_default_bbox_extra_artistsr:   r~   )r    Zbbox_artistsr±   r"   r"   r#   rX  µ  s    z%Figure.get_default_bbox_extra_artistsc       
   	   C   sò   g }|dkr|   ¡ }n|}x<|D ]4}| |¡}|dk	r |jdksJ|jdkr | |¡ q W xR| jD ]H}| ¡ r`y|j||d}W n tk
rœ   | |¡}Y nX | |¡ q`W dd„ |D ƒ}t|ƒdkrÌ| j	S t
 |¡}t|tƒ  d| j ¡ƒ}	|	S )aÜ  
        Return a (tight) bounding box of the figure in inches.

        Artists that have ``artist.set_in_layout(False)`` are not included
        in the bbox.

        Parameters
        ----------
        renderer : `.RendererBase` instance
            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
        -------
        bbox : `.BboxBase`
            containing the bounding box (in figure inches).
        Nr   )Úbbox_extra_artistsc             S   s<   g | ]4}t  |j¡rt  |j¡r|jd ks4|jd kr|‘qS )r   )ru   rv   rn   ro   )r(   rî   r"   r"   r#   r+   ì  s    z(Figure.get_tightbbox.<locals>.<listcomp>g      ð?)rX  Úget_tightbboxrn   ro   rØ   rH   r  r@   rF   rx   r   Úunionr   r   ry   r   )
r    r$  rY  Zbbr»   r*   rf   r±   Z_bboxrx   r"   r"   r#   rZ  ¿  s.    



zFigure.get_tightbboxc             C   s2   | j dkr.tjdd| d| _ | j  dddd¡ dS )z7Initialize the layoutbox for use in constrained_layout.NrÒ   )rÊ   rÌ   rË   g        g      ð?)rƒ   r©   rÐ   Zconstrain_geometry)r    r"   r"   r#   Úinit_layoutboxú  s
    

zFigure.init_layoutboxc       
      C   s†   ddl m} t d¡ | jdkr.t d¡ dS |  ¡ \}}}}| }| ¡ \}}	|| }||	 }|dkrpt	 
|¡}|||||||ƒ dS )z}
        Use ``layoutbox`` to determine pos positions within axes.

        See also `.set_constrained_layout_pads`.
        r   )Údo_constrained_layoutzExecuting constrainedlayoutNzðCalling figure.constrained_layout, but figure not setup to do constrained layout.  You either called GridSpec without the fig keyword, you are using plt.subplot, or you need to call figure or subplots with the constrained_layout=True kwarg.)Zmatplotlib._constrained_layoutr]  Ú_logÚdebugrƒ   rB   rC   r¬   r›   r©   rª   )
r    r$  r]  r¤   r¥   rW   rX   Zfigrn   ro   r"   r"   r#   r!  	  s    



z!Figure.execute_constrained_layoutçHáz®Gñ?c          
   C   sn   ddl m}m}m} || jƒ}	d|	kr0t d¡ |dkr@|| ƒ}|| | j|	|||||d}
|
rj| jf |
Ž dS )an  
        Automatically adjust subplot parameters to give specified padding.

        To exclude an artist on the axes from the bounding box calculation
        that determines the subplot parameters (i.e. legend, or annotation),
        then set `a.set_in_layout(False)` for that artist.

        Parameters
        ----------
        renderer : subclass of `~.backend_bases.RendererBase`, optional
            Defaults to the renderer for the figure.

        pad : float, optional
            Padding between the figure edge and the edges of subplots,
            as a fraction of the font size.
        h_pad, w_pad : float, optional
            Padding (height/width) between edges of adjacent subplots,
            as a fraction of the font size.  Defaults to *pad*.
        rect : tuple (left, bottom, right, top), optional
            A rectangle (left, bottom, right, top) in the normalized
            figure coordinate that the whole subplots area (including
            labels) will fit into. Default is (0, 0, 1, 1).

        See Also
        --------
        .Figure.set_tight_layout
        .pyplot.tight_layout
        r0   )rª   Úget_subplotspec_listÚget_tight_layout_figureNzcThis figure includes Axes that are not compatible with tight_layout, so results might be incorrect.)rI  r¥   r¤   r  )rŽ   rª   ra  rb  rH   rB   rC   r·   )r    r$  rI  r¥   r¤   r  rª   ra  rb  Zsubplotspec_listr¨   r"   r"   r#   rŽ   	  s    


zFigure.tight_layoutc             C   sÊ   |dkr| j }t |¡ ¡ }x¨|D ] }t d| ¡ ¡ | ¡ }| ¡ \}}}}}}	|j	 
¡ }
xd|D ]\}|j	 
¡ |
krb| ¡ }| ¡ \}}}}}}	|
dkr ||ks°|
dkrb||krb| j ||¡ qbW q"W dS )at  
        Align the ylabels of subplots in the same subplot column if label
        alignment is being done automatically (i.e. the label position is
        not manually set).

        Alignment persists for draw events after this is called.

        If a label is on the bottom, it is aligned with labels on axes that
        also have their label on the bottom and that have the same
        bottom-most subplot row.  If the label is on the top,
        it is aligned with labels on axes with the same top-most row.

        Parameters
        ----------
        axs : list of `~matplotlib.axes.Axes`
            Optional list of (or 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_labels

        Notes
        -----
        This assumes that ``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()

        Nz Working on: %srT   rV   )rH   ru   ÚasarrayÚravelr^  r_  Z
get_xlabelÚget_subplotspecÚget_rows_columnsr  Úget_label_positionr‰   Újoin)r    Úaxsr±   Ússr  r  Úrow0Úrow1Úcol0Úcol1ÚlabpoÚaxcZrowc0Zrowc1Zcolcr"   r"   r#   Úalign_xlabelsM	  s    ,


zFigure.align_xlabelsc             C   sØ   |dkr| j }t |¡ ¡ }x¶|D ]®}t d| ¡ ¡ | ¡ }| ¡ \}}}}}}	|g}
|j	 
¡ }xl|D ]d}||krh|j	 
¡ |krh| ¡ }| ¡ \}}}}}}|dkr®||ks¾|dkrh||	krh| j ||¡ qhW q"W dS )aO  
        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 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_labels

        Notes
        -----
        This assumes that ``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()

        Nz Working on: %srS   rU   )rH   ru   rc  rd  r^  r_  Z
get_ylabelre  rf  r  rg  rŠ   rh  )r    ri  r±   rj  r  r  rk  rl  rm  rn  Zsamero  rp  Zcolc0Zcolc1r"   r"   r#   Úalign_ylabels’	  s"    +


zFigure.align_ylabelsc             C   s   | j |d | j|d dS )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 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
        )ri  N)rq  rr  )r    ri  r"   r"   r#   Úalign_labels×	  s    zFigure.align_labelsc             K   s2   |  dd¡}tf ||| dœ|—Ž}| j |¡ |S )a@  
        Return a `.GridSpec` that has this figure as a parent.  This allows
        complex layout of axes in the figure.

        Parameters
        ----------
        nrows : int
            Number of rows in grid.

        ncols : int
            Number or columns in grid.

        Returns
        -------
        gridspec : `.GridSpec`

        Other Parameters
        ----------------
        *kwargs* 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   )rÍ   r   r‹   rØ   )r    r  r  r¨   rß   r  r"   r"   r#   Úadd_gridspecï	  s    &zFigure.add_gridspec)	NNNNrm   NNNN)T)T)F)r­   r®   rU   N)	r   r   NNNNNNF)NT)T)T)F)r0   r0   FFTNN)F)F)NF)NNT)NNNNNN)r0   r®   Tr0   rO  r+  )r  )N)N)Nr`  NNN)N)N)N)QrL   rM   rN   rO   rh   rl   r&   r   r“   r•   ÚpropertyrH   r˜   r   r   rŸ   r…   r£   r„   r§   r¬   r¹   rÂ   rÄ   rÈ   rÓ   rÔ   rÞ   rœ   r›   rã   rä   rå   ræ   rÕ   rç   rè   rê   rë   rì   rí   rï   rò   rù   rý   r   Zdedent_interpdr  r  r  r   r‡   rš   r	   r"  r%  rµ   r)  rÎ   r   r.  rþ   r/  r5  rB  rC  rH  rN  r·   rV  rW  rX  rZ  r\  r!  rŽ   rq  rr  rs  rt  Ú__classcell__r"   r"   )rk   r#   rd   ú   sº           
s
#
$

-a
 
U
(





$    
 2

+
K:-,  
 
3


;
 
/
E
E
rd   c       	      C   s¦   t | dƒot | ¡ }t d¡}t d¡}|rJ| jdd… \}}|| }n| }td d }t || |f¡}|td	|| žŽ  }|td
|| žŽ  }t |||¡}|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 : scalar or 2d array
        If a scalar, 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
        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       @)g      0@g      0@Nr+  zfigure.figsizer0   ç      ð?)rw  )rw  )	r°   ru   Zisscalarrâ   rÖ   r   Úminr@  rü   )	ÚargZisarrayZfigsize_minZfigsize_maxZnrZncZ	arr_ratioZ
fig_heightZnewsizer"   r"   r#   Ú	figaspect
  s    0


rz  )rd   )HrO   ZloggingZnumbersr   rB   Znumpyru   r7  r   r   r   r   r6  r   Zmatplotlib.artistrË   Zmartistr   r	   Zmatplotlib.cbookr3   r
   r   r   r#  Zmatplotlib.imager   Zmatplotlib.colorbarrN  rK  Zmatplotlib.axesr   r   r   Zmatplotlib.blocking_inputr   r   Zmatplotlib.gridspecr   Zmatplotlib.legendr)  r&  Zmatplotlib.patchesr   Zmatplotlib.projectionsr   r   Zmatplotlib.textr   r   Zmatplotlib.transformsr   r   r   r   Zmatplotlib._layoutboxrƒ   r©   Zmatplotlib.backend_basesr   Z	getLoggerrL   r^  ZinterpdrR   r$   r%   rA   rP   rd   rz  Zkwdocr"   r"   r"   r#   Ú<module>   sf   
mQ                  3O