
    d                    >   U d dl mZ d dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
 d dlmZ d dlmZ d dlmZmZmZm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mZ  ed          Z 	 d dl!Z!n# e"$ r dZ!Y nw xY werFd 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/m0Z0m1Z1 	 d dl2m3Z4 n# e"$ r
 dZ4de5d<   Y nw xY wdZ6dZ7dZ8d Z9d Z:d Z;d Z<	 	 	 	 	 	 	 	 	 	 ddZ=dd'Z>	 	 ddd*Z?dd/Z@	 	 	 	 ddd:ZAdd;ZBdd<ZCddd?ZDddCZEddEZFddJZGddPZHdQ ZIddUZJdV ZKddWZLdX ZMdY ZNdZ ZO	 	 	 	 	 	 dddfZPddgZQddhZR	 	 	 	 	 dddlZSdm ZTdndoddp fdqZUdr ZVds ZWdt ZXeddx            ZYedd{            ZYdd~ZY G d de
          ZZ	 	 	 dddZ[ddZ\	 	 dddZ]dS )    )annotationsN)HashableIterableMappingMutableMappingSequence)datetime)getfullargspec)TYPE_CHECKINGAnyCallableoverload)PandasMultiIndex)OPTIONS)DuckArrayModule)	is_scalarmodule_availablenc_time_axis)Axes)	Normalize)FuncFormatter)	ArrayLike)	DataArray)Dataset)AspectOptionsScaleOptionsr   pltg       @)g      2@g      B@g      R@)      ?r   g      @c                     ddl m}  | S )zimport pyplotr   N)matplotlib.pyplotpyplot)r   s    1lib/python3.11/site-packages/xarray/plot/utils.pyimport_matplotlib_pyplotr#   2   s     $#####J    c                    |                                  |k     }|                                 |k    }|r|rdS |rdS |rdS dS )Nbothminmaxneitherr'   r(   )	calc_datavminvmax
extend_min
extend_maxs        r"   _determine_extendr0   :   sY    4'J4'J j v	 u	 uyr$   c                   ddl }t          |          dk    r|d         |d         g}|sd}|dk    rd}n	|dv rd}nd}t          |          |z   dz
  }t          | |          }|j                            |||          \  }}	t          | d	|           |_        	  | t          j        	                    t          j
        g                    d         }
 | t          j                   } | t          j                  }|                    |
           | | d          k    r|                    |           | | | j        dz
            k    r|                    |           n# t           $ r Y nw xY w||	fS )
zB
    Build a discrete colormap and normalization of the data.
    r   N   r(   r&      r*   )extendname)
