o
    i                     @   s  d 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
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 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' e(e)Z*dZ+dZ,e+e, Z-dZ.de-e.f Z/e'j0j1e/d d	d
 Z2G dd dej3Z4G dd dej5Z6G dd dej7Z8G dd dZ9dd Z:G dd de9Z;e'<e+e,		d#ddZ=e'<e+e,ddddddZ>G dd  d e;Z?d!d" Z@dS )$a  
Colorbars are a visualization of the mapping from scalar values to colors.
In Matplotlib they are drawn into a dedicated `~.axes.Axes`.

.. note::
   Colorbars are typically created through `.Figure.colorbar` or its pyplot
   wrapper `.pyplot.colorbar`, which use `.make_axes` and `.Colorbar`
   internally.

   As an end-user, you most likely won't have to call the methods or
   instantiate the classes in this module explicitly.

:class:`ColorbarBase`
    The base class with full colorbar drawing functionality.
    It can be used as-is to make a colorbar for a given colormap;
    a mappable object (e.g., image) is not needed.

:class:`Colorbar`
    On top of `.ColorbarBase` this connects the colorbar with a
    `.ScalarMappable` such as an image or contour plot.

:class:`ColorbarPatch`
    A specialized `.Colorbar` to support hatched contour plots.

:func:`make_axes`
    Create an `~.axes.Axes` suitable for a colorbar. This functions can be
    used with figures containing a single axes or with freely placed axes.

:func:`make_axes_gridspec`
    Create a `~.SubplotBase` suitable for a colorbar. This function should
    be used for adding a colorbar to a `.GridSpec`.
    N)	docstringa  
    fraction : float, default: 0.15
        Fraction of original axes to use for colorbar.
    shrink : float, default: 1.0
        Fraction by which to multiply the size of the colorbar.
    aspect : float, default: 20
        Ratio of long to short dimensions.
a  
    pad : float, default: 0.05 if vertical, 0.15 if horizontal
        Fraction of original axes between colorbar and new image axes.
    anchor : (float, float), optional
        The anchor point of the colorbar axes.
        Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
    panchor : (float, float), or *False*, optional
        The anchor point of the colorbar parent axes. If *False*, the parent
        axes' anchor will be unchanged.
        Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.
a  

    ============  ====================================================
    Property      Description
    ============  ====================================================
    *extend*      {'neither', 'both', 'min', 'max'}
                  If not 'neither', make pointed end(s) for out-of-
                  range values.  These are set for a given colormap
                  using the colormap set_under and set_over methods.
    *extendfrac*  {*None*, 'auto', length, lengths}
                  If set to *None*, both the minimum and maximum
                  triangular colorbar extensions with have a length of
                  5% of the interior colorbar length (this is the
                  default setting). If set to 'auto', makes the
                  triangular colorbar extensions the same lengths as
                  the interior boxes (when *spacing* is set to
                  'uniform') or the same lengths as the respective
                  adjacent interior boxes (when *spacing* is set to
                  'proportional'). If a scalar, indicates the length
                  of both the minimum and maximum triangular colorbar
                  extensions as a fraction of the interior colorbar
                  length. A two-element sequence of fractions may also
                  be given, indicating the lengths of the minimum and
                  maximum colorbar extensions respectively as a
                  fraction of the interior colorbar length.
    *extendrect*  bool
                  If *False* the minimum and maximum colorbar extensions
                  will be triangular (the default). If *True* the
                  extensions will be rectangular.
    *spacing*     {'uniform', 'proportional'}
                  Uniform spacing gives each discrete color the same
                  space; proportional makes the space proportional to
                  the data interval.
    *ticks*       *None* or list of ticks or Locator
                  If None, ticks are determined automatically from the
                  input.
    *format*      None or str or Formatter
                  If None, `~.ticker.ScalarFormatter` is used.
                  If a format string is given, e.g., '%.3f', that is used.
                  An alternative `~.ticker.Formatter` may be given instead.
    *drawedges*   bool
                  Whether to draw lines at color boundaries.
    *label*       str
                  The label on the colorbar's long axis.
    ============  ====================================================

    The following will probably be useful only in the context of
    indexed colors (that is, when the mappable has norm=NoNorm()),
    or other unusual circumstances.

    ============   ===================================================
    Property       Description
    ============   ===================================================
    *boundaries*   None or a sequence
    *values*       None or a sequence which must be of length 1 less
                   than the sequence of *boundaries*. For each region
                   delimited by adjacent entries in *boundaries*, the
                   color mapped to the corresponding value in values
                   will be used.
    ============   ===================================================

a}
  

Add a colorbar to a plot.

Function signatures for the :mod:`~matplotlib.pyplot` interface; all
but the first are also method signatures for the `~.Figure.colorbar` method::

  colorbar(**kwargs)
  colorbar(mappable, **kwargs)
  colorbar(mappable, cax=cax, **kwargs)
  colorbar(mappable, ax=ax, **kwargs)

