a
    İa!Q                     @   s   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
mZmZmZmZmZmZ eddgZd	d
 ZdddZdd ZG dd dZdd Zedd Zedd Zedd ZdS )    N   )	broadcast   )_easy_facetgrid)_add_colorbar_get_nice_quiver_magnitude_is_numeric_process_cmap_cbar_kwargsget_axislabel_from_attrspltg      2@g      R@c              	   C   s  t | j }dd|}||vr2td| ||vrFtd| |d urb||vrbtd| |rt| | j}	|d u r|	rdnd}|	s|dkrtd| |d u s|d	u r|dkrd	nd
}
|dkrd	nd
}qd
}
d
}n |d	u r|dvrtdd
}d
}
|s|d u rF|dkrFd	}|rJd	}
|s2d}n|dkrJtdnd
}|sZ|d u r|dkr|rd	}
|szd}n|dkrtd|d ur|dvrtd|rt| | }| | }nd }d }|
||||t| | t| | |dS )Nz must be one of ({:s})z, xy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ylabelr   )	setZ	variableskeysformatjoin
ValueErrorr   valuesr   )dsr   r   r   r   	add_guidefuncnameZdvarsZ	error_msgZhue_is_numericr   r   r   r    r%   7lib/python3.9/site-packages/xarray/plot/dataset_plot.py_infer_meta_data   sz    




r'   c                 C   s   ddg}| | | | g}|r4| | |  | d |rP| | |  | d tt|t| }	|	d |	d d d d}
|r|	d |
d< |r|	d }|d u rt||}|jt|j|j	
  j	|jd|
d< |
S )Nr   r   r   size)r   r   r   sizes)datar)   )appenddictzipr   _parse_sizecopynpZreshapelocr!   ravelshape)r"   r   r   r   
markersize	size_normsize_mappingZbroadcast_keysZto_broadcastZbroadcastedr*   r(   r%   r%   r&   _infer_scatter_datai   s(    



r7   c                 C   s  t j}| d u rd S | j } t| sNt| }tddt| d d d }nt	t|  }}t
\}}|d u r~|j }n2t|tr|jj| }nt||jjsd}t|d|_| s|t| ||}t||||   }	|j rd|	|j< tt||	}
t|
S )Nr   z7``size_norm`` must be None, tuple, or Normalize object.Tr   )r   Z
matplotlibr!   flattenr   r0   uniqueZarangelensort_MARKERSIZE_RANGEcolors	Normalize
isinstancetupler    ZclipZscaledZasarraymaskanyr,   r-   pdZSeries)r*   normZmpllevelsZnumbersZ	min_widthZ	max_widtherrZsclZwidthsr)   r%   r%   r&   r.      s2    

 


r.   c                   @   s    e Zd ZdZdd Zdd ZdS )_Dataset_PlotMethodszp
    Enables use of xarray.plot functions as attributes on a Dataset.
    For example, Dataset.plot.scatter
    c                 C   s
   || _ d S )N)_ds)selfdatasetr%   r%   r&   __init__   s    z_Dataset_PlotMethods.__init__c                 O   s   t dd S )Nz^Dataset.plot cannot be called directly. Use an explicit plot method, e.g. ds.plot.scatter(...))r    )rJ   argskwargsr%   r%   r&   __call__   s    z_Dataset_PlotMethods.__call__N)__name__
__module____qualname____doc__rL   rO   r%   r%   r%   r&   rH      s   rH   c                    sX   d}j  d| _ tdfdd	 t d	 fdd	}tt|j|  S )
Na  
    Parameters
    ----------

    ds : Dataset
    x, y : str
        Variable names for the *x* and *y* grid positions.
    u, v : str, optional
        Variable names for the *u* and *v* velocities
        (in *x* and *y* direction, respectively; quiver/streamplot plots only).
    hue: str, optional
        Variable by which to color scatter points or arrows.
    hue_style: {'continuous', 'discrete'}, optional
        How to use the ``hue`` variable:

        - ``'continuous'`` -- continuous color scale
          (default for numeric ``hue`` variables)
        - ``'discrete'`` -- a color for each unique value, using the default color cycle
          (default for non-numeric ``hue`` variables)
    markersize: str, optional
        Variable by which to vary the size of scattered points (scatter plot only).
    size_norm: matplotlib.colors.Normalize or tuple, optional
        Used to normalize the ``markersize`` variable.
        If a tuple is passed, the values will be passed to
        :py:class:`matplotlib:matplotlib.colors.Normalize` as arguments.
        Default: no normalization (``vmin=None``, ``vmax=None``, ``clip=False``).
    scale: scalar, optional
        Quiver only. Number of data units per arrow length unit.
        Use this to control the length of the arrows: larger values lead to
        smaller arrows.
    add_guide: bool, optional, default: True
        Add a guide that depends on ``hue_style``:

        - ``'continuous'`` -- build a colorbar
        - ``'discrete'`` -- build a legend
    row : str, optional
        If passed, make row faceted plots on this dimension name.
    col : str, optional
        If passed, make column faceted plots on this dimension name.
    col_wrap : int, optional
        Use together with ``col`` to wrap faceted plots.
    ax : matplotlib axes object, optional
        If ``None``, use the current axes. Not applicable when using facets.
    subplot_kws : dict, optional
        Dictionary of keyword arguments for Matplotlib subplots
        (see :py:meth:`matplotlib:matplotlib.figure.Figure.add_subplot`).
        Only applies to FacetGrid plotting.
    aspect : scalar, optional
        Aspect ratio of plot, so that ``aspect * size`` gives the *width* in
        inches. Only used if a ``size`` is provided.
    size : scalar, optional
        If provided, create a new figure for the plot with the given size:
        *height* (in inches) of each plot. See also: ``aspect``.
    norm : matplotlib.colors.Normalize, optional
        If ``norm`` has ``vmin`` or ``vmax`` specified, the corresponding
        kwarg must be ``None``.
    vmin, vmax : float, optional
        Values to anchor the colormap, otherwise they are inferred from the
        data and other keyword arguments. When a diverging dataset is inferred,
        setting one of these values will fix the other by symmetry around
        ``center``. Setting both values prevents use of a diverging colormap.
        If discrete levels are provided as an explicit list, both of these
        values are ignored.
    cmap : matplotlib colormap name or colormap, optional
        The mapping from data values to color space. Either a
        Matplotlib colormap name or object. If not provided, this will
        be either ``'viridis'`` (if the function infers a sequential
        dataset) or ``'RdBu_r'`` (if the function infers a diverging
        dataset).
        See :doc:`Choosing Colormaps in Matplotlib <matplotlib:tutorials/colors/colormaps>`
        for more information.

        If *seaborn* is installed, ``cmap`` may also be a
        `seaborn color palette <https://seaborn.pydata.org/tutorial/color_palettes.html>`_.
        Note: if ``cmap`` is a seaborn color palette,
        ``levels`` must also be specified.
    colors : str or array-like of color-like, optional
        A single color or a list of colors. The ``levels`` argument
        is required.
    center : float, optional
        The value at which to center the colormap. Passing this value implies
        use of a diverging colormap. Setting it to ``False`` prevents use of a
        diverging colormap.
    robust : bool, optional
        If ``True`` and ``vmin`` or ``vmax`` are absent, the colormap range is
        computed with 2nd and 98th percentiles instead of the extreme values.
    extend : {'neither', 'both', 'min', 'max'}, optional
        How to draw arrows extending the colorbar beyond its limits. If not
        provided, ``extend`` is inferred from ``vmin``, ``vmax`` and the data limits.
    levels : int or array-like, optional
        Split the colormap (``cmap``) into discrete color intervals. If an integer
        is provided, "nice" levels are chosen based on the data range: this can
        imply that the final number of levels is not exactly the expected one.
        Setting ``vmin`` and/or ``vmax`` with ``levels=N`` is equivalent to
        setting ``levels=np.linspace(vmin, vmax, N)``.
    **kwargs : optional
        Additional keyword arguments to wrapped Matplotlib function.
    
Tc           (         s|  | dd}|r| d} nt| |||||jd} | d }|sD|rt  }!t j |!d< | |!d< dD ]
}"|!|"= qjtf d	d
i|!|S | dd }
t|
|||	}	|dkr|d ur|r| d }| d  nt| | j	fi t \ } fdddD }#ni }#|d us|d ur*jdvr*t
df | |||	|||||#d	|}$|rV|$S | dd rt|	| d | dd r|	| d | d r|	j|$| dd d | d r|d u ri n|}d|vr| dd |d< t|$|	||  | d rHt| | | | }%| | jdd}&|	j|$dd |%|% d!|& d"d#d$ jdv rb| |  }'n| |  }'|	|' |$S )%N_is_facetgridF	meta_data)r$   r   plotfuncr*   )rV   rN   r"   kindrK   figsizer   cbar_kwargscmap_paramsc                    s   i | ]}| | qS r%   r%   ).0Zvvr[   r%   r&   
<dictcomp>l  s   z0_dsplot.<locals>.newplotfunc.<locals>.<dictcomp>)vminvmaxrE   cmapr   z5u, v are only allowed for quiver or streamplot plots.)	r"   r   r   axuvr   r   r[   r   r   r   r   )Zhandlestitler   labelr   units g333333?g?rT   EZfigure)XYUrf   ZlabelposZcoordinates)popr'   rP   localsr/   globalsr   r
   r	   r!   r    getZ