matplotliblen_color_palettecolorsfrom_levels_and_colorsgetattrr5   npmamasked_invalidnaninfset_bad	set_underNset_over	TypeError)cmaplevelsr4   filledmplext_nn_colorspalnew_cmapcnormbadunderovers                r"   _build_discrete_cmaprR   G   s    
6{{a)VAY' 	>	!	!6{{U"Q&H
x
(
(Cj77F7SSOHeD&$//HM$d25''112215 bfWtBF|| DDGGu%%%44
####d####     	& U?s   9E$ $
E10E1c                   dd l m} ddlm} t	          j        dd|          }t          | t          t          f          r || |          }  | |          }nt          | t                    rr	  |j
        |           }  | |          }n`# t          $ rH 	 ddlm}  || |          }n0# t          t          f$ r  || g|          }  | |          }Y nw xY wY nw xY w | |          }|S )Nr   )ListedColormapg      ?)rC   )color_palette)rK   )r    r!   matplotlib.colorsrT   r<   linspace
isinstancelisttuplestrget_cmap
ValueErrorseabornrU   ImportError)rF   rK   r   rT   colors_irL   rU   s          r"   r8   r8   }   sN   ######000000{1c8,,H$u&& ~dh///d8nn	D#		 	%3<%%D$x..CC 		% 		% 		%%111111#mD8<<<, % % %%~tf999d8nn%		% d8nnJs6   .B
 

CB)(C)*CCCCCFTc                   ddl }t          |t                    rt          |          }t	          j        | t	          j        |                              }|j        dk    rt	          j        d          }|du}d}|d}d}||d}|dup|du}d}|du }|du }|2|rt	          j	        |t                    }n)|                                }n|rt          ||z
            }|5|rt	          j	        |dt          z
            }n)|                                }n|rt          ||z
            }|r<t          |t                    o|d         |d         z  dk     }|dk     r|dk    p| p|}nd}|r7|0t          t          ||z
            t          ||z
                      }| |}}||z  }||z  }|	d|	j        ||	_        n#|s||	j        k    rt          d          |	j        }|	j        ||	_        n#|s||	j        k    rt          d	          |	j        }t          |	|j        j                  r|	j        }||rt(          d
         }nt(          d         }|t+          |          rn|rt	          j        |||          }nU|dk    rt	          j        ||z   dz  g          }n3|j                            |dz
            }|                    ||          }|d         |d         }}||k    r1|j                            d                              ||          \  }}|t9          |||          }|5t          |	|j        j                  st;          ||||          \  }}|	|n|	}	|	d}d}t=          ||||||	          S )a  
    Use some heuristics to set good defaults for colorbar and range.

    Parameters
    ----------
    plot_data : Numpy array
        Doesn't handle xarray objects

    Returns
    -------
    cmap_params : dict
        Use depends on the type of the plotting function
    r   N        FTd   z4Cannot supply vmin and a norm with a different vmin.z4Cannot supply vmax and a norm with a different vmax.cmap_divergentcmap_sequentialr2   r3   r,   r-   rF   r4   rG   norm)r6   rX   r   sortedr<   ravelisfinitesizearray
percentileROBUST_PERCENTILEr'   absr(   r,   r]   r-   r9   BoundaryNorm
boundariesr   r   rW   asarraytickerMaxNLocatortick_valuesLinearLocatorr0   rR   dict)	plot_datar,   r-   rF   centerrobustr4   rG   rH   rh   _is_facetgridrI   r+   possibly_divergentcenter_is_noneuser_minmaxvlimvmin_was_nonevmax_was_nonelevels_are_divergent	divergentrt   newnorms                          r"   _determine_cmap_paramsr      s:   4 &(##  2;y#9#9:;;I ~HSMM	  u, N~ 	t/" t#:T)9K D DLMDLM| 	#=,=>>DD==??DD	 "4&=!!| 	#=C2C,CDDDD==??DD	 "4&=!! 	vx((GVAY-Ca-G 	
 Qh&TAXU~+=UAU 		 	  !<s4&=))3tf}+=+=>>DUDd 	FNDFND 9DII  YTTY%6%6 !WXXX9D9DII  YTTY%6%6 !WXXX9D $
/00 ! | 	.+,DD,-D V 	8 8T4881dTkQ%6$788 //
;;++D$77AYr
d t||Z--a00<<T4HH
d~"9dD99Zcj6M%N%N,T666JJg,wwD 4vD   r$   darrayDataArray | DatasetxHashable | Noneyrgbreturntuple[Hashable, Hashable]c           	         ||k    sJ ||k    sJ  j         dk    sJ d |fD             }t          t          |                    t          |          k     rt          ddd|d          |D ]}| j        vrt          |d           fd	 j        D             }||st          d
          |t          |          dk    r|d         }|0 |         j        dvr!t          d|d |         j         d          |3t          |          dv sJ |d         }t          j        d|d           |J t           	                    |di                    S )z
    Determine x and y labels for showing RGB images.

    Attempts to infer which dimension is RGB/RGBA by size and order of dims.

    N   c                    g | ]}||S N ).0as     r"   
<listcomp>z'_infer_xy_labels_3d.<locals>.<listcomp>R  s    888a!----r$   zHDimension names must be None or unique strings, but imshow was passed x=z, y=z
, and rgb=.z is not a dimensionc                >    g | ]}|         j         d v |fv|S )r      )rl   )r   labelr   r   r   s     r"   r   z'_infer_xy_labels_3d.<locals>.<listcomp>]  sC       %=''E!Q,?,? 	,?,?,?r$   zA 3-dimensional array was passed to imshow(), but there is no dimension that could be color.  At least one dimension must be of size 3 (RGB) or 4 (RGBA), and not given as x or y.r2   r   r   zCannot interpret dim z	 of size z as RGB or RGBA.)r3   r   rd   z`Several dimensions of this array could be colors.  Xarray will use the last possible dimension (zo) to match matplotlib.pyplot.imshow.  You can pass names of x, y, and/or rgb dimensions to override this guess.)
ndimr7   setr]   dimsrl   warningswarn_infer_xy_labelsisel)r   r   r   r   not_noner   could_be_colors   ```    r"   _infer_xy_labels_3dr   B  s4    ;#((((;#((((;!88Aq#;888H
3x==CMM))99 9!"9 9039 9 9
 
 	
  > >##<<<=== $     [  N
 {>{D
 
 	

 {s>**a//Q
6#;+699VCVVF3K4DVVV
 
 	
 {>""f,,,,R <58< < <	
 	
 	
 ??? FKKa111a888r$   imshowboolc                   |||k    rt          d          |r| j        dk    rt          | |||          S |(|&| j        dk    rt          d          | j        \  }}n|=t	          | |d           || j        d         k    r| j        d         n| j        d         }n|=t	          | |d	           || j        d         k    r| j        d         n| j        d         }nt	          | |d	           t	          | |d           | j                            |d          | j                            |d          u r/t          | j        |         t                    rt          d
          ||fS )z}
    Determine x and y labels. For use in _plot2d

    darray must be a 2 dimensional data array, or 3d for imshow only.
    Nzx and y cannot be equal.r   r3   zDataArray must be 2dr   r2   r   r   z/x and y cannot be levels of the same MultiIndex)	r]   r   r   r   _assert_valid_xy_indexesgetrX   r   )r   r   r   r   r   s        r"   r   r     s|    	
AFF3444 6&+"""61a555yQY;!3444{11	
C(((6;q>11FKNNv{1~	
C(((6;q>11FKNNv{1~C(((C(((?q!$$(;(;Aq(A(AAA&/!,.>?? T !RSSSa4Kr$   xyr5   r[   Nonec                V   d | j                                         D             }t          | j                  t          | j                  z  |z
  }|U||vrSd                    t          t          d |D                                           }t          | d| d| d          dS dS )zB
    make sure x and y passed to plotting functions are valid
    c                F    h | ]}t          |t                    |j        S r   )rX   r   dim)r   idxs     r"   	<setcomp>z#_assert_valid_xy.<locals>.<setcomp>  s;       c+,,  r$   Nz', 'c              3  4   K   | ]}t          |          V  d S r   r[   r   vs     r"   	<genexpr>z#_assert_valid_xy.<locals>.<genexpr>  s(      /I/I1A/I/I/I/I/I/Ir$   z must be one of None, 'z'. Received '
' instead.)	xindexes
get_uniquer   r   coordsjoinri   rZ   r]   )r   r   r5   multiindex_dimsvalid_xyvalid_xy_strs         r"   r   r     s     ?--//  O FK  3v}#5#55HH
Rx//{{6%/I/I/I/I/I*I*I#J#JKKUULUUrUUU
 
 	
 	//r$   figsizeIterable[float] | Nonerl   float | Noneaspectr   axAxes | Nonesubplot_kwsr   c                   	 dd l }dd lm} n# t          $ r t          d          w xY w| 9|t	          d          |t	          d           |j        | |          \  }}|S |X|t	          d          ||dk    r|j        d         \  }}	||	z  }
n|d	k    rd
}
n|}
||
z  |f}  |j        | |          \  }}|S |t	          d          |r|t	          d          |t          di |}|S )Nr   z.matplotlib is required for plot.utils.get_axisz0cannot provide both `figsize` and `ax` argumentsz2cannot provide both `figsize` and `size` arguments)r   
subplot_kwz-cannot provide both `size` and `ax` argumentsautozfigure.figsizeequalr2   z/cannot provide `aspect` argument without `size`z'cannot use subplot_kws with existing axr   )r6   r    r!   r_   r]   subplotsrcParams
_maybe_gca)r   rl   r   r   r   rI   r   _widthheightfaspects              r"   get_axisr     s~   L    ''''''' L L LJKKKL >OPPPQRRRWEEE2	>LMMM>Vv--L)9:ME6fnGGwGGG'>4(WEEE2	JKKK Dr~BCCC	z&&+&&Is   
 'c                 r    dd l m}  |j                    }|j        r |j                    S  |j        di | S )Nr   r   )r    r!   gcfaxesgca)r   r   fs      r"   r   r     sU    ###### 			A 	v swyy38""k"""r$   c                   t          d          j        }d}t          | j        |          r-|                    t          | j        j                            }nx| j                            d          r!|                    | j        d                   }n=| j                            d          r!|                    | j        d                   }nd}|S )z6Extracts and formats the unit/units from a attributes.pintz [{}]unitsunit )	r   typerX   dataformatr[   r   attrsr   )dapint_array_typer   s      r"   _get_units_from_attrsr     s    %f--2OE"'?++ S//00	g		 RXg.//	f		 RXf-..Lr$   r   extrac                v   d}| j                             d          r!|                    | j         d                   }n_| j                             d          r!|                    | j         d                   }n$| j        |                    | j                  }nd}t	          |           }|                    d          rL|                    d          dz  dk    r0d	                    t          j	        ||z   |z   d
d                    S d                    t          j	        ||z   |z   d                    S )zQMakes informative labels if variable metadata (attrs) follows
    CF conventions.z{}	long_namestandard_nameNr   $r3   r   z$
$<   F)break_long_words
   )
r   r   r   r5   r   
startswithcountr   textwrapwrap)r   r   r5   r   s       r"   label_from_attrsr     s$    D	x||K   {{28K011	o	&	& {{28O455		{{27##!"%%E s BC1!4!9!9{{M$,.UKKK
 
 	
 yyte|e';R@@AAAr$   rm   Iterable[pd.Interval]
np.ndarrayc                >    t          j        d | D                       S )zT
    Helper function which returns an array
    with the Intervals' mid points.
    c                    g | ]	}|j         
S r   )midr   r   s     r"   r   z+_interval_to_mid_points.<locals>.<listcomp>)  s    ***qQU***r$   )r<   rm   )rm   s    r"   _interval_to_mid_pointsr   #  s#     8**E***+++r$   Sequence[pd.Interval]c                    t          j        d | D                       }t          j        |t          j        | d         j        g          f          }|S )zT
    Helper function which returns an array
    with the Intervals' boundaries.
    c                    g | ]	}|j         
S r   leftr   s     r"   r   z-_interval_to_bound_points.<locals>.<listcomp>2  s     7 7 7A 7 7 7r$   rd   )r<   rm   concatenateright)rm   array_boundariess     r"   _interval_to_bound_pointsr  ,  sR     x 7 7 7 7 788~'759?BS9T9T&UVVr$   xarrayyarrayr   tuple[np.ndarray, np.ndarray]c           
        t          j        d | D                       }t          j        d | D                       }t          j        t          t          j                            t          ||                                        }t          j        t          t          j                            t          ||                                        }||fS )z
    Helper function to deal with a xarray consisting of pd.Intervals. Each
    interval is replaced with both boundaries. I.e. the length of xarray
    doubles. yarray is modified so it matches the new shape of xarray.
    c                    g | ]	}|j         
S r   r   r   s     r"   r   z4_interval_to_double_bound_points.<locals>.<listcomp>A  s    ///1///r$   c                    g | ]	}|j         
S r   )r   r   s     r"   r   z4_interval_to_double_bound_points.<locals>.<listcomp>B  s    000A000r$   )r<   rm   rY   	itertoolschainfrom_iterablezip)r  r  xarray1xarray2
xarray_out
yarray_outs         r"    _interval_to_double_bound_pointsr  8  s     h/////00Gh0000011G$y<<S'=R=RSSTTUUJ$y<<S=P=PQQRRSSJz!!r$   xvalyvalkwargsrx   -tuple[np.ndarray, np.ndarray, str, str, dict]c                   d}d}|                     dd                              d          r~d}t          | t          j                  }t          |t          j                  }|r|rt          d          |rt          | |          \  } }d}n|rt          ||           \  }} d}|r|d= nVt          | t          j                  rt          |           } d}t          |t          j                  rt          |          }d}| ||||fS )z
    Helper function to replace the values of x and/or y coordinate arrays
    containing pd.Interval with their mid-points or - for step plots - double
    points which double the length.
    r   	drawstylezsteps-Fz,Can't step plot intervals against intervals.T_center)r   r   _valid_other_typepdIntervalrE   r  r   )r  r  r  x_suffixy_suffixremove_drawstylex_is_intervaly_is_intervals           r"   _resolve_intervals_1dplotr   J  s5    HH zz+r""--h77 !  *$<<)$<< 	$] 	$JKKK 	$9$EEJD$# 	$9$EEJD$#  	${#
 T2;// 	!*400D HT2;// 	!*400D H x611r$   c                    d}t          | t          j                  r'|dk    rt          |           } nt	          |           } d}| |fS )z
    Helper function to replace the values of a coordinate array containing
    pd.Interval with their mid-points or - for pcolormesh - boundaries which
    increases length by 1.
    r   
pcolormeshr  )r  r  r  r  r   )val	func_namelabel_extras      r"   _resolve_intervals_2dplotr&  w  sT     Kbk** $$$+C00CC)#..C#Kr$   r   types'type[object] | tuple[type[object], ...]c                ^    t          fdt          j        |           D                       S )z6
    Do all elements of x have a type from types?
    c              3  8   K   | ]}t          |          V  d S r   )rX   )r   elr'  s     r"   r   z$_valid_other_type.<locals>.<genexpr>  s-      ;;z"e$$;;;;;;r$   )allr<   rj   )r   r'  s    `r"   r  r    s0     ;;;;rx{{;;;;;;r$   c                     |D ]#}t          j        t           j        |          rJ $t           fd|D                       S )zC
    Is any dtype from numpy_types superior to the dtype of x?
    c              3  L   K   | ]}t          j        j        |          V  d S r   )r<   
