a
    <b3U                     @  s   d Z ddlmZ ddlZddlmZmZ ddlZddlZ	ddl
mZ ddlm  mZ ddlmZ ddlZddlmZmZmZ ddlmZ erddlmZ ejG d	d
 d
ZdddZdd Zdd Z dd Z!dS )z
Module consolidating common testing functions for checking plotting.

Currently all plotting tests are marked as slow via
``pytestmark = pytest.mark.slow`` at the module level.
    )annotationsN)TYPE_CHECKINGSequence)cache_readonly)is_list_like)	DataFrameSeriesto_datetimeAxesc                   @  s   e Zd ZdZdd Zdd Zedd Zedd	 Zd9ddZ	d:ddZ
dd Zd;ddZd<ddddddZdd Zd=ddZdd Zd>d d!Zd?d#d$Zd@d%d&Zd'd( Zd)d* ZdAd,d-ZdBd.d/Zi fd0d1ZdCd3d4Zd5d6 Zd7d8 Zd
S )DTestPlotBasezE
    This is a common base class used for various plotting tests
    c                 C  sh  dd l }ddlm} || _|  d| _d| _| | _| | _| | _|	 | _	d| _
d| _d| _d| _d	}td
 tjjddg|d}tjjg d|d}t||tjjdd|dtjjdd|dtjjd|dttjj| j| j|tjdd| _W d    n1 s0    Y  t | _ttjjddtjjddtdtjjdd d| _d S )Nr   )compatl     j+2Zl     ReZ      )g@g333333@leftd   *   ZMaleZFemale)size)ABCB             )r   dtype)gender	classroomheightZweightcategorydatetime   )
matplotlibZpandas.plotting._matplotlibr   Z
rcdefaultsZstart_date_to_int64Zend_date_to_int64Zmpl_ge_2_2_3Zmpl_ge_3_0_0mpl_ge_3_1_0Zmpl_ge_3_2_0Zbp_n_objectsZpolycollection_factordefault_figsizeZdefault_tick_positiontmZ
RNGContextnprandomchoicer   normalrandintr	   Zint64Zhist_dfZmakeTimeDataFrameZtdfuniformZarangeZ	hexbin_df)selfmethodmplr   nr   r    r0   l/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/pandas/tests/plotting/common.pysetup_method*   sR    



&
zTestPlotBase.setup_methodc                 C  s   t   d S N)r%   close)r,   r-   r0   r0   r1   teardown_methoda   s    zTestPlotBase.teardown_methodc                 C  s   dd l m} |S Nr   )matplotlib.pyplotpyplot)r,   pltr0   r0   r1   r9   d   s    zTestPlotBase.pltc                 C  s   dd l m} |jS r6   )Zmatplotlib.colorscolorsZcolorConverter)r,   r:   r0   r0   r1   colorconverterj   s    zTestPlotBase.colorconverterNTc                 C  sf   |r|du rt d| |}|D ]>}|rP| dus:J | |  | q"| du s"J q"dS )aQ  
        Check each axes has expected legend labels

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        labels : list-like
            expected legend labels
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        Nz-labels must be specified when visible is True)
ValueError_flatten_visible
get_legend_check_text_labelsZ	get_texts)r,   axeslabelsvisibleaxr0   r0   r1   _check_legend_labelsp   s    
z!TestPlotBase._check_legend_labelsc                 C  sT   |r|du rt d|r@| \}}dd |D }||ksPJ n| du sPJ dS )aB  
        Check ax has expected legend markers

        Parameters
        ----------
        ax : matplotlib Axes object
        expected_markers : list-like
            expected legend markers
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        Nz.Markers must be specified when visible is Truec                 S  s   g | ]}|  qS r0   )Z
get_marker).0handler0   r0   r1   
<listcomp>       z5TestPlotBase._check_legend_marker.<locals>.<listcomp>)r<   Zget_legend_handles_labelsr>   )r,   rC   Zexpected_markersrB   Zhandles_markersr0   r0   r1   _check_legend_marker   s    z!TestPlotBase._check_legend_markerc                   sP   |  }|  }dd  t|t|ks,J  fddt||D  t  dS )z
        Check each axes has identical lines

        Parameters
        ----------
        xp : matplotlib Axes object
        rs : matplotlib Axes object
        c                 S  s    |   }|  }t|| d S r3   )Z