set_xlabelZ
set_ylabelZlegendr   r   attrsZ	quiverkeyZ_title_for_sliceZ	set_title)(r"   r   r   rc   rd   r   r   colrowrb   rY   r(   col_wrapsharexshareyaspectsubplot_kwsr#   rZ   cbar_axr_   r`   rE   infer_intervalscenterrF   robustr>   extendra   rN   rU   rV   allargsargZcmap_params_subset	primitiveZ	magnituderg   re   )rW   r]   r&   newplotfunc'  s    #




 






z_dsplot.<locals>.newplotfuncc           !         s8   t  }| j|d< || dD ]
} || = q f i |S )z
        The method should have the same signature as the function.

        This just makes the method work on Plotmethods objects,
        and passes all the other arguments straight through.
        r"   )_PlotMethods_objr   rN   )rn   rI   update)!r   r   r   rc   rd   r   r   rr   rs   rb   rY   rt   ru   rv   rw   r(   rx   r#   rZ   ry   r_   r`   rE   rz   r{   rF   r|   r>   r}   ra   rN   r~   r   )r   r%   r&   
plotmethod  s    (

z_dsplot.<locals>.plotmethod)NNNNNNNNNNNNTTNNNNNNNNNNNNNNN)NNNNNNNNNNNTTNNNNNNNNNNNNNNNN)rS   	functoolswrapssetattrrH   rP   )rW   Z	commondocr   r%   )r   rW   r&   _dsplot   s    d                                                           /r   c              	   K   s  d|v sd|v rt d|d}|d}|d}|dd}|d	d}	|d
d}
|dd |dd t| |||||	|
}|dkr.g }t|d j D ]}|d |k}|d dur|j|d j|ddj	 d |
|j|d j|ddj	 |d j|ddj	 fd|i| qn|du sB|dkr|d durf|j|d j d |d dur|j|d j d |j|d j |d j fi ||}|S )zx
    Scatter Dataset data variables against each other.

    Wraps :py:func:`matplotlib:matplotlib.pyplot.scatter`.
    r   r   z]Dataset.plot.scatter does not accept 'add_colorbar' or 'add_legend'. Use 'add_guide' instead.r[   r   r   r4   Nr5   r6   rc   rd   r   r)   T)Zdrop)sr   r   rf   r   )c)r    rm   r7   rD   r:   r!   r2   r   wherer9   r+   scatter)r"   r   r   rb   rN   r[   r   r   r4   r5   r6   r*   r   rf   rB   r%   r%   r&   r     sT    



 	r   c                 K   s   |du s |du s |du s |du r(t dt| | | | | | | | \}}}}|j|j|j|jg}|d}|d}	|r|| | j |	d st|	d|	d|	d< |d |d	d
 |j|i ||	}
|
S )zaQuiver plot of Dataset variables.

    Wraps :py:func:`matplotlib:matplotlib.pyplot.quiver`.
    Nz)Must specify x, y, u, v for quiver plots.r   r[   rE   r_   r`   r   ZpivotZmiddle)	r    r   r!   rm   r+   r   r?   
setdefaultr   )r"   r   r   rb   rc   rd   rN   rM   r   r[   hdlr%   r%   r&   r     s      &


r   c                 K   s  |du s |du s |du s |du r(t dt| | jdkrH| | jd }t| | jdkrh| | jd }|dur|du rt| | jt|g }|dur|du rt| | jt|g }t| | | | | | | | \}}}}|dur"|dur"|||}|||}|||}|||}|j|j|j|jg}	|d}
|d}|
r| |
 j|d< |d st	|d	|d
|d< |d |j
|	i ||}|jS )zjPlot streamlines of Dataset variables.

    Wraps :py:func:`matplotlib:matplotlib.pyplot.streamplot`.
    Nz-Must specify x, y, u, v for streamplot plots.r   r   r   r[   ZcolorrE   r_   r`   r   )r    r;   Zdimsr   r   Z	transposer!   rm   r   r?   r   lines)r"   r   r   rb   rc   rd   rN   ZxdimZydimrM   r   r[   r   r%   r%   r&   r   ;  s8     &



r   )N)r   Znumpyr0   ZpandasrD   Zcore.alignmentr   Z	facetgridr   Zutilsr   r   r   r	   r
   r   r   Zarrayr=   r'   r7   r.   rH   r   r   r   r   r%   r%   r%   r&   <module>   s&   $S
 '  "
<