issubdtypedtype)r   tr   s     r"   r   z(_valid_numpy_subdtype.<locals>.<genexpr>  s1      >>Qr}QWa((>>>>>>r$   )r<   r/  genericany)r   numpy_typesr1  s   `  r"   _valid_numpy_subdtyper5    sT      0 0=Q//////>>>>+>>>>>>r$   c                 4   t           j        t           j        t           j        t           j        t           j        t           j        f}t          f}t          dnt          j        f}||z  }| D ]}t          t          j
        |          |          sLt          t          j
        |          |          s*t          dt          j
        |          j         d          t          t          j
        |          |          rt          rddl}t!          d          dS )zj
    Raise exception if there is anything in args that can't be plotted on an
    axis by matplotlib.
    Nr   zPlotting requires coordinates to be numeric, boolean, or dates of type numpy.datetime64, datetime.datetime, cftime.datetime or pandas.Interval. Received data of type 	 instead.r   zPlotting of arrays of cftime.datetime objects or arrays indexed by cftime.datetime objects requires the optional `nc-time-axis` (v1.2.0 or later) package.)r<   floatingintegertimedelta64
datetime64bool_str_r	   cftimer5  rs   r  rE   r0  nc_time_axis_availabler   r_   )argsr4  other_typescftime_datetime_typesr   r   s         r"   _ensure_plottablerC    s/    	





-K .6KKn6?"4  ((K  !"*Q--==		 A<<		 Y ;=*Q--:MY Y Y   RZ]],ABB 	%  $####!  	 r$   c                R    t           j        t           j        g}t          | |          S r   )r<   r8  r9  r5  )arrr4  s     r"   _is_numericrF    s     ;
+K k222r$   c                *   |                     d|d                    ||                     d|           n|                     d|           t          | d          r|                    d           |                                } |j        | fi |}|S )Nr4   r   cax)
setdefaulthasattrpop
get_figurecolorbar)	primitiver   cbar_axcbar_kwargscmap_paramsfigcbars          r"   _add_colorbarrT    s    8[%:;;;tR((((ug... y(## "!!!
--//C3<	11[11DKr$   c                   |s||J |r<|t          j        | dt          z
            }|t          j        | t                    }nd|Et          j        | j        t           j                  rdnd}||k     rt          d|d|d          n|d}||k    rt          d|d	          |                     d
          |z
  ||z
  z                      d          } t          j        t          j	        | d          d          S )Nrc      r2   zvmin=z  is less than the default vmax (z/) - you must supply a vmax > vmin in this case.r   zvmax=zP is less than the default vmin (0) - you must supply a vmin < vmax in this case.f8f4)
r<   nanpercentilero   r/  r0  r9  r]   astypeminimummaximum)r   r,   r-   r{   s       r"   _rescale_imshow_rgbr]    sI   9T%)9)9)9  <#FC2C,CDDD<#F,=>>D 
mFL"*==Dss1$;;. . . . . .   
 
$;;. . . .   }}T""T)dTk:BB4HHF:bj++Q///r$   	xincreasebool | None	yincreasexscaler   yscalexticksArrayLike | Noneyticksxlimylimc	                ~   |nU|r)|                                  r|                                  n*|s(|                                  s|                                  |nU|r)|                                 r|                                  n*|s(|                                 s|                                  ||                     |           ||                     |           ||                     |           ||                     |           ||                     |           || 	                    |           dS dS )z.
    Update axes with provided parameters
    N)
xaxis_invertedinvert_xaxisyaxis_invertedinvert_yaxis
set_xscale
set_yscale
set_xticks
set_yticksset_xlimset_ylim)	r   r^  r`  ra  rb  rc  re  rf  rg  s	            r"   _update_axesrs    sh    	 r((** 
 r0022 
	 r((** 
 r0022 
 
f
f
f
f
D
D r$   c                   | j         |         dk     rdS | j         |         }|                     t          j        d|          |          |                     t          j        d|dz
            |          k    }|                     t          j        d|          |          |                     t          j        d|dz
            |          k    }t          j        |          pt          j        |          S )z
    >>> _is_monotonic(np.array([0, 1, 2]))
    True
    >>> _is_monotonic(np.array([2, 1, 0]))
    True
    >>> _is_monotonic(np.array([0, 2, 1]))
    False
    r   Tr2   axisr   )shapetaker<   aranger,  )coordrv  n	delta_pos	delta_negs        r"   _is_monotonicr~  2  s     {41tKJJryATJ::ejjIaQd ?I ?
 ?
 
	 JJryATJ::ejjIaQd ?I ?
 ?
 
	 vi  5BF9$5$55r$   c                   t          j        |           } |r#t          |           st          dz            |dk    r;| dk                                    rt          d          t          j        |           } dt          j        |           z  }|j        dk    rt          j        d          }t          j	        | dg          t          j	        |dg          z
  }t          j	        | dg          t          j	        |dg          z   }t          fd	t          | j                  D                       }t          j        || |         |z   |g          }|dk    rt          j        d
|          S |S )a  
    >>> _infer_interval_breaks(np.arange(5))
    array([-0.5,  0.5,  1.5,  2.5,  3.5,  4.5])
    >>> _infer_interval_breaks([[0, 1], [3, 4]], axis=1)
    array([[-0.5,  0.5,  1.5],
           [ 2.5,  3.5,  4.5]])
    >>> _infer_interval_breaks(np.logspace(-2, 2, 5), scale="log")
    array([3.16227766e-03, 3.16227766e-02, 3.16227766e-01, 3.16227766e+00,
           3.16227766e+01, 3.16227766e+02])
    ru  a"  The input coordinate is not sorted in increasing order along axis %d. This can lead to unexpected results. Consider calling the `sortby` method on the input DataArray. To plot data with categorical axes, consider using the `heatmap` function from the `seaborn` statistical plotting library.logr   z\Found negative or zero value in coordinates. Coordinates must be positive on logscale plots.      ?rb   rd   c              3  b   K   | ])}|k    rt          d d          nt          d           V  *d S )Nrd   )slice)r   r{  rv  s     r"   r   z)_infer_interval_breaks.<locals>.<genexpr>m  sN        :;199dB%++     r$   
   )r<   rs   r~  r]   r3  log10diffrl   rm   rx  rZ   ranger   r   power)	rz  rv  scalecheck_monotonicdeltasfirstlast	trim_lastinterval_breakss	    `       r"   _infer_interval_breaksr  H  s    JuE 
}U>>> 
:
 =AA
 
 	
 ~~QJ 	D   275t,,,,F{a#GEA3T***RWVaSt-L-L-LLE752$T***RWVbT-M-M-MMD    ?DUZ?P?P    I n	i 6)40t  O ~~xO,,,r$   rP  4Iterable[tuple[str, Any]] | Mapping[str, Any] | None%tuple[dict[str, Any], dict[str, Any]]c                  
 | j         dk    r|d<   fddD             i fS |i nt          |          }d| j         v r|d}|r|rt          d          |rd| j         vr|t          d	          t          |t          t
          f          rt          d
          |||r|n|| j         dk    d
t          t                    j        }
	                    fd|D                        |st          di 
}	n
fddD             }	|	|fS )z
    Parameters
    ----------
    func : plotting function
    data : ndarray,
        Data values

    Returns
    -------
    cmap_params : dict
    cbar_kwargs : dict
    surfacerF   c                >    i | ]}|                     |d           S r   r   )r   kr  s     r"   
<dictcomp>z-_process_cmap_cbar_kwargs.<locals>.<dictcomp>  s9     
 
 
 vzz!T""
 
 
r$   rg   Ncontour   z#Can't specify both cmap and colors.z.Can only specify colors with contour or levelszNSpecifying a list of colors in cmap is deprecated. Use colors keyword instead.)ry   rG   rF   rH   c              3  4   K   | ]}|v ||         fV  d S r   r   )r   r   r  s     r"   r   z,_process_cmap_cbar_kwargs.<locals>.<genexpr>  s/      HH!AKK6!9~KKKKHHr$   c                "    i | ]}||         S r   r   )r   r  cmap_kwargss     r"   r  z-_process_cmap_cbar_kwargs.<locals>.<dictcomp>  s/     
 
 
 {1~
 
 
r$   r   )
__name__rx   r]   rX   rY   rZ   r
   r   r@  update)funcr   rF   r9   rP  rG   r|   r  	cmap_argsrQ  r  s          `  @r"   _process_cmap_cbar_kwargsr  y  s   , }	!!v
 
 
 
I
 
 
  	
 $+""k1B1BKDM!!fn  @ @>???  KIT]22IJJJ $u&& 
*
 
 	
  *d-9,	 K 566;IHHHHyHHHHHH 
,;;{;;
 
 
 
I
 
 

 ##r$   c                   dd l }|j                            d          }t          j        t          j        |                                 |                                                    }|                    d|          d         }|S )Nr   r   )r6   rt   ru   r<   meanhypotto_numpyrv   )ur   rI   rt   r  	magnitudes         r"   _get_nice_quiver_magnituder    sn    Z##A&&F728AJJLL!**,,7788D""1d++B/Ir$   r9   r   c                    | S r   r   r   s    r"   <lambda>r    s    a r$   c                
    ddl }ddl}|j        }g }	g }
|dk    rR                                 }| |j        d           |	|
fS |                    d|j        d                    fd}nx|dk    r_t           |j        j	                  r 
                                }n                                 }|                    d	d
          fd}nt          d| d          t          j        |          }t          j         ||                    }t          j        |j        t          j                  }||r|j                            dd          }nN||s|j                            d          }n/t          |t,                    r|j                            |          }|                                 |dk    rd}t1          |          |k    rd}|r|                                }|                                }|j                            ||           |j                            ||           |#t          ||j        j                  r|}n`t          j        |          r|j                             |          }n1tC          |          }|j        "                    ||dz
  g d          }|#                    ||          }||k    ||k    z  }||         }t          j$        |                                |                                d          } ||          }t          j%        |          }t          j&        |||         ||                   }n||stO          |          tB          k    r|j        (                    |          }nt          d          |#                    dt1          |          dz
            )                    tB                    }||         }||         }tU          |d          r|+                    |           tY           
                                d          -                                          }|.                    |           t_          ||          D ]\  }} ||          \  }}t           |j        j0                  r1|.                    d 1                                d         |           nIt           |j        j	                  r/|.                     2                                d         |            |j3        dgdgfd	|i|}|	4                    |           |
4                     ||                     |	|
fS )a9  
    Create legend handles and labels for a PathCollection.

    Each legend handle is a `.Line2D` representing the Path that was drawn,
    and each label is a string what each Path represents.

    This is useful for obtaining a legend for a `~.Axes.scatter` plot;
    e.g.::

        scatter = plt.scatter([1, 2, 3],  [4, 5, 6],  c=[7, 2, 3])
        plt.legend(*scatter.legend_elements())

    creates three legend elements, one for each color with the numerical
    values passed to *c* as the labels.

    Also see the :ref:`automatedlegendcreation` example.


    Parameters
    ----------
    prop : {"colors", "sizes"}, default: "colors"
        If "colors", the legend handles will show the different colors of
        the collection. If "sizes", the legend will show the different
        sizes. To set both, use *kwargs* to directly edit the `.Line2D`
        properties.
    num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
        Target number of elements to create.
        If None, use all unique elements of the mappable array. If an
        integer, target to use *num* elements in the normed range.
        If *"auto"*, try to determine which option better suits the nature
        of the data.
        The number of created elements may slightly deviate from *num* due
        to a `~.ticker.Locator` being used to find useful locations.
        If a list or array, use exactly those elements for the legend.
        Finally, a `~.ticker.Locator` can be provided.
    fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
        The format or formatter to use for the labels. If a string must be
        a valid input for a `~.StrMethodFormatter`. If None (the default),
        use a `~.ScalarFormatter`.
    func : function, default: ``lambda x: x``
        Function to calculate the labels.  Often the size (or color)
        argument to `~.Axes.scatter` will have been pre-processed by the
        user using a function ``s = f(x)`` to make the markers visible;
        e.g. ``size = np.log10(x)``.  Providing the inverse of this
        function here allows that pre-processing to be inverted, so that
        the legend labels have the correct values; e.g. ``func = lambda
        x: 10**x``.
    **kwargs
        Allowed keyword arguments are *color* and *size*. E.g. it may be
        useful to set the color of the markers if *prop="sizes"* is used;
        similarly to set the size of the markers if *prop="colors"* is
        used. Any further parameters are passed onto the `.Line2D`
        instance. This may be useful to e.g. specify a different
        *markeredgecolor* or *alpha* for the legend handles.

    Returns
    -------
    handles : list of `.Line2D`
        Visual representation of each element of the legend.
    labels : list of str
        The string labels for elements of the legend.
    r   Nr9   zfCollection without array used. Make sure to specify the values to be colormapped via the `c` argument.rl   zlines.markersizec                X                                             |                     fS r   )rF   rh   )value_sizeselfs    r"   _get_color_and_sizez,legend_elements.<locals>._get_color_and_size!  s&    99TYYu--..55r$   sizescolorr  c                0    t          j        |           fS r   )r<   sqrt)r  _colors    r"   r  z,legend_elements.<locals>._get_color_and_size+  s    275>>))r$   z?Valid values for `prop` are 'colors' or 'sizes'. You supplied 'r   FT)	useOffsetuseMathTextz{x}r   	   r2   )r2   r3   g      @r            r  )nbinsmin_n_tickssteps   z4`num` only supports integers for non-numeric labels.set_locs)markeredgewidthalphar   )	linestylemarker
markersize)r  	linewidth)5r   r6   lines	get_arrayr   rK  r   rX   collectionsLineCollectionget_linewidths	get_sizesr]   r<   uniquers   r/  r0  numberrt   ScalarFormatterStrMethodFormatterr[   create_dummy_axisr7   r'   r(   rv  set_view_intervalset_data_intervalLocatoriterableFixedLocatorintru   rv   rW   argsortinterpr   rw   rZ  rJ  r  rx   	get_alphar  r  PathCollection	get_pathsget_linestyleLine2Dappend) r  propnumfmtr  r  r   rI   mlineshandleslabelsrE  r  valueslabel_valueslabel_values_are_numericlabel_values_minlabel_values_maxloccondvalues_interplabel_values_interpixindkwr#  labr  rl   hr  r  s    `                             @@r"   legend_elementsr    s   B OOOYFGFxnn;HM   
 F?"

63<0B#CDD	6 	6 	6 	6 	6 	6 	6 
dCO:;; 	#%%''CC..""CGS))	* 	* 	* 	* 	* 	* 7&*7 7 7
 
 	
 Ys^^F:dd6ll++L!}\-?KK {/{j((5d(KK	5j++E22	C		 1j++C00
f}}v;;#C .'++--'++--""#35EFFF""#35EFFF? #sz122 S!! j--c22#hhj,,37:U:U:U -  
 ??+;=MNNL !$44 00D (-L K

fjjllCHHM"&$}"5"5/00BY|-@-DmTVFWXXF	!9 99***3//CCSTTTooa\!2!2Q!677>>sCC#C( sJ #\""" 
d1133A6dnn>N>N	O	O	OBIIf--    S))#..tdCO:;; 	III4>>+;+;A+>4IPPPPco<== 	III 2 2 4 4Q 74IHHHFM1#s66%6266qcc#hhF?r$   c                    t                      }|rGt          |           dk    r4 |j        g g |          }|                    d           |g| z   } |g|z   }| |fS )z!Add a subtitle to legend handles.r2   )r   F)r#   r7   r  set_visible)r  r  textr   blank_handles        r"   _legend_add_subtitler    sv    
"
$
$C 	!Gq   "sz"b555  '''  .7*&F?r$   c                2  	 t                      		j                            dd          }|                     	j        j        j                  d                                         }	fd|D             }|D ]}|                                }t          |          dk     r*|\  }}|                                }t          d |D                       sC|
                    d           |                                D ]}||                    |           dS )z@Make invisible-handle "subtitles" entries look more like titles.zlegend.title_fontsizeNr   c                R    g | ]#}t          |j        j        j                  !|$S r   )rX   r6   	offsetboxHPacker)r   r   r   s     r"   r   z,_adjust_legend_subtitles.<locals>.<listcomp>  s0    WWWaz!S^5M5U'V'VWWWWr$   r3   c              3  >   K   | ]}|                                 V  d S r   )get_visible)r   artists     r"   r   z+_adjust_legend_subtitles.<locals>.<genexpr>  s.      >>F6%%''>>>>>>r$   )r#   r   r   findobjr6   r  VPackerget_childrenr7   r,  	set_widthset_size)
legend	font_sizehpackershpackareas	draw_area	text_arear  r  r   s
            @r"   _adjust_legend_subtitlesr    s0   
"
$
$C   !8$??I~~cn6>??BOOQQHWWWW8WWWH - -""$$u::>>$	9((** >>g>>>>> 	- """!..00 - -( MM),,,%- -r$   c           
        t          | j                                                  }dd                    t	          t          d |D                                            d}||vrt          d| d| d          ||vrt          d| d| d          |||vrt          d	| d| d          |r\t          | |         j                  }	||	rd
nd}|	s|d
k    rt          d|           ||du r|d
k    rdnd}
|dk    rdnd}n d}
d}n|du r|dvrt          d          d}d}
|s|'|dk    r!d}|rd}
|sd
}n|d
k    rt          d          nd}|s|$|dk    r|rd}
|sd
}n|d
k    rt          d          ||dvrt          d          |rt          | |                   }| |         }nd }d }|
||||t          | |                   t          | |                   |dS )Nz must be one of (z, c              3  4   K   | ]}t          |          V  d S r   r   r   s     r"   r   z#_infer_meta_data.<locals>.<genexpr>  s(      :Q:Qa3q66:Q:Q:Q:Q:Q:Qr$   )zExpected 'x' z. Received r7  zExpected 'y' zExpected 'hue' 
continuousdiscretez7Cannot create a colorbar for a non numeric coordinate: TF)quiver
streamplotz&Cannot set add_guide when hue is None.r  zKhue_style must be 'continuous' or None for .plot.quiver or .plot.streamplotr  )r  r  z:hue_style must be either None, 'discrete' or 'continuous'.)add_colorbar
add_legendadd_quiverkey	hue_label	hue_stylexlabelylabelhue)
r   	variableskeysr   ri   rZ   r]   rF  r  r   )dsr   r   r  r  	add_guidefuncnamedvars	error_msghue_is_numericr  r  r  r  s                 r"   _infer_meta_datar(    s   !!##$$EVDIIfU:Q:Q5:Q:Q:Q5Q5Q.R.R$S$SVVVI~~KKKqKKKLLL~~KKKqKKKLLL
3e++O9OOOOOPPP
 $RW^44(6FJI 	9#<#<O#OO   	T 1 1#,#<#<44%L!*j!8!8eJJ LJJ1I!I!IEFFF
 Y&H,@,@ 	L (		l** '  
  	Y&H,D,D 	L (		l** '  
 2L!L!LUVVV
 $RW--	g	 % &"2a5))"2a5))	 	 	r$   r   rh   :tuple[float | None, float | None, bool] | Normalize | Nonec                    d S r   r   r   rh   s     r"   _parse_sizer,    	    
 Cr$   r   	pd.Seriesc                    d S r   r   r+  s     r"   r,  r,    r-  r$   DataArray | NoneNone | pd.Seriesc                   dd l }| d S | j                                        }t          |          sCt	          j        |          }t	          j        ddt          |          z             d d d         }n(t	          j        t	          j        |                    x}}t          \  }}}||j
                                        }nPt          |t                    r |j
        j        | }n+t          ||j
        j                  sd}	t          |	          t          ||j
        j                  sJ d|_        |                                s |t	          j        |                      ||          }
t	          j        ||
||z
  z  z             }|
j                                        r
d||
j        <   t)          t+          ||                    }t-          j        |          S )Nr   r2   rd   z7``size_norm`` must be None, tuple, or Normalize object.T)r6   r  flattenrF  r<   r  ry  r7   sort_MARKERSIZE_RANGEr9   r   rX   rZ   r]   clipscaledrs   maskr3  rx   r  r  Series)r   rh   rI   flatdatarG   numbers	min_widthdefault_width	max_widtherrsclwidthsr  s                r"   r,  r,  "  s    |t{""$$Hx   88$$)Aq3v;;//"5729X#6#6777*;'I}i |z##%%	D%	 	  #sz#T*cj233 GoodCJ011111DI;;== "RZ  !!! $w--CZ	C9y+@$AABBF
x||~~ sxVV$$%%E9Ur$   c                     e Zd ZU dZded<   ded<   ded<   ded<   ded	<   d
ed<   dZ	 	 d2d3dZd4dZd5dZd Z	e
d6d            Ze
d7d            Zed8d            Zed9d            Zd:d!Zed;d#            Zed<d$            Zd=d%Ze
d6d&            Ze
d>d(            Ze
d>d)            Ze
d?d*            Ze
d@d,            Zd?d-Ze
dAd/            Ze
dBd1            ZdS )C
_Normalizea  
    Normalize numerical or categorical values to numerical values.

    The class includes helper methods that simplifies transforming to
    and from normalized values.

    Parameters
    ----------
    data : DataArray
        DataArray to normalize.
    width : Sequence of three numbers, optional
        Normalize the data to these (min, default, max) values.
        The default is None.
    r0  _datar   _data_unique_data_unique_index_data_unique_inverser   _data_is_numeric!tuple[float, float, float] | None_width)rD  rE  rF  rG  rH  rJ  NFr   r   r|   r   r   c                l   || _         |s|nd | _        t          d          j        }t	          ||n|j        |          r|                                n|}t          j        |d          \  }}|| _	        t          j
        d|j                  | _        || _        |dnt          |          | _        d S )Nr   T)return_inverser   F)rD  rJ  r   r   rX   r   r  r<   r  rE  ry  rl   rF  rG  rF  rH  )r  r   r   r|   r   	to_uniquedata_uniquedata_unique_inverses           r"   __init__z_Normalize.__init__m  s     
#0:eed)&116 $,$$DIOODMMOOO 	
 ,.9Yt+T+T+T(('"$)A{/?"@"@$7!)-;t;L;Lr$   r[   c                    t          j        ddd          5  d| j         d| j         d| j         	 cd d d            S # 1 swxY w Y   d S )Nr   Tr  )	precisionsuppress	thresholdz<_Normalize(data, width=z)>
z -> )r<   printoptionsrJ  rE  _values_uniquer  s    r"   __repr__z_Normalize.__repr__  s    _q41EEE 	 	@4; @ @$@ @*.*=@ @	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   A  AAr  c                *    t          | j                  S r   )r7   rE  rW  s    r"   __len__z_Normalize.__len__  s    4$%%%r$   c                    | j         |         S r   )rE  )r  keys     r"   __getitem__z_Normalize.__getitem__  s     %%r$   c                    | j         S r   )rD  rW  s    r"   r   z_Normalize.data  s
    zr$   c                    | j         S )a+  
        Check if data is numeric.

        Examples
        --------
        >>> a = xr.DataArray(["b", "a", "a", "b", "c"])
        >>> _Normalize(a).data_is_numeric
        False

        >>> a = xr.DataArray([0.5, 0, 0, 0.5, 2, 3])
        >>> _Normalize(a).data_is_numeric
        True
        )rH  rW  s    r"   data_is_numericz_Normalize.data_is_numeric  s     $$r$   r   c                    d S r   r   r  r   s     r"   _calc_widthsz_Normalize._calc_widths      r$   r   c                    d S r   r   rb  s     r"   rc  z_Normalize._calc_widths  rd  r$   np.ndarray | DataArrayc                    | j         |S | j         \  }}}t          j        |          t          j        |          z
  }|dk    r	|d|z  z   }n%|t          j        |          z
  |z  }||||z
  z  z   }|S )zH
        Normalize the values so they're inbetween self._width.
        Nr   )rJ  r<   r(   r'   )r  r   xminxdefaultxmaxdiff_maxy_minyrA  r  s           r"   rc  z_Normalize._calc_widths  s     ;H#{hRVAYY.QA%FF RVAYY.0AA--Fr$   r   c                    d S r   r   r  r   s     r"   _indexes_centeredz_Normalize._indexes_centered  rd  r$   c                    d S r   r   rm  s     r"   rn  z_Normalize._indexes_centered  rd  r$   c                    |dz  dz   S )zv
        Offset indexes to make sure being in the center of self.levels.
        ["a", "b", "c"] -> [1, 3, 5]
        r3   r2   r   rm  s     r"   rn  z_Normalize._indexes_centered  s    
 1uqyr$   c                    | j         dS | j        r| j         }nR|                     | j                  }| j                             |                    | j         j                            }|                     |          S )a9  
        Return a normalized number array for the unique levels.

        Examples
        --------
        >>> a = xr.DataArray(["b", "a", "a", "b", "c"])
        >>> _Normalize(a).values
        <xarray.DataArray (dim_0: 5)>
        array([3, 1, 1, 3, 5])
        Dimensions without coordinates: dim_0

        >>> _Normalize(a, width=(18, 36, 72)).values
        <xarray.DataArray (dim_0: 5)>
        array([45., 18., 18., 45., 72.])
        Dimensions without coordinates: dim_0

        >>> a = xr.DataArray([0.5, 0, 0, 0.5, 2, 3])
        >>> _Normalize(a).values
        <xarray.DataArray (dim_0: 6)>
        array([0.5, 0. , 0. , 0.5, 2. , 3. ])
        Dimensions without coordinates: dim_0

        >>> _Normalize(a, width=(18, 36, 72)).values
        <xarray.DataArray (dim_0: 6)>
        array([27., 18., 18., 27., 54., 72.])
        Dimensions without coordinates: dim_0

        >>> _Normalize(a * 0, width=(18, 36, 72)).values
        <xarray.DataArray (dim_0: 6)>
        array([36., 36., 36., 36., 36., 36.])
        Dimensions without coordinates: dim_0

        N)r   )r   r`  rn  rG  copyreshaperw  rc  )r  r#  rE  s      r"   r  z_Normalize.values  sx    F 94  	D)CC(()BCCC)..ckk$)/&B&B.CCC  %%%r$   np.ndarray | Nonec                    | j         dS | j        r| j        }n|                     | j                  }|                     |          S )a  
        Return unique values.

        Examples
        --------
        >>> a = xr.DataArray(["b", "a", "a", "b", "c"])
        >>> _Normalize(a)._values_unique
        array([1, 3, 5])

        >>> _Normalize(a, width=(18, 36, 72))._values_unique
        array([18., 45., 72.])

        >>> a = xr.DataArray([0.5, 0, 0, 0.5, 2, 3])
        >>> _Normalize(a)._values_unique
        array([0. , 0.5, 2. , 3. ])

        >>> _Normalize(a, width=(18, 36, 72))._values_unique
        array([18., 27., 54., 72.])
        N)r   r`  rE  rn  rF  rc  r  r#  s     r"   rV  z_Normalize._values_unique  sS    * 94  	B#CC(()@AAC  %%%r$   c                N    | j         rd}n|                     | j                  }|S )z
        Return ticks for plt.colorbar if the data is not numeric.

        Examples
        --------
        >>> a = xr.DataArray(["b", "a", "a", "b", "c"])
        >>> _Normalize(a).ticks
        array([1, 3, 5])
        N)r`  rn  rF  rv  s     r"   ticksz_Normalize.ticks  s2      	BCC(()@AAC
r$   c                p    t          j        | j        t          j        | j                  dz             dz  S )a  
        Return discrete levels that will evenly bound self.values.
        ["a", "b", "c"] -> [0, 2, 4, 6]

        Examples
        --------
        >>> a = xr.DataArray(["b", "a", "a", "b", "c"])
        >>> _Normalize(a).levels
        array([0, 2, 4, 6])
        r2   r3   )r<   r  rF  r(   rW  s    r"   rG   z_Normalize.levels0  s4     Id-rvd6M/N/NQR/RSSVWW	
r$   r.  c                    | j         t          d          t          j        t	          t          | j         | j                                      S )Nzself.data can't be None.)rV  r]   r  r9  rx   r  rE  rW  s    r"   _lookupz_Normalize._lookup@  sB    &7888yc$"5t7HIIJJKKKr$   c                    | j                                                             |d                                          S )Nnearest)method)r{  
sort_indexreindexr  rm  s     r"   _lookup_arrz_Normalize._lookup_arrG  s7    
 |&&((0090EENNPPPr$   r   c                N     t                      }dd fd} |j        |          S )	a  
        Return a FuncFormatter that maps self.values elements back to
        the original value as a string. Useful with plt.colorbar.

        Examples
        --------
        >>> a = xr.DataArray([0.5, 0, 0, 0.5, 2, 3])
        >>> aa = _Normalize(a, width=(0, 0.5, 1))
        >>> aa._lookup
        0.000000    0.0
        0.166667    0.5
        0.666667    2.0
        1.000000    3.0
        dtype: float64
        >>> aa.format(1)
        '3.0'
        Nr   r   pos
None | Anyc                >                         | g          d          S )Nr   r  r   r  r  s     r"   _funcz _Normalize.format.<locals>._funcc  s!    &&s++A.00r$   r   r   r   r  r  )r#   r   )r  r   r  s   `  r"   r   z_Normalize.formatN  sH    & '((	1 	1 	1 	1 	1 	1 	1 !s '''r$    Callable[[Any, None | Any], Any]c                     dd fd}|S )	a  
        Return a lambda function that maps self.values elements back to
        the original value as a numpy array. Useful with ax.legend_elements.

        Examples
        --------
        >>> a = xr.DataArray([0.5, 0, 0, 0.5, 2, 3])
        >>> aa = _Normalize(a, width=(0, 0.5, 1))
        >>> aa._lookup
        0.000000    0.0
        0.166667    0.5
        0.666667    2.0
        1.000000    3.0
        dtype: float64
        >>> aa.func([0.16, 1])
        array([0.5, 3. ])
        Nr   r   r  r  c                .                         |           S r   r  r  s     r"   r  z_Normalize.func.<locals>._func|  s    ##A&&&r$   r   r  r   )r  r  s   ` r"   r  z_Normalize.funch  s-    (	' 	' 	' 	' 	' 	' 	' r$   )NF)r   r0  r   rI  r|   r   r   r   r   r[   )r   r  )r   r0  )r   r   )r   r   r   r   )r   r   r   r   )r   rf  r   rf  )r   r   r   r   )r   r   r   r   )r   rf  r   rf  )r   rt  )r   r   )r   r.  )r   r   )r   r  )r  
__module____qualname____doc____annotations__	__slots__rP  rX  rZ  r]  propertyr   r`  r   rc  rn  r  rV  rx  rG   r{  r  r   r  r   r$   r"   rC  rC  M  s          """"$$$$----I 48#	M M M M M*   & & & && & &    X % % % X%     X    X   &    X    X    ,& ,& ,& X,&\ & & & X&>    X$ 
 
 
 X
 L L L XLQ Q Q Q ( ( ( X(2    X  r$   rC  hueplt_normsizeplt_normr  None | boolr  plotfunc_name
str | Nonetuple[bool, bool]c                    |dk    rdS |r| j         t          d          || j         d}nd}|r| j         |j         t          d          ||s| j         	| j        du s|j         d}nd}||fS )Nhist)FFz*Cannot create a colorbar when hue is None.TFz7Cannot create a legend when hue and markersize is None.)r   KeyErrorr`  )r  r  r  r  r  s        r"   _determine_guider    s     | E+*2CDDD'LL L Rk&.<3D3LPQQQ	!-+2MQV2V2V ,JJJ##r$   plotfuncc                \   t          |t                    r|n|g}g g }}| df|dffD ]\  }}|j        g g }
}	|D ]'}t          ||d|j                  \  }}|	|z  }	|
|z  }
(t          j        |
d          \  }}t          j        |          }||                                         }
t          j	        |	          |                                         }	t          |	|
t          |j                            \  }	}
||	z  }||
z  }|                    ||d          }t          |           |S )	Nr9   r  r   )r  r  T)return_indexr  )
framealpha)rX   rY   r   r  r  r<   r  r  tolistrm   r  r   r	  r  )r  r  rN  	legend_axr  r  r  
huesizepltr  hdllblphdl_lbl_r  r  r	  s                    r"   _add_legendr    sY    (	488I		ykI"VG	h	w  
D ?&
 2C  ,Q&zWWW