get_xydatar%   assert_almost_equal)xplrslZxpdataZrsdatar0   r0   r1   
check_line   s    z,TestPlotBase._check_data.<locals>.check_linec                   s   g | ]\}} ||qS r0   r0   )rE   rM   rN   rO   r0   r1   rG      rH   z,TestPlotBase._check_data.<locals>.<listcomp>N)	get_lineslenzipr%   r4   )r,   ZxprsZxp_linesZrs_linesr0   rP   r1   _check_data   s    	zTestPlotBase._check_datac                 C  sB   ddl m} t||s$t|s$|g}|D ]}| |ks(J q(dS )a   
        Check each artist is visible or not

        Parameters
        ----------
        collections : matplotlib Artist or its list-like
            target Artist or its list or collection
        visible : bool
            expected visibility
        r   )
CollectionN)matplotlib.collectionsrV   
isinstancer   get_visible)r,   collectionsrB   rV   patchr0   r0   r1   _check_visible   s
    zTestPlotBase._check_visiblezAxes | Sequence[Axes]boolNone)r@   filledreturnc                 C  s2   |  |}|D ]}|jD ]}|j|ksJ qqdS )z
        Check for each artist whether it is filled or not

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        filled : bool
            expected filling
        N)r=   Zpatchesfill)r,   r@   r_   rC   r[   r0   r0   r1   _check_patches_all_filled   s    

z&TestPlotBase._check_patches_all_filledc                   s*   |  }tt||  fdd|jD S )Nc                   s   g | ]} | qS r0   r0   rE   vZmappedr0   r1   rG      rH   z3TestPlotBase._get_colors_mapped.<locals>.<listcomp>)uniquedictrS   values)r,   Zseriesr:   rf   r0   re   r1   _get_colors_mapped   s    zTestPlotBase._get_colors_mappedc                 C  s  ddl m}m}m} ddlm} | j}	|dur|durR| ||}|dt| }t|t|ksfJ t	||D ]d\}
}t
|
|r|
 }|	|}n(t
|
||frt|
 d }n|
 }|	|}||kspJ qp|dur|dur| ||}|dt| }t|t|ksJ t	||D ]Z\}
}t
|
|rH|
 d }n|
 }t
|tjrft|}|	|}||ks&J q&dS )a3  
        Check each artist has expected line colors and face colors

        Parameters
        ----------
        collections : list-like
            list or collection of target artist
        linecolors : list-like which has the same length as collections
            list of expected line colors
        facecolors : list-like which has the same length as collections
            list of expected face colors
        mapping : Series
            Series used for color grouping key
            used for andrew_curves, parallel_coordinates, radviz test
        r   )rV   LineCollectionPolyCollection)Line2DN)rW   rV   rj   rk   Zmatplotlib.linesrl   r;   ri   rR   rS   rX   Z	get_colorZto_rgbatupleZget_edgecolorZget_facecolorr&   Zndarray)r,   rZ   Z