Parameters
----------
mappable
    The `matplotlib.cm.ScalarMappable` (i.e., `~matplotlib.image.AxesImage`,
    `~matplotlib.contour.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.

ax : `~matplotlib.axes.Axes`, list of Axes, optional
    Parent axes from which space for a new colorbar axes will be stolen.
    If a list of axes is given they will all be resized to make room for the
    colorbar axes.

use_gridspec : bool, optional
    If *cax* is ``None``, a new *cax* is created as an instance of Axes.  If
    *ax* is an instance of Subplot and *use_gridspec* is ``True``, *cax* is
    created as an instance of Subplot using the :mod:`~.gridspec` module.

Returns
-------
colorbar : `~matplotlib.colorbar.Colorbar`
    See also its base class, `~matplotlib.colorbar.ColorbarBase`.

Notes
-----
Additional keyword arguments are of two kinds:

  axes properties:
%s
  colorbar properties:
%s

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* kwargs are ignored.

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

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

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

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

)colorbar_docc                  O   s   t d d S )Nz,Use the colorbar set_ticks() method instead.)cbook_warn_external)argskw r   N/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/matplotlib/colorbar.py_set_ticks_on_axis_warn   s   r
   c                       ,   e Zd ZdZ fddZ fddZ  ZS )_ColorbarAutoLocatora  
    AutoLocator for Colorbar

    This locator is just a `.MaxNLocator` except the min and max are
    clipped by the norm's min and max (i.e. vmin/vmax from the
    image/pcolor/contour object).  This is necessary so ticks don't
    extrude into the "extend regions".
    c                    s&   || _ d}g d}t j||d dS )z
        This ticker needs to know the *colorbar* so that it can access
        its *vmin* and *vmax*.  Otherwise it is the same as
        `~.ticker.AutoLocator`.
        auto)      g      @   
   )nbinsstepsN	_colorbarsuper__init__)selfcolorbarr   r   	__class__r   r	   r      s   z_ColorbarAutoLocator.__init__c                    sh   ||kr	||}}t || jjj}t|| jjj}t ||}|| d }|||| k||| k@  S N绽|=)maxr   normvminminvmaxr   tick_valuesr   r    r"   ticksrtolr   r   r	   r#      s   
z _ColorbarAutoLocator.tick_values__name__
__module____qualname____doc__r   r#   __classcell__r   r   r   r	   r      s    	r   c                       s.   e Zd ZdZd fdd	Z fddZ  ZS )_ColorbarAutoMinorLocatora*  
    AutoMinorLocator for Colorbar

    This locator is just a `.AutoMinorLocator` except the min and max are
    clipped by the norm's min and max (i.e. vmin/vmax from the
    image/pcolor/contour object).  This is necessary so that the minorticks
    don't extrude into the "extend regions".
    Nc                    s   || _ || _t jdd dS )zo
        This ticker needs to know the *colorbar* so that it can access
        its *vmin* and *vmax*.
        N)n)r   ndivsr   r   )r   r   r.   r   r   r	   r     s   z"_ColorbarAutoMinorLocator.__init__c                    sF   | j jj}| j jj}t  }|| d }|||| k||| k@  S r   )r   r   r    r"   r   __call__r$   r   r   r	   r0     s
   


z"_ColorbarAutoMinorLocator.__call__N)r(   r)   r*   r+   r   r0   r,   r   r   r   r	   r-     s    		r-   c                       r   )_ColorbarLogLocatora  
    LogLocator for Colorbarbar

    This locator is just a `.LogLocator` except the min and max are
    clipped by the norm's min and max (i.e. vmin/vmax from the
    image/pcolor/contour object).  This is necessary so ticks don't
    extrude into the "extend regions".

    c                    s   || _ t j|i | dS )z
        This ticker needs to know the *colorbar* so that it can access
        its *vmin* and *vmax*.  Otherwise it is the same as
        `~.ticker.LogLocator`.  The ``*args`` and ``**kwargs`` are the
        same as `~.ticker.LogLocator`.
        Nr   )r   r   r   kwargsr   r   r	   r   +  s   z_ColorbarLogLocator.__init__c                    s   ||kr	||}}t || jjj}t|| jjj}t ||}t	|t	| d }|t	|t	|| kt	|t	|| k@  }|S r   )
r   r   r   r    r!   r"   r   r#   nplog10r$   r   r   r	   r#   5  s   
z_ColorbarLogLocator.tick_valuesr'   r   r   r   r	   r2   !  s    	
r2   c                   @   sf  e Zd ZdZdZedd														
				dPddZdd Zdd Z	dd Z
eddd Zdd Zdd Zdd Zdd Zdd ZdQd d!ZdRd"d#ZdQd$d%Zd&d' Zd(d) Zd*d+ Zdd,d-d.Zd/d0 Zd1d2 Zd3d4 ZdQd5d6Zd7d8 ZdSd9d:Zd;d< Zd=d> Z d?d@ Z!dTdBdCZ"dDdE Z#dFdG Z$dHdI Z%dJdK Z&dLdM Z'dNdO Z(dS )UColorbarBaseak  
    Draw a colorbar in an existing axes.

    There are only some rare cases in which you would work directly with a
    `.ColorbarBase` as an end-user. Typically, colorbars are used
    with `.ScalarMappable`\s such as an `.AxesImage` generated via
    `~.axes.Axes.imshow`. For these cases you will use `.Colorbar` and
    likely create it via `.pyplot.colorbar` or `.Figure.colorbar`.

    The main application of using a `.ColorbarBase` explicitly is drawing
    colorbars that are not associated with other elements in the figure, e.g.
    when showing a colormap by itself.

    If the *cmap* kwarg is given but *boundaries* and *values* are left as
    None, then the colormap will be displayed on a 0-1 scale. To show the
    under- and over-value colors, specify the *norm* as::

        norm=colors.Normalize(clip=False)

    To show the colors versus index instead of on the 0-1 scale,
    use::

        norm=colors.NoNorm()

    Useful public methods are :meth:`set_label` and :meth:`add_lines`.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The `~.axes.Axes` instance in which the colorbar is drawn.
    lines : list
        A list of `.LineCollection` if lines were drawn, otherwise
        an empty list.
    dividers : `.LineCollection`
        A LineCollection if *drawedges* is ``True``, otherwise ``None``.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The `~.axes.Axes` instance in which the colorbar is drawn.
    cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
        The colormap to use.
    norm : `~matplotlib.colors.Normalize`

    alpha : float
        The colorbar transparency between 0 (transparent) and 1 (opaque).

    values

    boundaries

    orientation : {'vertical', 'horizontal'}

    ticklocation : {'auto', 'left', 'right', 'top', 'bottom'}

    extend : {'neither', 'both', 'min', 'max'}

    spacing : {'uniform', 'proportional'}

    ticks : `~matplotlib.ticker.Locator` or array-like of float

    format : str or `~matplotlib.ticker.Formatter`

    drawedges : bool

    filled : bool

    extendfrac

    extendrec

    label : str
    2   3.3cmapNverticalr   uniformFT c                 C   sB  t jtjd g|d t jddg|d t jg d|d t jddg|
d	 || _t |_|_|j	d
d
d |d u r=t
 }|d u rEt }|	d u rTt|drR|j}	nd}	|| _|| _|| _|| _|| _|	| _t jtdd tddtdd tddd|	d| _|
| _|| _|| _|| _|| _|| _d | _g | _tj t!"dt#j$d dt#j$d ddd| _%|&| j% | j%j	d d d tj t!"dt#j$d ddd| _'|&| j' d | _(d | _)d | _*d | _+d | _,|dkr|dkrdnd }|| _-| .| | /  t!0|rt1j2|t3|d!| _)n|| _)t4|t5rt16|| _*n|| _*| 7  d S )"N)r9   r:   
horizontal)orientation)r   leftrighttopbottom)ticklocationr;   proportional)spacingF)frame_onnavigateextendneitherr   r   )rI   bothr!   r   rH   r   r   axes.edgecolornoneaxes.linewidthTr   	edgecolor	facecolor	linewidthclosedzorderclip_box	clip_pathaxes.facecolor{Gz?colorrT   rV   r   rB   r@   r   )8r   _check_isinstancecolorsColormap_check_in_listaxr
   
set_xticks
set_ytickssetcmget_cmap	NormalizehasattrrH   alphar9   r   values
boundaries_check_getitemslice_insiderE   r>   	drawedgesfilled
extendfrac
extendrectsolidslinesmpatchesPolygonr4   emptymplrcParamsoutline
add_artistpatchdividerslocator	formatter_manual_tick_data_values_ColorbarBase__scalerC   	set_label_reset_locator_formatter_scaleiterabletickerFixedLocatorlen
isinstancestrFormatStrFormatterdraw_all)r   rc   r9   r   rk   rl   rm   r>   rC   rH   rE   r%   formatrq   rr   rs   rt   labelr   r   r	   r     s   


zColorbarBase.__init__c                 C   
   | j dv S )z-Return whether the lower limit is open ended.rK   r!   rL   r   r   r   r	   _extend_lower     
zColorbarBase._extend_lowerc                 C   r   )z-Return whether the upper limit is open ended.rK   r   rL   r   r   r   r	   _extend_upper  r   zColorbarBase._extend_upperc           	      C   s   |    |   |  \}}| jddtjf }|   | ||}|jdd\}}|j	dd\}}| j
j||f||fd | j| | j| |   | jrZ| ||| dS dS )zs
        Calculate any free parameters based on the current cmap and norm,
        and do all the drawing.
        Nr   axis)xlimylim)_process_values_find_range_mesh_valuesr4   newaxis_config_axis_outliner!   r   rc   rf   r|   set_xyr~   update_ticksrr   _add_solids)	r   XYCxyxminyminxmaxymaxr   r   r	   r     s   zColorbarBase.draw_allc                 C   s   |    d S r1   )r   r   r   r   r	   config_axis  s   zColorbarBase.config_axisc                 C   s   | j }| jdkr|j|j}}tjd r|   n|j|j}}tjd r)|   |j| j| jd |	g  |j	g dd | 
  dS )zSet up long and short axis.r:   zytick.minor.visiblezxtick.minor.visible)label_positionticks_positionT)minorN)rc   r>   yaxisxaxisrz   r{   minorticks_onrf   rC   	set_ticks
_set_label)r   rc   	long_axis
short_axisr   r   r	   r     s   



zColorbarBase._config_axisc                 C   sh  | j }| j}|du r|| jdu rot| jtjr+t| j}dt	|d  }t
j|dd}nQt| jtjr>| jj}t
j|dd}n>t| jtjrJt| }n2t| jtjr`t
jtdd| jjdd}ntjd rjt
 }nt| }n| j| j }t