dtt Ys666FAs*S//CC&--//C(3--$++--C ,C6Fz6W6WXXHCsNGcMFgv#>>FV$$$Mr$   r  r   coords_to_plot$MutableMapping[str, Hashable | None]default_guesstuple[str, ...]ignore_guess_kwargstuple[tuple[str, ...], ...]MutableMapping[str, Hashable]c                  	 d |                                 D             	t          	fd| j                                        D                       }t	          |||          D ]<\  }}}|                    |d           t          fd|D                       r|||<   =|                                 D ]\  }}t          | ||           |S )u  
    Guess what coords to plot if some of the values in coords_to_plot are None which
    happens when the user has not defined all available ways of visualizing
    the data.

    Parameters
    ----------
    darray : DataArray
        The DataArray to check for available coords.
    coords_to_plot : MutableMapping[str, Hashable]
        Coords defined by the user to plot.
    kwargs : dict
        Extra kwargs that will be sent to matplotlib.
    default_guess : Iterable[str], optional
        Default values and order to retrieve dims if values in dims_plot is
        missing, default: ("x", "hue", "size").
    ignore_guess_kwargs : tuple[tuple[str, ...], ...]
        Matplotlib arguments to ignore.

    Examples
    --------
    >>> ds = xr.tutorial.scatter_example_dataset(seed=42)
    >>> # Only guess x by default:
    >>> xr.plot.utils._guess_coords_to_plot(
    ...     ds.A,
    ...     coords_to_plot={"x": None, "z": None, "hue": None, "size": None},
    ...     kwargs={},
    ... )
    {'x': 'x', 'z': None, 'hue': None, 'size': None}

    >>> # Guess all plot dims with other default values:
    >>> xr.plot.utils._guess_coords_to_plot(
    ...     ds.A,
    ...     coords_to_plot={"x": None, "z": None, "hue": None, "size": None},
    ...     kwargs={},
    ...     default_guess=("x", "hue", "size"),
    ...     ignore_guess_kwargs=((), ("c", "color"), ("s",)),
    ... )
    {'x': 'x', 'z': None, 'hue': 'y', 'size': 'z'}

    >>> # Don't guess ´size´, since the matplotlib kwarg ´s´ has been defined:
    >>> xr.plot.utils._guess_coords_to_plot(
    ...     ds.A,
    ...     coords_to_plot={"x": None, "z": None, "hue": None, "size": None},
    ...     kwargs={"s": 5},
    ...     default_guess=("x", "hue", "size"),
    ...     ignore_guess_kwargs=((), ("c", "color"), ("s",)),
    ... )
    {'x': 'x', 'z': None, 'hue': 'y', 'size': None}

    >>> # Prioritize ´size´ over ´s´:
    >>> xr.plot.utils._guess_coords_to_plot(
    ...     ds.A,
    ...     coords_to_plot={"x": None, "z": None, "hue": None, "size": "x"},
    ...     kwargs={"s": 5},
    ...     default_guess=("x", "hue", "size"),
    ...     ignore_guess_kwargs=((), ("c", "color"), ("s",)),
    ... )
    {'x': 'y', 'z': None, 'hue': 'z', 'size': 'x'}
    c                    i | ]
\  }}|||S r   r   )r   r  r   s      r"   r  z)_guess_coords_to_plot.<locals>.<dictcomp>  s    UUUTQq}Aq}}}r$   c              3  H   K   | ]}|                                 v|V  d S r   )r  )r   r  coords_to_plot_exists     r"   r   z(_guess_coords_to_plot.<locals>.<genexpr>  sC        14H4O4O4Q4Q+Q+Q+Q+Q+Q+Q r$   Nc              3  H   K   | ]}                     |d           d u V  d S r   r  )r   ign_kwr  s     r"   r   z(_guess_coords_to_plot.<locals>.<genexpr>  sG       7
 7
17FJJvt$$,7
 7
 7
 7
 7
 7
r$   )itemsrZ   r   r!  r  r   r,  r   )
r   r  r  r  r  available_coordsr  r   ign_kwsr  s
     `      @r"   _guess_coords_to_plotr    s#   H VU^-A-A-C-CUUU    =%%''     }.>@STT $ $3a&&.3 7
 7
 7
 7
;B7
 7
 7
 4
 4
. !$N1 &&(( ) )3a((((r$   )
NNNNFNNTNF)
r   r   r   r   r   r   r   r   r   r   )FN)r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r5   r[   r   r   )NNNN)r   r   rl   r   r   r   r   r   r   r   r   r   )r   r   r   r   r  )r   )r   r[   r   r[   )rm   r   r   r   )rm   r   r   r   )r  r   r  r   r   r  )r  r   r  r   r  rx   r   r  )r   r   r'  r(  r   r   )r   r   )NNNNNN)r   r   r^  r_  r`  r_  ra  r   rb  r   rc  rd  re  rd  rf  rd  rg  rd  r   r   )r   )r   NF)NNNNF)rP  r  r   r  )r   r   rh   r)  r   r   )r   r   rh   r)  r   r.  )r   r0  rh   r)  r   r1  )NNN)r  rC  r  rC  r  r  r  r  r  r  r   r  )r  rC  r  rC  r  r[   )r  r  )r   r   r  r  r  rx   r  r  r  r  r   r  )^
__future__r   r  r   r   collections.abcr   r   r   r   r   r	   inspectr
   typingr   r   r   r   numpyr<   pandasr  xarray.core.indexesr   xarray.core.optionsr   xarray.core.pycompatr   xarray.core.utilsr   r   r?  r>  r_   matplotlib.axesr   rV   r   matplotlib.tickerr   numpy.typingr   xarray.core.dataarrayr   xarray.core.datasetr   xarray.core.typesr   r   r    r!   r   r  ro   r5  _LINEWIDTH_RANGEr#   r0   rR   r8   r   r   r   r   r   r   r   r   r   r  r  r   r&  r  r5  rC  rF  rT  r]  rs  r~  r  r  r  r  r  r  r(  r,  rC  r  r  r  r   r$   r"   <module>r     s   " " " " " " "       Q Q Q Q Q Q Q Q Q Q Q Q Q Q       " " " " " " 9 9 9 9 9 9 9 9 9 9 9 9         0 0 0 0 0 0 ' ' ' ' ' ' 0 0 0 0 0 0 9 9 9 9 9 9 9 9)).99 MMMM   FFF  $$$$$$++++++//////&&&&&&//////++++++========'''''''      ' "   
 
 
3 3 3l  N 
			] ] ] ]@;9 ;9 ;9 ;9D $ $ $ $ $P
 
 
 
0 '+ 	, , , , ,^# # # #   B B B B B0, , , ,	 	 	 	" " " "$*2 *2 *2 *2Z  "< < < <	? 	? 	?* * * *Z3 3 3
  "0 0 0J  ##!!. . . . .b6 6 6 6,. . . .h 
HLE$ E$ E$ E$ E$P   VKK@ @ @ @F  $- - -:P P Pf 
   
 
   
( ( ( (Vr r r r r r r rp	 !%" $$ $ $ $ $B& & & &Z &,7<V V V V V V Vs$   (A- -A76A7)B0 0B?>B?