linecolorsZ
facecolorsmappingrV   rj   rk   rl   convr[   colorresultexpectedr0   r0   r1   _check_colors   s<    




zTestPlotBase._check_colorsc                 C  s`   t |s| |ks\J nBdd |D }t|t|ks<J t||D ]\}}||ksFJ qFdS )a.  
        Check each text has expected labels

        Parameters
        ----------
        texts : matplotlib Text object, or its list-like
            target text, or its list
        expected : str or list-like which has the same length as texts
            expected text label, or its list
        c                 S  s   g | ]}|  qS r0   )get_text)rE   tr0   r0   r1   rG   .  rH   z3TestPlotBase._check_text_labels.<locals>.<listcomp>N)r   rt   rR   rS   )r,   Ztextsrr   rA   labeler0   r0   r1   r?      s    zTestPlotBase._check_text_labelsc           
      C  s  ddl m} | |}|D ]}|dus.|durt|j |rH| }n| |jdd }|D ]4}	|dur|t|		 | |dur`t|	
 | q`|dus|durt|j |r| }n| |jdd }|D ]4}	|durt|		 | |durt|	
 | qqdS )a  
        Check each axes has expected tick properties

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xlabelsize : number
            expected xticks font size
        xrot : number
            expected xticks rotation
        ylabelsize : number
            expected yticks font size
        yrot : number
            expected yticks rotation
        r   )NullFormatterNT)minor)Zmatplotlib.tickerrx   r=   rX   xaxisZget_minor_formatterZget_xticklabelsr%   rL   Zget_fontsizeZget_rotationyaxisZget_yticklabels)
r,   r@   Z
xlabelsizeZxrotZ
ylabelsizeZyrotrx   rC   rA   rv   r0   r0   r1   _check_ticks_props3  s*    


zTestPlotBase._check_ticks_propslinearc                 C  s<   |  |}|D ](}|j |ks$J |j |ksJ qdS )a  
        Check each axes has expected scales

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xaxis : {'linear', 'log'}
            expected xaxis scale
        yaxis : {'linear', 'log'}
            expected yaxis scale
        N)r=   rz   Z	get_scaler{   )r,   r@   rz   r{   rC   r0   r0   r1   _check_ax_scalesc  s    
zTestPlotBase._check_ax_scalesc           	      C  s   ddl m} |du r| j}| |}|durZt||ks<J |D ]}t| dks@J q@|dur|| ||}||ks|J t|d j	
 tj|tjd dS )a  
        Check expected number of axes is drawn in expected layout

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        axes_num : number
            expected number of axes. Unnecessary axes should be set to
            invisible.
        layout : tuple
            expected layout, (expected number of rows , columns)
        figsize : tuple
            expected figsize. default is matplotlib default
        r   flatten_axesN)r   )!pandas.plotting._matplotlib.toolsr   r$   r=   rR   Zget_children_get_axes_layoutr%   Zassert_numpy_array_equalfigureZget_size_inchesr&   arrayZfloat64)	r,   r@   Zaxes_numZlayoutZfigsizer   Zvisible_axesrC   rq   r0   r0   r1   _check_axes_shapet  s    
zTestPlotBase._check_axes_shapec                 C  sV   t  }t  }|D ]4}|  }||d d  ||d d  qt|t|fS )Nr      )setget_positionZ
get_pointsaddrR   )r,   r@   Zx_setZy_setrC   Zpointsr0   r0   r1   r     s    zTestPlotBase._get_axes_layoutc                 C  s&   ddl m} ||}dd |D }|S )z
        Flatten axes, and filter only visible

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like

        r   r   c                 S  s   g | ]}|  r|qS r0   )rY   )rE   rC   r0   r0   r1   rG     rH   z1TestPlotBase._flatten_visible.<locals>.<listcomp>)r   r   )r,   r@   r   r0   r0   r1   r=     s    	zTestPlotBase._flatten_visibler   c                 C  sx   |  |}|D ]d}|j}d}d}|D ]4}t|dd}	t|dd}
|	rL|d7 }|
r$|d7 }q$||ksfJ ||ksJ qdS )a  
        Check axes has expected number of errorbars

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xerr : number
            expected number of x errorbar
        yerr : number
            expected number of y errorbar
        r   has_xerrFhas_yerrr   N)r=   
containersgetattr)r,   r@   ZxerrZyerrrC   r   Z
xerr_countZ
yerr_countcr   r   r0   r0   r1   _check_has_errorbars  s    

z!TestPlotBase._check_has_errorbarsc                 C  s  ddl m} t|td}|du rj|du r,d}t||| s>J |dkrft|j|sVJ t|jtsfJ n|du r| |D ]}t||s|J q|dS t|tsJ t	|
 t	|ksJ | D ]\}}	t|	|| sJ |dkr|r|	 |ksJ q|dkrD|r|	j |ksJ t|	j|s0J t|	jts~J q|dkrz|	d d }
|
j}|r~| |ks~J qtqdS )	at  
        Check box returned type is correct

        Parameters
        ----------
        returned : object to be tested, returned from boxplot
        return_type : str
            return_type passed to boxplot
        expected_keys : list-like, optional
            group labels in subplot case. If not passed,
            the function checks assuming boxplot uses single ax
        check_ax_title : bool
            Whether to check the ax.title is the same as expected_key
            Intended to be checked by calling from ``boxplot``.
            Normal ``plot`` doesn't attach ``ax.title``, it must be disabled.
        r   r
   )rg   r@   bothNrg   r   r@   Zmedians)matplotlib.axesr   rg   rm   rX   rC   linesr=   r   sortedkeysitemsZ	get_titler@   AssertionError)r,   returnedreturn_typeZexpected_keysZcheck_ax_titler   typesrkeyvalueliner@   r0   r0   r1   _check_box_return_type  s>    

z#TestPlotBase._check_box_return_typec                   sf  dd l } fdd}d}|D ]B} jddt| | |d7 }|jddd |jf d	|i| | rnJ  jddt| | |d7 }|jdd
d |jf |dd| | rJ |dvr jddt| | |d7 }|jdd
d |jf d	|i| | sJ  jddt| | |d7 }|jddd |jf |d
d| | sJ qd S )Nr   c                    sz    j  j }  j  j } jrLtdd | D }tdd |D }n$tdd | D }tdd |D }|ov| S )Nc                 s  s   | ]}|j   V  qd S r3   ZgridlinerY   rE   gr0   r0   r1   	<genexpr>  rH   zHTestPlotBase._check_grid_settings.<locals>.is_grid_on.<locals>.<genexpr>c                 s  s   | ]}|j   V  qd S r3   r   r   r0   r0   r1   r     rH   c                 s  s   | ]}|j  V  qd S r3   ZgridOnr   r0   r0   r1   r     rH   c                 s  s   | ]}|j  V  qd S r3   r   r   r0   r0   r1   r     rH   )r9   Zgcarz   Zget_major_ticksr{   r#   all)ZxticksZyticksZxoffZyoffr,   r0   r1   
is_grid_on  s    z5TestPlotBase._check_grid_settings.<locals>.is_grid_onr   r   r@   F)gridkindT)r   r   )ZpieZhexbinZscatter)r"   r9   ZsubplotrR   rcZplot)r,   objkindskwsr.   r   Zspndxr   r0   r   r1   _check_grid_settings  s2    


z!TestPlotBase._check_grid_settingsrp   c                   s    fdd|d D S )zT
        Auxiliary function for correctly unpacking cycler after MPL >= 1.5
        c                   s   g | ]}|  qS r0   r0   rc   fieldr0   r1   rG   <  rH   z/TestPlotBase._unpack_cycler.<locals>.<listcomp>zaxes.prop_cycler0   )r,   ZrcParamsr   r0   r   r1   _unpack_cycler8  s    zTestPlotBase._unpack_cyclerc                 C  s   | j  r|jd S |jS )Nx)r   mpl_ge_3_5_0_shared_axesZ_shared_x_axesr,   rC   r0   r0   r1   
get_x_axis>  s    zTestPlotBase.get_x_axisc                 C  s   | j  r|jd S |jS )Ny)r   r   r   Z_shared_y_axesr   r0   r0   r1   
get_y_axisA  s    zTestPlotBase.get_y_axis)NT)NT)T)T)NNN)NNNN)r}   r}   )NNN)r   r   )NT)rp   )__name__
__module____qualname____doc__r2   r5   r   r9   r;   rD   rK   rU   r\   rb   ri   rs   r?   r|   r~   r   r   r=   r   r   r   r   r   r   r0   r0   r0   r1   r   $   s<   7




  
B 
0

$

 
<0
r   alwaysFc           
      K  s  ddl m} |rt}nt}d}t  t| zzt|d| }|	  || |fi |D ]}t
| q`t
jdd}|| W d   n1 s0    Y  W n( ty }	 z|	W Y d}	~	n
d}	~	0 0 W t
| nt
| 0 |W  d   S 1 s0    Y  dS )aT  
    Create plot and ensure that plot return object is valid.

    Parameters
    ----------
    f : func
        Plotting function.
    filterwarnings : str
        Warnings filter.
        See https://docs.python.org/3/library/warnings.html#warning-filter
    default_axes : bool, optional
        If False (default):
            - If `ax` not in `kwargs`, then create subplot(211) and plot there
            - Create new subplot(212) and plot there as well
            - Mind special corner case for bootstrap_plot (see `_gen_two_subplots`)
        If True:
            - Simply run plotting function with kwargs provided
            - All required axes instances will be created automatically
            - It is recommended to use it when the plotting function
            creates multiple axes itself. It helps avoid warnings like
            'UserWarning: To output multiple subplots,
            the figure containing the passed axes is being cleared'
    **kwargs
        Keyword arguments passed to the plotting function.

    Returns
    -------
    Plot object returned by the last plotting.
    r   Nr   T)Zreturn_filelike)r7   r8   _gen_default_plot_gen_two_subplotswarningscatch_warningssimplefiltergetZgcfZclfr%   Z"assert_is_valid_plot_return_objectZensure_cleanZsavefig	Exceptionr4   )
ffilterwarningsZdefault_axeskwargsr9   Z	gen_plotsretfigpatherrr0   r0   r1   _check_plot_worksE  s$    

,r   c                 k  s   | f i |V  dS )z'
    Create plot in a default way.
    Nr0   r   r   r   r0   r0   r1   r     s    r   c                 k  s^   d|vr| d | f i |V  | tjju r<d|vsJJ n| d|d< | f i |V  dS )z9
    Create plot on two subplots forcefully created.
    rC         N)Zadd_subplotpdZplottingZbootstrap_plotr   r0   r0   r1   r     s    
r   c                  C  s   t jt jt\} }| S r3   )osr   splitabspath__file__)pthrI   r0   r0   r1   curpath  s    r   )r   F)"r   
__future__r   r   typingr   r   r   Znumpyr&   Zpandas.util._decoratorsr   Zpandas.util._test_decoratorsutilZ_test_decoratorstdZpandas.core.dtypes.apir   Zpandasr   r   r   r	   Zpandas._testingZ_testingr%   r   r   Zskip_if_no_mplr   r   r   r   r   r0   r0   r0   r1   <module>   s.       $
: