a
    1$e                     @   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Zd dl	m
Z
 ddlmZ efddZd d
dZdd Zdd Zd!ddZeeZd"ddZeeZd#ddZeeZd$ddZd%ddZeeG dd deZdS )&    N)PlotAccessor)CategoricalDtype)Version   )docc                    s    fdd}|S )z&Helper to provide deprecation warning.c                     s6   t jd jdd  d dd  | i | d S )Nz{} is intended for internal r   z!use only, and will be deprecated.   
stacklevel)warningswarnformat__name__)argskwargsnewwarning_type N/var/www/html/django/DPS/env/lib/python3.9/site-packages/geopandas/plotting.pyold   s    zdeprecated.<locals>.oldr   )r   r   r   r   r   r   
deprecated   s    	r   Multic                 C   s   g g  }}| j j| sD| j sD|   sD| tt| fS t	| D ]j\}}|dur|j |r|js|j
D ]}|| || qtqL|du sL|jrqLqL|| || qL|t|fS )aV  
    Returns Series like geoms and index, except that any Multi geometries
    are split into their components and indices are repeated for all component
    in the same Multi geometry. At the same time, empty or missing geometries are
    filtered out.  Maintains 1:1 matching of geometry to value.

    Prefix specifies type of geometry to be flatten. 'Multi' for MultiPoint and similar,
    "Geom" for GeometryCollection.

    Returns
    -------
    components : list of geometry

    component_index : index array
        indices are repeated for all components in the same Multi geometry
    N)	geom_typestr
startswithanyis_emptyisnanparangelen	enumerategeomsappendarray)r"   prefix
componentsZcomponent_indexZixZgeompolyr   r   r   _sanitize_geoms   s$    




r(   c           	      C   s   ddl }ddlm} ddlm} t|j}|tdkr@ddg}ng d}|  D ]x\}}d	|v rl||rqPn:d
|v rt|t	rt
|dkrt|d |rqPn
||v rqPtjj|rPtj||dd| |< qPdS )a@  
    Most arguments to the plot functions must be a (single) value, or a sequence
    of values. This function checks each key-value pair in 'kwargs' and expands
    it (in place) to the correct length/formats with help of 'multiindex', unless
    the value appears to already be a valid (single) value for the key.
    r   N)is_color_like)Iterablez3.4markerpath_effects)r+   alphar,   color	linestyler   r   Zaxis)
matplotlibmatplotlib.colorsr)   typingr*   r   __version__items
isinstancetupler    pdapitypesis_list_liker   take)	r   
multiindexr1   r)   r*   ZmplZscalar_kwargsattvaluer   r   r   _expand_kwargsH   s.    


r@   c                    sh   ddl m} ddlm   j t| jjddddf g fdd| j	D R  }||fi |S )a|  Constructs a matplotlib patch from a Polygon geometry

    The `kwargs` are those supported by the matplotlib.patches.PathPatch class
    constructor. Returns an instance of matplotlib.patches.PathPatch.

    Example (using Shapely Point and a matplotlib axes)::

        b = shapely.geometry.Point(0, 0).buffer(1.0)
        patch = _PolygonPatch(b, fc='blue', ec='blue', alpha=0.5)
        ax.add_patch(patch)

    GeoPandas originally relied on the descartes package by Sean Gillies
    (BSD license, https://pypi.org/project/descartes) for PolygonPatch, but
    this dependency was removed in favor of the below matplotlib code.
    r   )	PathPatchPathNr   c                    s,   g | ]$} t |jd d d df qS Nr   )r   asarraycoords).0ringrB   r   r   
<listcomp>       z!_PolygonPatch.<locals>.<listcomp>)
Zmatplotlib.patchesrA   Zmatplotlib.pathrC   Zmake_compound_pathr   rE   ZexteriorrF   Z	interiors)Zpolygonr   rA   pathr   rB   r   _PolygonPatchn   s     rL   c                 K   s   ddl m} t|\}}	|dur0tj||	dd}dd | D }|durR||d< t||	 |dd	 |D fi |}
|dur|
t| |
	| d
|vr|

|| | j|
dd |   |
S )a  
    Plots a collection of Polygon and MultiPolygon geometries to `ax`

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        where shapes will be plotted
    geoms : a sequence of `N` Polygons and/or MultiPolygons (can be mixed)

    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).
        Otherwise follows `color` / `facecolor` kwargs.
    edgecolor : single color or sequence of `N` colors
        Color for the edge of the polygons
    facecolor : single color or sequence of `N` colors
        Color to fill the polygons. Cannot be used together with `values`.
    color : single color or sequence of `N` colors
        Sets both `edgecolor` and `facecolor`
    **kwargs
        Additional keyword arguments passed to the collection

    Returns
    -------
    collection : matplotlib.collections.Collection that was plotted
    r   )PatchCollectionNr0   c                 S   s   i | ]\}}|d vr||qS )
markersizer+   r   rG   r>   r?   r   r   r   
<dictcomp>   s   z,_plot_polygon_collection.<locals>.<dictcomp>r.   c                 S   s   g | ]}t |qS r   )rL   )rG   r'   r   r   r   rI      rJ   z,_plot_polygon_collection.<locals>.<listcomp>normTZautolim)matplotlib.collectionsrM   r(   r   r<   r5   r@   	set_arrayrE   set_cmapset_climadd_collectionautoscale_view)axr"   valuesr.   cmapvminvmaxr   rM   r=   
collectionr   r   r   _plot_polygon_collection   s&    

r`   c                 K   s   ddl m} t|\}}	|dur0tj||	dd}dd | D }|durR||d< t||	 dd	 |D }
||
fi |}|dur|t| |	| d
|vr|
|| | j|dd |   |S )a  
    Plots a collection of LineString and MultiLineString geometries to `ax`

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        where shapes will be plotted
    geoms : a sequence of `N` LineStrings and/or MultiLineStrings (can be
            mixed)
    values : a sequence of `N` values, optional
        Values will be mapped to colors using vmin/vmax/cmap. They should
        have 1:1 correspondence with the geometries (not their components).
    color : single color or sequence of `N` colors
        Cannot be used together with `values`.

    Returns
    -------
    collection : matplotlib.collections.Collection that was plotted
    r   )LineCollectionNr0   c                 S   s   i | ]\}}|d vr||qS rN   r   rP   r   r   r   rQ      s   z/_plot_linestring_collection.<locals>.<dictcomp>r.   c                 S   s(   g | ] }t |jd d d df qS rD   )r   r$   rF   )rG   Z
linestringr   r   r   rI      rJ   z/_plot_linestring_collection.<locals>.<listcomp>rR   TrS   )rT   ra   r(   r   r<   r5   r@   rU   rE   rV   rW   rX   rY   )rZ   r"   r[   r.   r\   r]   r^   r   ra   r=   segmentsr_   r   r   r   _plot_linestring_collection   s(    

rc   oc	                 K   s   |dur|durt dt|\}}
dd |D }dd |D }|durP||	d< |dur`||	d< |durp||	d< |dur||	d	< t|	|
 d
|	vr| j||f|||d|	}n| j||fd|i|	}|S )a  
    Plots a collection of Point and MultiPoint geometries to `ax`

    Parameters
    ----------
    ax : matplotlib.axes.Axes
        where shapes will be plotted
    geoms : sequence of `N` Points or MultiPoints

    values : a sequence of `N` values, optional
        Values mapped to colors using vmin, vmax, and cmap.
        Cannot be specified together with `color`.
    markersize : scalar or array-like, optional
        Size of the markers. Note that under the hood ``scatter`` is
        used, so the specified value will be proportional to the
        area of the marker (size in points^2).

    Returns
    -------
    collection : matplotlib.collections.Collection that was plotted
    Nz3Can only specify one of 'values' and 'color' kwargsc                 S   s   g | ]}|j s|jnd qS N)r   xrG   pr   r   r   rI   )  rJ   z*_plot_point_collection.<locals>.<listcomp>c                 S   s   g | ]}|j s|jnd qS re   )r   yrg   r   r   r   rI   *  rJ   csr.   r+   rR   r]   r^   r\   r\   )
ValueErrorr(   r@   Zscatter)rZ   r"   r[   r.   r\   r]   r^   r+   rO   r   r=   rf   ri   r_   r   r   r   _plot_point_collection  s$    !
rn   autoc                 K   s~  d|v r"t jdtdd |d}d|v rDt jdtdd |d}zddlm} W n tyn   td	Y n0 |du r|j|d
\}}|dkr| jr| jj	r| j
}	t|	d |	d g}
|dt|
tj d   q|d n|dur|| | jrt jdtdd |S | j r4t jdtdd |S tjj|oRt|t| k}d}|durtt| }t|dr||j }|d| |d< |d| |d< t| j dd\}}|rtj!||ddnd}|rt"|tj#r|$| j%}|rtj!||ddn|}t&'|}|j(}t)|dk|dkB }t)|dk|dkB |dkB }t)|dk|dkB }|| }|js|dd}|r|| n|}|dur|}|r|| nd}t*|||f||d| || }|js$|r|| nd}|r|| n|}t+|||f||d | || }|jsr|rB|| nd}|rT|| n|}t,|||f||d | |-  |S )!aC  
    Plot a GeoSeries.

    Generate a plot of a GeoSeries geometry with matplotlib.

    Parameters
    ----------
    s : Series
        The GeoSeries to be plotted. Currently Polygon,
        MultiPolygon, LineString, MultiLineString, Point and MultiPoint
        geometries can be plotted.
    cmap : str (default None)
        The name of a colormap recognized by matplotlib. Any
        colormap will work, but categorical colormaps are
        generally recommended. Examples of useful discrete
        colormaps include:

            tab10, tab20, Accent, Dark2, Paired, Pastel1, Set1, Set2

    color : str, np.array, pd.Series, List (default None)
        If specified, all objects will be colored uniformly.
    ax : matplotlib.pyplot.Artist (default None)
        axes on which to draw the plot
    figsize : pair of floats (default None)
        Size of the resulting matplotlib.figure.Figure. If the argument
        ax is given explicitly, figsize is ignored.
    aspect : 'auto', 'equal', None or float (default 'auto')
        Set aspect of axis. If 'auto', the default aspect for map plots is 'equal'; if
        however data are not projected (coordinates are long/lat), the aspect is by
        default set to 1/cos(s_y * pi/180) with s_y the y coordinate of the middle of
        the GeoSeries (the mean of the y range of bounding box) so that a long/lat
        square appears square in the middle of the plot. This implies an
        Equirectangular projection. If None, the aspect of `ax` won't be changed. It can
        also be set manually (float) as the ratio of y-unit to x-unit.
    **style_kwds : dict
        Color options to be passed on to the actual plot function, such
        as ``edgecolor``, ``facecolor``, ``linewidth``, ``markersize``,
        ``alpha``.

    Returns
    -------
    ax : matplotlib axes instance
    colormapU'colormap' is deprecated, please use 'cmap' instead (for consistency with matplotlib)   r   axesK'axes' is deprecated, please use 'ax' instead (for consistency with pandas)r   NThe matplotlib package is required for plotting in geopandas. You can install it using 'conda install -c conda-forge matplotlib' or 'pip install matplotlib'.figsizero   r      equalzNThe GeoSeries you are attempting to plot is empty. Nothing has been displayed.zeThe GeoSeries you are attempting to plot is composed of empty geometries. Nothing has been displayed.Nr]   r^   Geomr%   r0   PolygonMultiPolygon
LineStringMultiLineString
LinearRingPoint
MultiPoint	facecolor)r   r\   )r.   r\   ).r
   r   FutureWarningpopmatplotlib.pyplotpyplotImportErrorsubplotscrsis_geographictotal_boundsr   mean
set_aspectcospiemptyUserWarningr   allr8   r9   r:   r;   r    r   hasattrrz   getminmaxr(   geometryr<   r6   Seriesreindexindex	geopandas	GeoSeriesr   rE   r`   rc   rn   draw)rk   r\   r.   rZ   rw   aspect
style_kwdspltfigboundsy_coordZcolor_givenr[   r"   r=   Z
expl_colorexpl_series
geom_typespoly_idxline_idx	point_idxpolysr   Zcolor_Zvalues_linespointsr   r   r   plot_seriesD  s    .


 
 



r   F   c           9      K   s	  d|v r"t jdtdd |d}d|v rDt jdtdd |d}|durh|durht jdtdd d}zd	dlm} W n ty   td
Y n0 |du r|durtd|j	|d\}}|dkr | j
r| j
jr| j}t|d |d g}|dt|tj d   n
|d n|dur4|| |durF| }| jrbt jdtdd |S t|trx| | j}|du rt| jf||||||d|S t|tjtjfr|jd	 | jd	 krtdn|}t|tjr|| j}n| | }t|jt r$|durtdd}n@tj!j"#|js`tj!j"$|js`tj!j"%|js`|rdd}tj&t'|dd}|durd}zd	dl(}W n ty   t|Y n0 t)|j*t)dk rt||du ri }d|vr|	|d< |j+t&||  |fi |}d}|durdd|v rdt,|d |j-krTtd.t,|d |j-nt/|d}n\d}|durd|v r|d}|0|}|dur|dd }nd }|sd!d" |D }tj1tj2gt,| |j3dd#}tj1j4|j5|j3dd#|| < |du rd$}|r|du rd%}tj1||d&} t/| j6}t/t7|| | ' @  }!|!rdtd'.|!| j8|  }|
du r~d	n|
}
|du rt,|d n|}|rt9|d	 D ]}"t:||"|d	 }q|
du r|t;|  < n|
}#|du r
|t;|  = n|}$t>| jd(d)\}%}&tj?||&d	d*}tj?||&d	d*}t@A|%}'|'jB}(t&|(d+k|(d,kB })t&|(d-k|(d.kB |(d/kB }*t&|(d0k|(d1kB }+|'|)tC|@  },||)tC|@  }-|,jstD||,|-f|#|$|d2| |'|*tC|@  }.||*tC|@  }-|.js*tE||.|-f|#|$|d2| |'|+tC|@  }/||+tC|@  }-|/jst|tjrtj?||&d	d*}||+tC|@  }tF||/|-f|#|$||d3| |'| j }0|dur|0r|rd4|vr||d4< | }1|1G| t|'| fd5|i|1 |r|s|du ri }d|v r0|d d	d6lHmI}2 d	d7lJmK}3 d	d8lLmM}4 |Nd9d}5|5sr|3|#|$d:}5|4jO|5|d;}6|r|dur|}g }7tP|D ]:\}8} |7Q|2d	gd	gd<d=|Nd>dd?|6R|8d	d@ q|durj|0rjd4|1v r|1d4 |1dA< |7Q|2d	gd	gd<d=|1Nd>dd?|1NdAd|1NdBd|1NdC|1NdBd rLdnd	dD	 |Q|1NdEdF |SdGd |SdHdI |SdJ|7 |Sd| |jTf i | nJ|dur|SdK| n|Sd5| |6UtVg  |W jX|6fi | |Y  |S )La  
    Plot a GeoDataFrame.

    Generate a plot of a GeoDataFrame with matplotlib.  If a
    column is specified, the plot coloring will be based on values
    in that column.

    Parameters
    ----------
    column : str, np.array, pd.Series (default None)
        The name of the dataframe column, np.array, or pd.Series to be plotted.
        If np.array or pd.Series are used then it must have same length as
        dataframe. Values are used to color the plot. Ignored if `color` is
        also set.
    kind: str
        The kind of plots to produce. The default is to create a map ("geo").
        Other supported kinds of plots from pandas:

        - 'line' : line plot
        - 'bar' : vertical bar plot
        - 'barh' : horizontal bar plot
        - 'hist' : histogram
        - 'box' : BoxPlot
        - 'kde' : Kernel Density Estimation plot
        - 'density' : same as 'kde'
        - 'area' : area plot
        - 'pie' : pie plot
        - 'scatter' : scatter plot
        - 'hexbin' : hexbin plot.
    cmap : str (default None)
        The name of a colormap recognized by matplotlib.
    color : str, np.array, pd.Series (default None)
        If specified, all objects will be colored uniformly.
    ax : matplotlib.pyplot.Artist (default None)
        axes on which to draw the plot
    cax : matplotlib.pyplot Artist (default None)
        axes on which to draw the legend in case of color map.
    categorical : bool (default False)
        If False, cmap will reflect numerical values of the
        column being plotted.  For non-numerical columns, this
        will be set to True.
    legend : bool (default False)
        Plot a legend. Ignored if no `column` is given, or if `color` is given.
    scheme : str (default None)
        Name of a choropleth classification scheme (requires mapclassify).
        A mapclassify.MapClassifier object will be used
        under the hood. Supported are all schemes provided by mapclassify (e.g.
        'BoxPlot', 'EqualInterval', 'FisherJenks', 'FisherJenksSampled',
        'HeadTailBreaks', 'JenksCaspall', 'JenksCaspallForced',
        'JenksCaspallSampled', 'MaxP', 'MaximumBreaks',
        'NaturalBreaks', 'Quantiles', 'Percentiles', 'StdMean',
        'UserDefined'). Arguments can be passed in classification_kwds.
    k : int (default 5)
        Number of classes (ignored if scheme is None)
    vmin : None or float (default None)
        Minimum value of cmap. If None, the minimum data value
        in the column to be plotted is used.
    vmax : None or float (default None)
        Maximum value of cmap. If None, the maximum data value
        in the column to be plotted is used.
    markersize : str or float or sequence (default None)
        Only applies to point geometries within a frame.
        If a str, will use the values in the column of the frame specified
        by markersize to set the size of markers. Otherwise can be a value
        to apply to all points, or a sequence of the same length as the
        number of points.
    figsize : tuple of integers (default None)
        Size of the resulting matplotlib.figure.Figure. If the argument
        axes is given explicitly, figsize is ignored.
    legend_kwds : dict (default None)
        Keyword arguments to pass to :func:`matplotlib.pyplot.legend` or
        :func:`matplotlib.pyplot.colorbar`.
        Additional accepted keywords when `scheme` is specified:

        fmt : string
            A formatting specification for the bin edges of the classes in the
            legend. For example, to have no decimals: ``{"fmt": "{:.0f}"}``.
        labels : list-like
            A list of legend labels to override the auto-generated labels.
            Needs to have the same number of elements as the number of
            classes (`k`).
        interval : boolean (default False)
            An option to control brackets from mapclassify legend.
            If True, open/closed interval brackets are shown in the legend.
    categories : list-like
        Ordered list-like object of categories to be used for categorical plot.
    classification_kwds : dict (default None)
        Keyword arguments to pass to mapclassify
    missing_kwds : dict (default None)
        Keyword arguments specifying color options (as style_kwds)
        to be passed on to geometries with missing values in addition to
        or overwriting other style kwds. If None, geometries with missing
        values are not plotted.
    aspect : 'auto', 'equal', None or float (default 'auto')
        Set aspect of axis. If 'auto', the default aspect for map plots is 'equal'; if
        however data are not projected (coordinates are long/lat), the aspect is by
        default set to 1/cos(df_y * pi/180) with df_y the y coordinate of the middle of
        the GeoDataFrame (the mean of the y range of bounding box) so that a long/lat
        square appears square in the middle of the plot. This implies an
        Equirectangular projection. If None, the aspect of `ax` won't be changed. It can
        also be set manually (float) as the ratio of y-unit to x-unit.

    **style_kwds : dict
        Style options to be passed on to the actual plot function, such
        as ``edgecolor``, ``facecolor``, ``linewidth``, ``markersize``,
        ``alpha``.

    Returns
    -------
    ax : matplotlib axes instance

    Examples
    --------
    >>> import geodatasets
    >>> df = geopandas.read_file(geodatasets.get_path("nybb"))
    >>> df.head()  # doctest: +SKIP
       BoroCode  ...                                           geometry
    0         5  ...  MULTIPOLYGON (((970217.022 145643.332, 970227....
    1         4  ...  MULTIPOLYGON (((1029606.077 156073.814, 102957...
    2         3  ...  MULTIPOLYGON (((1021176.479 151374.797, 102100...
    3         1  ...  MULTIPOLYGON (((981219.056 188655.316, 980940....
    4         2  ...  MULTIPOLYGON (((1012821.806 229228.265, 101278...

    >>> df.plot("BoroName", cmap="Set1")  # doctest: +SKIP

    See the User Guide page :doc:`../../user_guide/mapping` for details.

    rp   rq   rr   r   rs   rt   Nz7Only specify one of 'column' or 'color'. Using 'color'.r   ru   z%'ax' can not be None if 'cax' is not.rv   ro   r   rx   ry   zQThe GeoDataFrame you are attempting to plot is empty. Nothing has been displayed.)r\   r.   rZ   rw   rO   r   z=The dataframe and given column have different number of rows.z=Cannot specify 'categories' when column has categorical dtypeTbool)dtypezMThe 'mapclassify' package (>= 2.4.0) is required to use the 'scheme' keyword.z2.4.0klabelszJNumber of labels must match number of bins, received {} labels for {} binsz{:.2f}fmtintervalFc                 S   s   g | ]}|d d qS )r   r   )rG   rj   r   r   r   rI   #  rJ   z"plot_dataframe.<locals>.<listcomp>)
categoriesZorderedZviridisZtab10)r   zHColumn contains values not listed in categories. Missing categories: {}.r{   r|   r0   r}   r~   r   r   r   r   r   rl   )r]   r^   rO   r\   r.   rZ   )Line2D)	Normalize)cmrR   )r]   r^   )rR   r\   nonerd   r-   
   )r/   r+   r-   rO   markerfacecolormarkeredgewidthr   Z	edgecolorZ	linewidth)r/   r+   r-   rO   r   Zmarkeredgecolorr   labelNaNZ	numpointslocbestZhandlescax)Zr
   r   r   r   r   r   r   r   rm   r   r   r   r   r   r   r   r   r   copyr   r6   r   r[   r   r   Zndarrayr8   r   shaper   r   r   r   r9   r:   Zis_object_dtypeZis_bool_dtypeZis_string_dtyperE   r   mapclassifyr   r4   Zclassifyr    r   r   listZget_legend_classesZCategoricalnanZbinsZ
from_codesZybr   uniquecodeswhereinsertisnanr   r   r(   r<   r   r   r   invertr`   rc   rn   updateZmatplotlib.linesr   r2   r   r1   r   r   ZScalarMappabler!   r#   Zto_rgba
setdefaultlegendrU   r$   Z
get_figureZcolorbarr   )9dfcolumnr\   r.   rZ   r   Zcategoricalr   schemer   r]   r^   rO   rw   Zlegend_kwdsr   Zclassification_kwdsZmissing_kwdsr   r   r   r   r   r   r[   Znan_idxZmc_errr   Zbinningr   r   Zshow_intervalcatmissingnZmnZmxr"   r=   r   r   r   r   r   r   Zsubsetr   r   Zmissing_dataZmerged_kwdsr   r   r   rR   Zn_cmapZpatchesr?   r   r   r   plot_dataframe  s"    



 















""












r   c                   @   s"   e Zd ZejZdd Zdd ZdS )GeoplotAccessorc                 O   sf   | j  }|dd}|dkr4t|g|R i |S || jv rTt|f d|i|S t| dd S )Nkindgeoz is not a valid plot kind)_parentr   r   r   _pandas_kindsr   rm   )selfr   r   datar   r   r   r   __call__  s    

zGeoplotAccessor.__call__c                 O   s   | |ddi|S )Nr   r   r   )r   r   r   r   r   r   r     s    zGeoplotAccessor.geoN)r   
__module____qualname__r   Z
_all_kindsr   r   r   r   r   r   r   r     s   r   )r   )NNNNN)NNNNN)NNNNNrd   N)NNNNro   )NNNNNFFNr   NNNNNNNNro   )r
   numpyr   Zpandasr8   Zpandas.plottingr   r   r   Zpackaging.versionr   Z
_decoratorr   r   r   r(   r@   rL   r`   Zplot_polygon_collectionrc   Zplot_linestring_collectionrn   Zplot_point_collectionr   r   r   r   r   r   r   <module>   sj   
*& 
= 
7       
? 
 1                  
   \