j|dd}|du rt| jtjrt
 }nt| jtjrt
j| jjd	}nt
 }n| j}|| _ || _td
| ||fS )a  
        Return the ``locator`` and ``formatter`` of the colorbar.

        If they have not been defined (i.e. are *None*), suitable formatter
        and locator instances will be created, attached to the respective
        attributes and returned.
        Nr   r   r   )baseoffsetr^   )subs	linthreshr   z_internal.classic_mode)r   zlocator: %r)r   r   rm   r   r   r`   NoNormr   r   intr   IndexLocatorBoundaryNormr   LogNormr2   
SymLogNormSymmetricalLogLocatorr4   aranger   rz   r{   MaxNLocatorr   _boundariesrp   LogFormatterSciNotationScalarFormatter_logdebug)r   r   r   nvr   br   r   r	   _get_ticker_locator_formatter&  sJ   








z*ColorbarBase._get_ticker_locator_formatterc                 C   s0   | j duo	| jdk}t| jtjtjfv o| S )z
        Return if we should use an adjustable tick locator or a fixed
        one.  (check is used twice so factored out here...)
        Nr;   )rm   rE   typer   r`   ri   r   )r   
contouringr   r   r	   _use_auto_colorbar_locator[  s   z'ColorbarBase._use_auto_colorbar_locatorc                 C   s   d| _ d| _t| jtjr"| jd | jd | 	  d| _
dS | jd | jd t| jtju r;d| _
dS d| _
dS )z
        Reset the locator et al to defaults.  Any user-hardcoded changes
        need to be re-entered if this gets called (either at init, or when
        the mappable normal gets changed: Colorbar.update_normal)
        Nloglinearmanual)r   r   r   r   r`   r   rc   
set_xscale
set_yscaler   r   r   ri   r   r   r   r	   r   d  s   


z+ColorbarBase._reset_locator_formatter_scalec                 C   s   | j }|  \}}| jdkr|jn|j}|  r*td| || |	| dS td | 
||\}}}|| || | | dS )z
        Force the update of the ticks and ticklabels. This must be
        called whenever the tick locator and/or tick formatter changes.
        r:   z*Using auto colorbar locator %r on colorbarzUsing fixed locator on colorbarN)rc   r   r>   r   r   r   r   r   set_major_locatorset_major_formatter_tickerr   set_ticklabelsget_major_formatterset_offset_string)r   rc   r   r   r   r%   
ticklabelsoffset_stringr   r   r	   r   {  s   



zColorbarBase.update_ticksc                 C   s<   t |rtj|t|d| _n|| _|r|   d| _dS )a  
        Set tick locations.

        Parameters
        ----------
        ticks : array-like or `~matplotlib.ticker.Locator` or None
            The tick positions can be hard-coded by an array of values; or
            they can be defined by a `.Locator`. Setting to *None* reverts
            to using a default locator.

        update_ticks : bool, default: True
            If True, tick locations are updated immediately.  If False, the
            user has to call `update_ticks` later to update the ticks.

        r^   TN)r4   r   r   r   r   r   r   stale)r   r%   r   r   r   r	   r     s   

zColorbarBase.set_ticksc                 C   s4   | j du r| j}| jdkr|jn|j}| S | j S )z*Return the x ticks as a list of locations.Nr:   )r   rc   r>   r   r   get_majorticklocs)r   r   rc   r   r   r   r	   	get_ticks  s   
zColorbarBase.get_ticksc                 C   s<   t | jtjrt|| _|r|   ntd d| _	dS )z
        Set tick labels.

        Tick labels are updated immediately unless *update_ticks* is *False*,
        in which case one should call `.update_ticks` explicitly.
        z"set_ticks() must have been called.TN)
r   r   r   r   FixedFormatterr   r   r   r   r   )r   r   r   r   r   r	   r     s   

zColorbarBase.set_ticklabelsc                 C   s`   | j }| jdkr|jn|j}| dkr'|t| ddd |t	  dS |t
|  dS )zn
        Turn the minor ticks of the colorbar on without extruding
        into the "extend regions".
        r:   r   g      $@r   )r   r   N)rc   r>   r   r   	get_scaleset_minor_locatorr2   set_minor_formatterr   r   r-   r   rc   r   r   r   r	   r     s   
zColorbarBase.minorticks_onc                 C   s.   | j }| jdkr|jn|j}|t  dS )z)Turn the minor ticks of the colorbar off.r:   N)rc   r>   r   r   r   r   NullLocatorr   r   r   r	   minorticks_off  s   zColorbarBase.minorticks_offc                 C   sF   | j dkr| jj| jfi | j n| jj| jfi | j d| _d S )Nr:   T)r>   rc   
set_ylabel_label_labelkw
set_xlabelr   r   r   r   r	   r     s   

zColorbarBase._set_labellocc                   s   | j dkrdnd}|ddg}t fdd|D r(|dur%td	| d
d}n|du r3tjd|  }| j dkr@tjd|d ntjd|d |dv rTd |< d d< n|dv r`d |< d d< || _ | _| 	  dS )z-Add a label to the long axis of the colorbar.r:   yxhorizontalalignmenthac                    s   g | ]}| v qS r   r   ).0kr3   r   r	   
<listcomp>      z*ColorbarBase.set_label.<locals>.<listcomp>NzYSpecifying *loc* is disallowed when any of its corresponding low level keyword arguments z are also suppliedcenterz%saxis.labellocation)rB   r   rA   r   )r?   r   r@   )r@   rA         ?r@   )r?   rB           r?   )
r>   any	TypeErrorrz   r{   r   rb   r   r   r   )r   r   r   r3   _pos_xy_protected_kwr   r   r	   r     s,   



zColorbarBase.set_labelc              	   C   s   |j d }dd|d |d d| d d| d |d |dg	}|jd| }|jd| }| jdkr:t||gS t||gS )zo
        Return *x*, *y* arrays of colorbar bounding polygon,
        taking orientation into account.
        r   r   r   rJ   r=   )shapeTreshaper>   r4   column_stack)r   r   r   Niir   r   r   r   r	   r     s   
2
zColorbarBase._outlinec                    sP    j d }| jdkr fddtd|d D S  fddtd|d D S )z;Return the separator line segments; helper for _add_solids.r   r:   c                    s"   g | ]}t t | | qS r   listzipr   ir   r   r   r	   r        " z'ColorbarBase._edges.<locals>.<listcomp>r   c                    s"   g | ]}t t|  | qS r   r  r  r  r   r	   r     r	  )r   r>   range)r   r   r   r  r   r  r	   _edges  s   

zColorbarBase._edgesc                 C   s.  |j d |j d kr|dd }| jdkr|||f}nt|t|t|f}t| j| j| jdd}t	d | j
j|i |dd	i}| jdurP| j  || _| jdur`| j  d| _| jrd
tjd  f}tj| ||tjd f|d| _| j
| j dS t| j| jkr| jd dS dS )zd
        Draw the colors using `~.axes.Axes.pcolormesh`;
        optionally add separators.
        r   NrJ   r:   None)r9   r   rk   
edgecolorszSetting pcolormeshshadingflat      ?rP   rN   r`   
linewidthsT)r   r>   r4   	transposedictr9   r   rk   r   r   rc   
pcolormeshru   remover   rq   rz   r{   collectionsLineCollectionr  add_collectionr   _yn_rasterizeset_rasterized)r   r   r   r   r   r   colr  r   r   r	   r     s:   







zColorbarBase._add_solidsc                 C   s,  |  |}| jd | jd  d }|| jd | k || jd | k@ }|| }t|r3t|| }t|r?t|| }t| jd | jd g|\}}	| jdkr^tj||	gdd}
n	tj|	|gdd}
tj	|
|d}|r| j
r| j
D ]}|  qvg | _
| j
| || | j| d| _dS )	aQ  
        Draw lines on the colorbar.

        The lines are appended to the list :attr:`lines`.

        Parameters
        ----------
        levels : array-like
            The positions of the lines.
        colors : color or list of colors
            Either a single color applying to all lines or one color value for
            each line.
        linewidths : float or array-like
            Either a single linewidth applying to all lines or one linewidth
            for each line.
        erase : bool, default: True
            Whether to remove any previously added lines.
        rJ   r   r   r:   r   )r  TN)_locater  r4   r   asarraymeshgridr>   stackr  r  rv   r  append	set_colorrc   r  r   )r   levelsr`   r  eraser   r&   igoodr   r   r   r  lcr   r   r	   	add_lines6  s*   
$

 





zColorbarBase.add_linesc           	      C   s0  t | jtjr| jdu r| jd | jd f}n| j| jf}|j|d d |j|d d |j	|  |j
|  |j	|  |j
|  t| }t |tjrfd}|||d d|  k||d d|  k@  }n|d |d  d }|||d | k||d | k@  }|| _| |}||}| }|||fS )z
        Return the sequence of ticks (colorbar data locations),
        ticklabels (strings), and the corresponding offset string.
        Nr   rJ   )minposr   r   )r   r   r`   r   rm   r   r    r"   create_dummy_axisset_view_intervalset_data_intervalr4   arrayr   
LogLocatorr   r  format_ticks
get_offset)	r   r   r   intvr   epsr%   r   r   r   r   r	   r   a  s(   



.$


zColorbarBase._tickerc                 C   s  |du r| j }|durEtj|td| _| jdu r<d| jdd | jdd   | _t| jt	j
r:| jd tj| _dS t| j| _dS | jdurt| j| _| j du rtt| jd }d| jdd | jdd   |dd< d|d  |d  |d	< d|d
  |d  |d< || _dS t| j | _dS t| jt	j
r| | jjd | jj d }tjt|d tjd}tj| jjtjd|| j< |  rd|d	< |  r| jj|d< || _|| _dS t| jt	jrQt| jj }|  r|d	 d g| }|  r||d d g }t|}tt|d }| jj }d|dd |dd   || j< |  r<|d	 d |d	< |  rI|d d |d< || _|| _dS | j s_d	| j_d| j_tj| jj| jjdd\| j_| j_| j| | jjd }t| jt	jt	j fr|  rd|d	  |d	< |  rd|d  |d< n|  r|d	 d |d	< |  r|d d |d< | !| dS )z
        Set the :attr:`_boundaries` and :attr:`_values` attributes
        based on the input boundaries and values.  Input boundaries
        can be *self.boundaries* or the argument *b*.
        N)dtyper  rJ   r   gh㈵>g       @r   r   皙?)expanderg?g?)"rm   r4   r  floatr   rl   r   r   r   r`   r   astypeint16r-  zerosr   
_uniform_yr9   r  r   rp   r   r   r   r  scaledr    r"   mtransformsnonsingularinverse	PowerNormr   r   )r   r   vbir   r   r	   r   ~  s   


(

"





zColorbarBase._process_valuesc                 C   s$   | j | j }|d | _|d | _dS )z
        Set :attr:`vmin` and :attr:`vmax` attributes to the first and
        last boundary excluding extended end boundaries.
        r   rJ   N)r   rp   r    r"   )r   r   r   r   r	   r     s   
zColorbarBase._find_rangec                 C   s6   t | j}| jdkr|d8 }|S | jdv r|d8 }|S )z9Return the number of boundaries excluding end extensions.rK   r   r!   r   r   )r   r   rH   )r   nbr   r   r	   
_central_N  s   


zColorbarBase._central_Nc                 C   s8   | j jd }| jdkr|d7 }|S | jdv r|d7 }|S )ze
        Based on the colormap and extend variable, return the
        number of boundaries.
        r   rK   r   rD  )r9   r  rH   )r   r  r   r   r	   _extended_N  s   

zColorbarBase._extended_N皙?c              
   C   s   t ||g}t|tr tjdg| d ||g|dd< |S |durKz||dd< t | r5t	 W |S  t
t	fyJ } zt	d|d}~ww |S )z
        Return the lengths of colorbar extensions.

        This is a helper method for _uniform_y and _proportional_y.
        r   )rs   Nzinvalid value for extendfrac)r4   r-  r   r   r   rb   lowerisnanr   
ValueErrorr   )r   fracautominautomaxdefaultextendlengtherrr   r   r	   _get_extension_lengths  s"   

z#ColorbarBase._get_extension_lengthsc                 C   s   | j dkrtdd|}|S d|d   }}| j| j||dd}| j dkr>t|d d	}d
|d  |d< d|d  |d< n&| j dkrTt|d d	}d
|d  |d< nt|d d	}d|d  |d< tdd||| j< |S )zv
        Return colorbar data coordinates for *N* uniformly
        spaced boundaries, plus ends if required.
        rI   r   r   r   rH  rO  rK   r   dr   rJ   r!   )rH   r4   linspacerR  rs   r;  rp   )r   r  r   rM  rN  rP  r   r   r	   r<  
  s&   


zColorbarBase._uniform_yc                 C   s  t | jtjr| j| jd  }|| jd | jd   }n| | j }tj|tj	}| j
dkrN|d |d  }|d |d  | }|d |d  | }nC| j
dkrp|d |d  }|d |d  | }|d |d  | }n!| j
d	kr|d |d  }|d |d  | }|d |d  | }| j
d
v r| j| j||dd}| j
dv rd|d  |d< | j
dv rd|d  |d< || j }t|d |d }tj||tj	|| j< |S )zi
        Return colorbar data coordinates for the boundaries of
        a proportional colorbar.
        r   rJ   r!   r   r   r4  r   r5  rK   )rK   r!   r   rH  rS  r   r   r   r   )r   r   r`   r   r   copyr4   marr   nanrH   rR  rs   rp   ri   )r   r   clenrM  rN  rP  yir   r   r   r	   _proportional_y#  s<   






zColorbarBase._proportional_yc                 C   s  t  | j}| j|_| j|_tddg}| jdkr"| |  }n| 	 }tdg}| j
dkrA||}||}||}n| j| j }|| | j }|| | j }|| | j }|| _t||\}}|  rv| jsv||dddf< |  r| js||dddf< ||fS )	a  
        Return ``(X, Y)``, the coordinate arrays for the colorbar pcolormesh.
        These are suitable for a vertical colorbar; swapping and transposition
        for a horizontal colorbar are done outside this function.

        These are scaled between vmin and vmax.
        r   r   r;   r  r   r   NrJ   )rV  r   r    r"   r4   r-  rE   r<  rF  r[  r   r@  r  r   r   rt   r   )r   r   r   r   xmiddvr   r   r   r   r	   r   J  s.   



zColorbarBase._meshc                 C   s   t | jtjtjfr| j}|}n| j| jdd }| j|dd }|}| j}|d |d kr<|dd }|dd }|d |d krP|dd }|dd }t	|||}|S )zq
        Given a set of color data values, return their
        corresponding colorbar data coordinates.
        F)clipr   r   NrJ   r4  )
r   r   r`   r   r   r   rr   r  r4   interp)r   r   r   xnbuniqueyuniquezr   r   r	   r  r  s   zColorbarBase._locatec                 C   s
   || _ dS )z<Set the transparency between 0 (transparent) and 1 (opaque).Nrk   )r   rk   r   r   r	   	set_alpha  r   zColorbarBase.set_alphac                 C   s   | j   dS )z%Remove this colorbar from the figure.N)rc   r  r   r   r   r	   r    s   zColorbarBase.remove)NNNNNr:   r   Nr;   NNFTNFr<   T)Fr1   )rH  ))r(   r)   r*   r+   r  r   _make_keyword_onlyr   r   r   r   
deprecatedr   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r(  r   r   r   rF  rG  rR  r<  r[  r   r  re  r  r   r   r   r	   r6   A  sl    J
^
5	




$+
U		
'(r6   c                 K   s<   |  D ]\}}|| v rtjdd|dd || |< qdS )zR
    Update dict *d* with entries in *kwargs*, which must be absent from *d*.
    r8   zThe z parameter to Colorbar has no effect because it is overridden by the mappable; it is deprecated since %(since)s and will be removed %(removal)s.)messageN)itemsr   warn_deprecated)rT  r3   r   rB  r   r   r	   _add_disjoint_kwargs  s   
rl  c                   @   s^   e Zd ZdZdd Zejddddd Zdd
dZdd Z	ejddddd Z
dd ZdS )Colorbara3  
    This class connects a `ColorbarBase` to a `~.cm.ScalarMappable`
    such as an `~.image.AxesImage` generated via `~.axes.Axes.imshow`.

    .. note::
        This class is not intended to be instantiated directly; instead, use
        `.Figure.colorbar` or `.pyplot.colorbar` to create a colorbar.
    c                 K   s   |  d ur
|  || _t||j|jd t|tjrP|}t||	 |j
|j|j|jd |dtj|jdd tj| |fi | |jsN| | d S d S t|jdddura|d|jj t|tjrot||	 d	 tj| |fi | d S )
N)r9   r   )rk   rm   rl   rH   rr   r%   r   r^   colorbar_extendFrH   rd  )	get_arrayautoscale_Nonemappablerl  r9   r   r   contour
ContourSet	get_alpha_levelscvaluesrH   rr   
setdefaultr   r   r$  r6   r   r(  getattrrn  martistArtist)r   rc   rq  r3   csr   r   r	   r     s4   zColorbar.__init__r8   update_normal)alternativec                 C   s   t d | | dS )z
        Update this colorbar to match the mappable's properties.

        Typically this is automatically registered as an event handler
        by :func:`colorbar_factory` and should not be called manually.
        zcolorbar mappable changedN)r   r   r|  )r   rq  r   r   r	   on_mappable_changed  s   
zColorbar.on_mappable_changedTc                 C   sT   t |tjr	|jrtddd |jD }dd |jD }tj| |j	|||d dS )av  
        Add the lines from a non-filled `~.contour.ContourSet` to the colorbar.

        Parameters
        ----------
        CS : `~.contour.ContourSet`
            The line positions are taken from the ContourSet levels. The
            ContourSet must not be filled.
        erase : bool, default: True
            Whether to remove any previously added lines.
        z+add_lines is only for a ContourSet of linesc                 S      g | ]}|d  qS r   r   )r   cr   r   r	   r     r   z&Colorbar.add_lines.<locals>.<listcomp>c                 S   r  r  r   )r   tr   r   r	   r     r   )r%  N)
r   rr  rs  rr   rK  tcolorstlinewidthsr6   r(  r$  )r   CSr%  r  r  r   r   r	   r(    s   
zColorbar.add_linesc                 C   s   t d|j| j || _| |  |j| _|j| jkr%|j| _|   |   t	| jt
jr;| j}|js;| | d| _dS )a
  
        Update solid patches, lines, etc.

        This is meant to be called when the norm of the image or contour plot
        to which this colorbar belongs changes.

        If the norm on the mappable is different than before, this resets the
        locator and formatter for the axis, so if these have been customized,
        they will need to be customized again.  However, if the norm only
        changes values of *vmin*, *vmax* or *cmap* then the old formatter
        and locator will be preserved.
        zcolorbar update normal %r %rTN)r   r   r   rq  re  rt  r9   r   r   r   rr  rs  rr   r(  r   r   rq  r  r   r   r	   r|    s   

zColorbar.update_normalc                 C   s   | j   d| _d| _tjtdtj	d dtj	d ddd| _
| j | j
 | j
jddd	 tjtdtj	d
 ddd| _| j | j d| _g | _d| _| | |   t| jtjrl| j}|jsn| | dS dS dS )a  
        Destroy and rebuild the colorbar.  This is
        intended to become obsolete, and will probably be
        deprecated and then removed.  It is not called when
        the pyplot.colorbar function or the Figure.colorbar
        method are used to create the colorbar.
        NrM   rN   rO   rP   Tr   rQ   rW   rZ   r[   rJ   r\   )rc   clar   r   rw   rx   r4   ry   rz   r{   r|   r}   rf   r~   ru   rv   r   r|  r   r   rq  rr  rs  rr   r(  r  r   r   r	   update_bruteforce  s4   


zColorbar.update_bruteforcec                 C   s   t |  | jj| jj d| j_d| j_z| jj}W n
 ty&   Y dS w z|	 
 }| }W n tyH   |jdd}|| Y dS w || dS )z
        Remove this colorbar from the figure.

        If the colorbar was created with ``use_gridspec=True`` the previous
        gridspec is restored.
        NToriginal)r6   r  rq  callbacksSM
disconnectcolorbar_cidr   axesAttributeErrorget_subplotspecget_gridspecget_topmost_subplotspecget_position_set_positionset_subplotspec)r   rc   gssubplotspecposr   r   r	   r  <  s"   
zColorbar.removeNrf  )r(   r)   r*   r+   r   r   rh  r~  r(  r|  r  r  r   r   r   r	   rm    s    	



,rm  333333?r      c                    s  g d}|dur|durt dd||du r |du r d}|du r,|dkr*dnd}tj||d d	d
dddd
d	dddddddddddddd}|| }	|	d |d< ||d< |d|	d }
|d|	d }t| }t| 	 } z| d 
  }|jdu}W n ty   d}Y nw |	d }|rd}|d|}| d   t fdd| D stdtjdd | D }|}|dv r|d kr|||| \}}}n|d!| | d!| \}}}|d"||
|}n.|dkr|||| \}}}n|d!| | d!| \}}}||d"|
|}d"| }t||}| D ] }||jd#d$}t|}|| |durF|| q' j|d%d&}|s_d}d}|j||
d'd( n!|st| d }tj ||||||d)\}}nt!| |||||\}}||_||_"||fS )*a  
    Create an `~.axes.Axes` suitable for a colorbar.

    The axes is placed in the figure of the *parents* axes, by resizing and
    repositioning *parents*.

    Parameters
    ----------
    parents : `~.axes.Axes` or list of `~.axes.Axes`
        The Axes to use as parents for placing the colorbar.

    location : None or {'left', 'right', 'top', 'bottom'}
        The position, relative to *parents*, where the colorbar axes
        should be created. If None, the value will either come from the
        given ``orientation``, else it will default to 'right'.

    orientation : None or {'vertical', 'horizontal'}
        The orientation of the colorbar. Typically, this keyword shouldn't
        be used, as it can be derived from the ``location`` keyword.

    %s

    Returns
    -------
    cax : `~.axes.Axes`
        The child axes.
    kw : dict
        The reduced keyword dictionary to be passed when creating the colorbar
        instance.

    Other Parameters
    ----------------
    %s
    )r?   r@   rA   rB   Nz[position and orientation are mutually exclusive. Consider setting the position to any of {}z, r@   r:   rB   )locationr   r  r   r  r6  )anchorpanchorpadr>   rH  r  r   r  r   r=   r  r>   rC   r  r  r   Fr  g{Gz?c                 3   s    | ]	} |  u V  qd S r1   )
get_figurer   rc   figr   r	   	<genexpr>  s    zmake_axes.<locals>.<genexpr>zJUnable to create a colorbar axes as not all parents share the same figure.c                 S   s   g | ]
}|j d d qS )Tr  )r  frozenr  r   r   r	   r     s    zmake_axes.<locals>.<listcomp>)r?   r@   r?   r   r   Tr  
<colorbar>r   boxr  
adjustable)r  )#r   r   joinr   rb   popr4   r   
atleast_1dravelr  r  
_layoutboxr  r  allrK  r>  BboxunionsplitxshrunkanchoredsplityBboxTransform	transformr  r  
set_anchoradd_axes
set_aspectconstrained_layoutlayoutcolorbarsinglelayoutcolorbargridspec_poslayoutbox)parentsr  r>   fractionshrinkaspectr   	locationsdefault_location_settingsloc_settingsr  parent_anchorparents_iterabler  using_constrained_layoutpad0r  parents_bboxpbpbcb_pb1shrinking_transrc   new_posncaxlblbposr   r  r	   	make_axesY  s   %





r  )r  r  r  c                K   sp  | dd}d|d< d| }d| d }|||g}|   }	t|	j tj}
|dkrY|dd}d	| d|  }|
dd	|  ||| |gd
}	|
dd|	d d|d}d}d}n0|dd}d	| d|  }|
d	d|  ||| |gd}	|
dd|	d d|d
}d| }d}d}| 	|	d  | 
  | | j | | |  }|j|d dd}|j||dd ||fS )a  
    Create a `~.SubplotBase` suitable for a colorbar.

    The axes is placed in the figure of the *parent* axes, by resizing and
    repositioning *parent*.

    This function is similar to `.make_axes`. Primary differences are

    - `.make_axes_gridspec` only handles the *orientation* keyword
      and cannot handle the *location* keyword.

    - `.make_axes_gridspec` should only be used with a `.SubplotBase` parent.

    - `.make_axes` creates an `~.axes.Axes`; `.make_axes_gridspec` creates a
      `.SubplotBase`.

    - `.make_axes` updates the position of the parent.  `.make_axes_gridspec`
      replaces the ``grid_spec`` attribute of the parent with a new one.

    While this function is meant to be compatible with `.make_axes`,
    there could be some minor differences.

    Parameters
    ----------
    parent : `~.axes.Axes`
        The Axes to use as parent for placing the colorbar.

    %s

    Returns
    -------
    cax : `~.axes.SubplotBase`
        The child axes.
    kw : dict
        The reduced keyword dictionary to be passed when creating the colorbar
        instance.

    Other Parameters
    ----------------
    orientation : {'vertical', 'horizontal'}, default: 'vertical'
        The orientation of the colorbar.

    %s
    r>   r:   r   rC   r   r  r  rH  r   )subplot_specwspacewidth_ratios   r   )r  hspaceheight_ratiosr  r  r  r  r  r   r  r  r  r  )rw  r  r  	layoutboxnonetreer  gridspecGridSpecFromSubplotSpecr  r  update_paramsr  figboxr  r  add_subplotr  )parentr  r  r  r   r>   x1pad_s	wh_ratiosr  gs_from_subplotspecr  wh_spacegs2r  r  r  r  r   r   r	   make_axes_gridspec  s\   /



r  c                   @   s    e Zd ZdZdd Zdd ZdS )ColorbarPatcha
  
    A Colorbar that uses a list of `~.patches.Patch` instances rather than the
    default `~.collections.PatchCollection` created by `~.axes.Axes.pcolor`,
    because the latter does not allow the hatch pattern to vary among the
    members of the collection.
    c                 K   s    g | _ tj| ||fi | d S r1   )solids_patchesrm  r   )r   rc   rq  r   r   r   r	   r   o  s   zColorbarPatch.__init__c              
   C   s  t |}| jj| }g }tt |d D ]s}|| d }|| }	t|| d || d g|| d || d g||d  d ||d  d g||d  d ||d  d gg}
| jdkrg|
ddddf }
tjt	
|
| | ||	dd| jd}| j| || q| jr| jD ]}|  q|| _| jdur| j  d| _| jrtj| ||tjd	 fd
tjd  fd| _| j| j dS dS )zg
        Draw the colors using `~matplotlib.patches.Patch`;
        optionally add separators.
        r   r   r=   .NrJ   F)rS   hatchrT   antialiasedrk   rN   r  rP   r  )r   rq  hatchesr
  r4   r-  r>   rw   	PathPatchmpathPathr9   r   rk   rc   	add_patchr"  r  r  r   rq   r  r  r  rz   r{   r  )r   r   r   r   
n_segmentsr  patchesr  valr  r   r~   solidr   r   r	   r   v  sF   






zColorbarPatch._add_solidsN)r(   r)   r*   r+   r   r   r   r   r   r	   r  g  s    r  c                 K   sf   t |tjrtdd |jD rt| |fi |}n	t| |fi |}|jd|j	}||_
||_|S )a1  
    Create a colorbar on the given axes for the given mappable.

    .. note::
        This is a low-level function to turn an existing axes into a colorbar
        axes.  Typically, you'll want to use `~.Figure.colorbar` instead, which
        automatically handles creation and placement of a suitable axes as
        well.

    Parameters
    ----------
    cax : `~matplotlib.axes.Axes`
        The `~.axes.Axes` to turn into a colorbar.
    mappable : `~matplotlib.cm.ScalarMappable`
        The mappable to be described by the colorbar.
    **kwargs
        Keyword arguments are passed to the respective colorbar class.

    Returns
    -------
    `.Colorbar` or `.ColorbarPatch`
        The created colorbar instance. `.ColorbarPatch` is only used if
        *mappable* is a `.ContourSet` with hatches.
    c                 s   s    | ]}|d uV  qd S r1   r   )r   r  r   r   r	   r    s    z#colorbar_factory.<locals>.<genexpr>changed)r   rr  rs  r   r  r  rm  r  connectr|  r   r  )r  rq  r3   cbcidr   r   r	   colorbar_factory  s   r  )NNr  r   r  )Ar+   rV  loggingnumpyr4   
matplotlibrz   matplotlib.artistartistry  matplotlib.cbookr   matplotlib.collectionsr  matplotlib.colorsr`   matplotlib.contourrr  matplotlib.cmrg   matplotlib.gridspecr  matplotlib.patchesr  rw   matplotlib.pathpathr  matplotlib.tickerr   matplotlib.transforms
transformsr>  matplotlib._layoutboxr  r  matplotlib._constrained_layout_constrained_layoutr  r   	getLoggerr(   r   _make_axes_param_doc_make_axes_other_param_docmake_axes_kw_doccolormap_kw_docr   interpdupdater
   r   r   AutoMinorLocatorr-   r.  r2   r6   rl  rm  Substitutionr  r  r  r  r   r   r   r	   <module>   sf    !
?MO!       ] 
5 
)d@