a
    Sic߸                     @   s  d 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
ZddlZzddlmZ dZW n eyr   dZY n0 dd	lmZ dd
lmZ ddlmZ ddlmZmZmZmZmZ ddgZdd Zdd Z dd Z!dd Z"G dd dZ#dddddddddddddddddddddZ$G dd dZ%dddd d!dddd"d#d$Z&G d%d& d&eZ'dd!d ddd'ddddddddd(d)d*dd+d,dZ(dS )-z(Functions to visualize matrices of data.    N)LineCollection)gridspec)	hierarchyFT   )cm)Grid)get_colormap)despineaxis_ticklabels_overlaprelative_luminanceto_utf8_draw_figureheatmap
clustermapc                 C   s(   t | tjrdtt| jS | jS dS )z6Convert a pandas index or multiindex to an axis label.-N)
isinstancepd
MultiIndexjoinmapr   namesnameindex r   J/var/www/html/django/DPS/env/lib/python3.9/site-packages/seaborn/matrix.py_index_to_label   s    r   c                 C   s&   t | tjrdd | jD S | jS dS )z5Convert a pandas index or multiindex into ticklabels.c                 S   s   g | ]}d  tt|qS )r   )r   r   r   .0ir   r   r   
<listcomp>*       z(_index_to_ticklabels.<locals>.<listcomp>N)r   r   r   valuesr   r   r   r   _index_to_ticklabels'   s    r#   c                    sN   t jj z | d  tt | W S  tyH    fdd| D  Y S 0 dS )zAConvert either a list of colors or nested lists of colors to RGB.r   c                    s   g | ]}t t |qS r   )listr   )r   lto_rgbr   r   r    9   r!   z#_convert_colors.<locals>.<listcomp>N)mplcolorsr'   r$   r   
ValueError)r)   r   r&   r   _convert_colors/   s    r+   c                 C   s   |du rt | jt}t|t jrN|j| jkr6tdtj|| j	| j
td}n4t|tjr|j	| j	s|j
| j
rd}t||t| B }|S )zEnsure that data and mask are compatible and add missing values.

    Values will be plotted for cells where ``mask`` is ``False``.

    ``data`` is expected to be a DataFrame; ``mask`` can be an array or
    a DataFrame.

    Nz&Mask must have the same shape as data.)r   columnsdtypez2Mask must have the same index and columns as data.)npzerosshapeboolr   ndarrayr*   r   	DataFramer   r,   equalsisnull)datamaskerrr   r   r   _matrix_mask<   s$    	r9   c                   @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )_HeatMapperz?Draw a heatmap plot of a matrix with nice labels and colormaps.TNc                 C   sh  t |tjr|j}nt|}t|}t||}tjt||}d}t |t	rd|}t
|j}n |du rxt
|j}n|du rg }d}t |t	r|}t
|j}n |du rt
|j}n|du rg }t|sg | _g | _n:t |tr|dkrd| _t
|j| _n| ||\| _| _t|s*g | _g | _n>t |trT|dkrTd| _t
|j| _n| ||\| _| _t|j}t|j}|dur|nd| _|dur|nd| _| |||||| |du s|du rd}d}n:t |tr|}n$t|}|j|jkrd}t|d}|| _|| _|| _|| _|| _|	du r<i n|	  | _!|
| _"|du rZi n|  | _#dS )zInitialize the plotting object.r   TFautoN (`data` and `annot` must have same shape.)$r   r   r3   r"   r.   asarrayr9   mamasked_whereintr#   r,   r   lenxticksxticklabelsstr_skip_ticksyticksyticklabelsr   xlabelylabel_determine_cmap_paramsr1   r0   r*   r6   	plot_dataannot
annot_datafmtcopy	annot_kwscbarcbar_kws)selfr6   vminvmaxcmapcenterrobustrM   rO   rQ   rR   rS   rD   rH   r7   rL   Z
xtickeveryZ
ytickeveryrI   rJ   rN   r8   r   r   r   __init__d   s    









z_HeatMapper.__init__c                 C   s  | ttj}|du r6|r,t|d}n
t|}|du rZ|rPt|d}n
t|}|| | _| _	|du r|du rt
j| _qt
j| _n6t|trt|| _n t|trtj|| _n|| _|dur| tjtjgd }| tj }	| tj}
|	| dk}|
| | jjd k}t|| || }tj|| || }|||g\}}t||d}tj| || _| j| |r| j|	 |r| j|
 dS )z@Use some heuristics to set good defaults for colorbar and range.N   b   r   r      )astypefloatfilledr.   nannanpercentilenanminnanmaxrU   rV   r   rocketrW   Zicefirer   rE   r   r$   r(   r)   ListedColormapr?   masked_invalidinfNmax	Normalizelinspaceset_bad	set_underset_over)rT   rL   rU   rV   rW   rX   rY   Z	calc_databadunderoverZ	under_setZover_setvrangeZnormlizecmincmaxccr   r   r   rK      sF    






z"_HeatMapper._determine_cmap_paramsc                 C   s   |   | jj\}}tt|d t|d \}}t|j|j| |	 | jjD ]v\}}}	}
}|	tj
jurXt|
}|dkrdnd}d| j d |}t|ddd}|| j |j|||fi | qXd	S )
z/Add textual labels with the value in each cell.      ?g&1?z.15wz{:}rX   )colorhavaN)update_scalarmappablerN   r0   r.   meshgridarangezipflat	get_arrayget_facecolorsr?   maskedr   rO   formatdictupdaterQ   text)rT   axmeshheightwidthxposyposxymrz   vallumZ
text_color
annotationZtext_kwargsr   r   r   _annotate_heatmap   s    $
z_HeatMapper._annotate_heatmapc                 C   sr   t |}|dkrg g  }}nN|dkr:t|d | }}n0d||  }}}t|||d }|||| }||fS )z3Return ticks and labels at evenly spaced intervals.r   r   rw   )rB   r.   r   )rT   labelsZ	tickeverynticksstartendstepr   r   r   rF   	  s    z_HeatMapper._skip_ticksc                 C   s   |j j }| |}|j|jg| }|j|jg| }|	dg\}|j
 }t||d  }	|	dk rrg g fS t||	 d }
|
dkrdn|
}
| ||
\}}||fS )z5Determine ticks and ticklabels that minimize overlap.r   H   r   )figuredpi_scale_transinvertedget_window_extenttransformedr   r   xaxisyaxis	set_tickslabel1get_sizerA   rB   rF   )rT   r   r   axis	transformbboxsizetickfontsizeZ	max_ticksZ
tick_everyr   r   r   r   _auto_ticks  s    
z_HeatMapper._auto_ticksc                 C   s  t |ddd d|vr2|d| j |d| j |j| jfd| ji|}|jd| jj	d fd| jj	d fd	 |
  | jr|jj|||fi | j}|jd |d
dr|jd t| jtr| jdkr| || jd\}}n| j| j }}t| jtr(| jdkr(| || jd\}}	n| j| j }}	|j||d ||}
|j|	dd}tj|dd t|j t |
rtj|
dd t |rtj|dd |j| j!| j"d | j#r| $|| dS )z&Draw the heatmap on the provided Axes.T)r   leftbottomnormrU   rV   rW   r   r   )xlimylim
rasterizedFr;   )rC   rG   verticalrotationrX   )r|   
horizontal)rI   rJ   N)%r	   
setdefaultrU   rV   
pcolormeshrL   rW   setr6   r0   invert_yaxisrR   r   colorbarrS   outlineset_linewidthgetsolidsset_rasterizedr   rC   rE   r   rD   rG   rH   set_xticklabelsset_yticklabelspltsetpr   r
   rI   rJ   rM   r   )rT   r   caxkwsr   cbrC   rD   rG   rH   xtlytlr   r   r   plot&  s<    &



z_HeatMapper.plot)TTN)
__name__
__module____qualname____doc__rZ   rK   r   rF   r   r   r   r   r   r   r:   a   s    
\9r:   z.2gwhiter;   )rU   rV   rW   rX   rY   rM   rO   rQ   
linewidths	linecolorrR   rS   cbar_axsquarerD   rH   r7   r   c                K   sb   t | |||||||||||||}|	|d< |
|d< |du rBt }|rP|d |||| |S )a  Plot rectangular data as a color-encoded matrix.

    This is an Axes-level function and will draw the heatmap into the
    currently-active Axes if none is provided to the ``ax`` argument.  Part of
    this Axes space will be taken and used to plot a colormap, unless ``cbar``
    is False or a separate Axes is provided to ``cbar_ax``.

    Parameters
    ----------
    data : rectangular dataset
        2D dataset that can be coerced into an ndarray. If a Pandas DataFrame
        is provided, the index/column information will be used to label the
        columns and rows.
    vmin, vmax : floats, optional
        Values to anchor the colormap, otherwise they are inferred from the
        data and other keyword arguments.
    cmap : matplotlib colormap name or object, or list of colors, optional
        The mapping from data values to color space. If not provided, the
        default will depend on whether ``center`` is set.
    center : float, optional
        The value at which to center the colormap when plotting divergent data.
        Using this parameter will change the default ``cmap`` if none is
        specified.
    robust : bool, optional
        If True and ``vmin`` or ``vmax`` are absent, the colormap range is
        computed with robust quantiles instead of the extreme values.
    annot : bool or rectangular dataset, optional
        If True, write the data value in each cell. If an array-like with the
        same shape as ``data``, then use this to annotate the heatmap instead
        of the data. Note that DataFrames will match on position, not index.
    fmt : str, optional
        String formatting code to use when adding annotations.
    annot_kws : dict of key, value mappings, optional
        Keyword arguments for :meth:`matplotlib.axes.Axes.text` when ``annot``
        is True.
    linewidths : float, optional
        Width of the lines that will divide each cell.
    linecolor : color, optional
        Color of the lines that will divide each cell.
    cbar : bool, optional
        Whether to draw a colorbar.
    cbar_kws : dict of key, value mappings, optional
        Keyword arguments for :meth:`matplotlib.figure.Figure.colorbar`.
    cbar_ax : matplotlib Axes, optional
        Axes in which to draw the colorbar, otherwise take space from the
        main Axes.
    square : bool, optional
        If True, set the Axes aspect to "equal" so each cell will be
        square-shaped.
    xticklabels, yticklabels : "auto", bool, list-like, or int, optional
        If True, plot the column names of the dataframe. If False, don't plot
        the column names. If list-like, plot these alternate labels as the
        xticklabels. If an integer, use the column names but plot only every
        n label. If "auto", try to densely plot non-overlapping labels.
    mask : bool array or DataFrame, optional
        If passed, data will not be shown in cells where ``mask`` is True.
        Cells with missing values are automatically masked.
    ax : matplotlib Axes, optional
        Axes in which to draw the plot, otherwise use the currently-active
        Axes.
    kwargs : other keyword arguments
        All other keyword arguments are passed to
        :meth:`matplotlib.axes.Axes.pcolormesh`.

    Returns
    -------
    ax : matplotlib Axes
        Axes object with the heatmap.

    See Also
    --------
    clustermap : Plot a matrix using hierarchical clustering to arrange the
                 rows and columns.

    Examples
    --------

    .. include:: ../docstrings/heatmap.rst

    r   	edgecolorNequal)r:   r   gca
set_aspectr   )r6   rU   rV   rW   rX   rY   rM   rO   rQ   r   r   rR   rS   r   r   rD   rH   r7   r   kwargsplotterr   r   r   r   c  s    [
c                   @   sP   e Zd ZdZdd Zdd Zdd Zedd	 Zd
d Z	edd Z
dd ZdS )_DendrogramPlotterzAObject for drawing tree of similarities between data rows/columnsc           
         s~  || _ | j dkr|j}t|tjr*|j}nt|}t|}|| _|| _	| j	j
| _
|| _|| _|| _ || _|| _|du r| j| _n|| _|  | _dt| j	j
d  d }	| jr:t| j	j  fdd| jD  | jrg | _|	| _g | _ | _t| j	j| _d| _n,|	| _g | _ | _g | _d| _t| j	j| _n(g g  | _| _g g  | _| _d	\| _| _| jd
 | _| jd | _dS )zPlot a dendrogram of the relationships between the columns of data

        Parameters
        ----------
        data : pandas.DataFrame
            Rectangular data
        r   N
   r      c                    s   g | ]} | qS r   r   r   
ticklabelsr   r   r      r!   z/_DendrogramPlotter.__init__.<locals>.<listcomp>r<   )r<   r<   ZdcoordZicoord) r   Tr   r   r3   r"   r.   r>   arrayr6   r0   metricmethodlabelrotatecalculated_linkagelinkagecalculate_dendrogram
dendrogramr   r#   r   reordered_indrC   rG   rD   rH   r   rJ   rI   dependent_coordindependent_coord)
rT   r6   r   r   r   r   r   r   r   r   r   r   r   rZ     sR    





z_DendrogramPlotter.__init__c                 C   s   t j| j| j| jd}|S )Nr   r   )r   r   r   r   r   )rT   r   r   r   r   _calculate_linkage_scipy  s    z+_DendrogramPlotter._calculate_linkage_scipyc                 C   sb   dd l }d}| jdko| j|v }|s.| jdkrD|j| j| j| jdS |j| j| j| jd}|S d S )Nr   )centroidmedianZward	euclideansingler   )fastclusterr   r   Zlinkage_vectorr   r   )rT   r   Zeuclidean_methodsr   r   r   r   r   _calculate_linkage_fastcluster  s    z1_DendrogramPlotter._calculate_linkage_fastclusterc                 C   sD   z
|   W S  ty:   t| jdkr6d}t| Y n0 |  S )Ni'  zYClustering large matrix with scipy. Installing `fastcluster` may give better performance.)r   ImportErrorr.   productr0   warningswarnr   )rT   msgr   r   r   r   '  s    
z%_DendrogramPlotter.calculated_linkagec                 C   s   t j| jdtj dS )a  Calculates a dendrogram based on the linkage matrix

        Made a separate function, not a property because don't want to
        recalculate the dendrogram every time it is accessed.

        Returns
        -------
        dendrogram : dict
            Dendrogram dictionary as returned by scipy.cluster.hierarchy
            .dendrogram. The important key-value pairing is
            "reordered_ind" which indicates the re-ordering of the matrix
        T)Zno_plotZcolor_threshold)r   r   r   r.   rh   rT   r   r   r   r   4  s    
z'_DendrogramPlotter.calculate_dendrogramc                 C   s
   | j d S )z2Indices of the matrix, reordered by the dendrogramleaves)r   r   r   r   r   r   D  s    z _DendrogramPlotter.reordered_indc           	      C   s  |du ri n|  }|dd |d|dd | jrT| jdkrTt| j| j}nt| j| j}tdd	 |D fi |}|	| t
| j}ttt| j}| jr|jd
 |d|d  |d|d  |  |  n |d|d  |d|d  t|ddd |j| j| j| j| jd || j}|j| jdd}t|j t
|dkrxt |rxt!j"|dd t
|dkrt |rt!j"|dd | S )zPlots a dendrogram of the similarities between data on the axes

        Parameters
        ----------
        ax : matplotlib.axes.Axes
            Axes object upon which the dendrogram is plotted

        Nr   rw   r)   rz   )皙?r   r   r   c                 S   s   g | ]\}}t t||qS r   )r$   r   )r   r   r   r   r   r   r    Z  r!   z+_DendrogramPlotter.plot.<locals>.<listcomp>rightr   g?Tr   r   r   )rC   rG   rI   rJ   r   r   r   )#rP   r   popr   r   r   r   r   r   add_collectionrB   r   rj   r   r   set_ticks_positionset_ylimset_xliminvert_xaxisr   r	   r   rC   rG   rI   rJ   r   rD   r   rH   r   r   r
   r   r   )	rT   r   tree_kwscoordslinesZnumber_of_leavesZmax_dependent_coordr   r   r   r   r   r   I  s@    	



z_DendrogramPlotter.plotN)r   r   r   r   rZ   r   r   propertyr   r   r   r   r   r   r   r   r     s   ?

r   r   average)r   r   r   r   r   r   r  r   c          
   	   C   s@   t rtdt| ||||||d}	|du r2t }|	j||dS )a  Draw a tree diagram of relationships within a matrix

    Parameters
    ----------
    data : pandas.DataFrame
        Rectangular data
    linkage : numpy.array, optional
        Linkage matrix
    axis : int, optional
        Which axis to use to calculate linkage. 0 is rows, 1 is columns.
    label : bool, optional
        If True, label the dendrogram at leaves with column or row names
    metric : str, optional
        Distance metric. Anything valid for scipy.spatial.distance.pdist
    method : str, optional
        Linkage method to use. Anything valid for
        scipy.cluster.hierarchy.linkage
    rotate : bool, optional
        When plotting the matrix, whether to rotate it 90 degrees
        counter-clockwise, so the leaves face right
    tree_kws : dict, optional
        Keyword arguments for the ``matplotlib.collections.LineCollection``
        that is used for plotting the lines of the dendrogram tree.
    ax : matplotlib axis, optional
        Axis to plot on, otherwise uses current axis

    Returns
    -------
    dendrogramplotter : _DendrogramPlotter
        A Dendrogram plotter object.

    Notes
    -----
    Access the reordered dendrogram indices with
    dendrogramplotter.reordered_ind

    z)dendrogram requires scipy to be installed)r   r   r   r   r   r   N)r   r  )	_no_scipyRuntimeErrorr   r   r   r   )
r6   r   r   r   r   r   r   r  r   r   r   r   r   r     s    *r   c                
   @   sz   e Zd ZdddZdd ZdddZedd	d
ZedddZdd Z	edddZ
dd Zdd Zdd Zdd ZdS )ClusterGridNc                 C   s  t rtdt|tjr || _nt|| _| | j|||| _t| j|| _	t
j|d| _| j||dd\| _| _| j||dd\| _| _z|	\}}W n ty   |	 }}Y n0 z|
\}}W n ty   |
 }}Y n0 | | j||}| | j||}| jdu rdnd}| jdu r dnd}tj||||d	| _| j| jd
 | _| j| jd | _| j  | j  d| _d| _| jdur| j| jd | _| jdur| j| jd | _| j| jd | _|du rd | _| _n| j| jd | _| j| _|| _ d| _!d| _"dS )z=Grid object for organizing clustered heatmap input on to axesz*ClusterGrid requires scipy to be available)figsizer   r   r   Nr[      )width_ratiosheight_ratios)r   )r   r  )r  r   )r   r  )r  r  )r   r   )#r
  r  r   r   r3   r6   format_datadata2dr9   r7   r   r   _figure_preprocess_colors
row_colorsrow_color_labels
col_colorscol_color_labels	TypeError
dim_ratiosr   GridSpecgsadd_subplotax_row_dendrogramax_col_dendrogramset_axis_offax_row_colorsax_col_colors
ax_heatmapax_cbarr   cbar_posdendrogram_rowdendrogram_col)rT   r6   	pivot_kwsz_scorestandard_scaler  r  r  r7   dendrogram_ratiocolors_ratior'  Zrow_dendrogram_ratioZcol_dendrogram_ratioZrow_colors_ratioZcol_colors_ratior  r  nrowsncolsr   r   r   rZ     st    




zClusterGrid.__init__c                 C   s   d}|durt |tjtjfrt|ds0|dksBt|dsf|dkrf|rJdnd}| d| d	}t||dkr|||j}n||j}|	t
d
}t |tjrt|j}|jj}n |jdu rdg}n|jg}|j}t|}||fS )zAPreprocess {row/col}_colors to extract labels and convert colors.Nr   r   r,   r   colrowz<_colors indices can't be matched with data indices. Provide z?_colors as a non-indexed datatype, e.g. by using `.to_numpy()``r   r<   )r   r   r3   Serieshasattrr  reindexr   r,   r^   objectfillnar$   r   r"   r   r+   )rT   r6   r)   r   r   	axis_namer   r   r   r   r    s4    


zClusterGrid._preprocess_colorsc                 C   sb   |dur|j f i |}n|}|dur6|dur6td|durJ| ||}|dur^| ||}|S )z,Extract variables from data or use directly.Nz:Cannot perform both z-scoring and standard-scaling on data)pivotr*   r+  r,  )rT   r6   r*  r+  r,  r  r   r   r   r  0  s    zClusterGrid.format_datar   c                 C   s>   |dkr| }n| j }||  |  }|dkr4|S |j S dS )a  Standarize the mean and variance of the data axis

        Parameters
        ----------
        data2d : pandas.DataFrame
            Data to normalize
        axis : int
            Which axis to normalize across. If 0, normalize across rows, if 1,
            normalize across columns.

        Returns
        -------
        normalized : pandas.DataFrame
            Noramlized data with a mean of 0 and variance of 1 across the
            specified axis.
        r   N)r   meanstd)r  r   Zz_scoredr   r   r   r+  D  s    zClusterGrid.z_scorec                 C   sJ   |dkr| }n| j }| }|| | |   }|dkr@|S |j S dS )a  Divide the data by the difference between the max and min

        Parameters
        ----------
        data2d : pandas.DataFrame
            Data to normalize
        axis : int
            Which axis to normalize across. If 0, normalize across rows, if 1,
            normalize across columns.

        Returns
        -------
        standardized : pandas.DataFrame
            Noramlized data with a mean of 0 and variance of 1 across the
            specified axis.

        r   N)r   minrj   )r  r   Zstandardizedsubtractr   r   r   r,  b  s    zClusterGrid.standard_scalec                 C   sN   |g}|dur8t |dkr&t|}nd}||| g7 }|dt|  |S )z8Get the proportions of the figure taken up by each axes.Nr[   r   )r.   ndimrB   appendsum)rT   r)   r-  r.  ratiosn_colorsr   r   r   r    s    
zClusterGrid.dim_ratiosr   c                    s  zt j| d  W nN tyb   t| t| d  } t fdd| dd D s^tdY n0 dt|  } | g} i }t| ft}t	| D ]6\}}t	|D ]$\}}	|
|	t|}
|
|||f< qq|dd|f }|dkr|j}t jt|}||fS )a  Turns a list of colors into a numpy matrix and matplotlib colormap

        These arguments can now be plotted using heatmap(matrix, cmap)
        and the provided colors will be plotted.

        Parameters
        ----------
        colors : list of matplotlib colors
            Colors to label the rows or columns of a dataframe.
        ind : list of ints
            Ordering of the rows or columns, to reorder the original colors
            by the clustered dendrogram order
        axis : int
            Which axis this is labeling

        Returns
        -------
        matrix : numpy.array
            A numpy array of integer values, where each indexes into the cmap
        cmap : matplotlib.colors.ListedColormap

        r   c                 3   s   | ]}t | kV  qd S )N)rB   )r   cr   r   r   	<genexpr>  r!   z<ClusterGrid.color_list_to_matrix_and_cmap.<locals>.<genexpr>r   Nz/Multiple side color vectors must have same size)r(   r)   r'   r*   rB   allr.   r/   rA   	enumerater   r   rf   r$   )r)   indr   r   unique_colorsmatrixr   innerjrz   idxrW   r   rD  r   color_list_to_matrix_and_cmap  s&    z)ClusterGrid.color_list_to_matrix_and_cmapc                 C   s   |r&t | j||dd| jd||d	| _n| jg  | jg  |rbt | j||dd| j||d| _n| jg  | jg  t| jddd t| jddd d S )NFr   T)r   r   r   r   r   r   r   r  r   )r   r   r   r   r   r   r  r   )	r   r  r   r(  
set_xticks
set_yticksr!  r)  r	   )rT   row_clustercol_clusterr   r   row_linkagecol_linkager  r   r   r   plot_dendrograms  s$    


zClusterGrid.plot_dendrogramsc                 K   s  |  }|dd |dd |dd |dd |dd |dd |dd |d	d |d
d | jdur| j| j|dd\}}| jdur| j}nd}t|f|d| j|dd| |durtj| j	 dd nt
| jddd | jdurz| j| j|dd\}}| jdur,| j}nd}t|f|d| jd|d| |dur| jj  tj| j dd nt
| jddd dS )zPlots color labels between the dendrogram and the heatmap

        Parameters
        ----------
        heatmap_kws : dict
            Keyword arguments heatmap

        rW   Nr   rX   rM   rU   rV   rY   rD   rH   r   r  F)rW   rR   r   rD   rH   Z   r   T)r   r   r   )rP   r   r  rN  r  r   r#  r   r   get_xticklabelsr	   r  r  r$  r   
tick_rightget_yticklabels)rT   xindyindr   rJ  rW   r  r  r   r   r   plot_colors  sR    




zClusterGrid.plot_colorsc              
   K   s  | j j||f | _ | jj||f | _|dd}zt|| }W n ttfyX   Y n0 |dd}zt|| }W n ttfy   Y n0 |dd }|d u s|du rnNt|t	r| j }n8t|}|j
| j j
krd}	t|	|| d d |f }|}|d| jd u t| j f| j| j|| j|||d| | j }|sJd n
|d	  }
| jjd
 | jjd
 |
d ur| j }tj||
d tddd}| jd u r| jjf i | n4| j  | jjf i | | j  | j| j d S )NrD   r;   rH   rM   Fr=   rR   )r   r   rS   r7   rD   rH   rM   r   r   r   {Gz?)h_padw_pad)r  ilocr7   r   r.   r>   r  
IndexErrorr   r1   r0   r*   r   r&  r   r%  rY  get_rotationr   r  set_label_positionr   r   r   r  tight_layoutr"  set_axis_onset_positionr'  )rT   colorbar_kwsrZ  r[  r   r   r   rM   rN   r8   Zytl_rotZtight_paramsr   r   r   plot_matrix$  sX    






zClusterGrid.plot_matrixc	              	   K   s   |	 ddr$d}
t|
 |	d |d u r0i n|}| j|||||||d z| jj}W n$ ty|   t	| j
jd }Y n0 z| jj}W n$ ty   t	| j
jd }Y n0 | j||fi |	 | j|||fi |	 | S )Nr   Fz%``square=True`` ignored in clustermap)rS  rT  r  r   r   )r   r   r   r   rU  r)  r   AttributeErrorr.   r   r  r0   r(  r\  rh  )rT   r   r   rg  rQ  rR  rS  rT  r  r   r   rZ  r[  r   r   r   r   ]  s(    

zClusterGrid.plot)
NNNNNNNNNN)NN)r   )r   )r   )r   r   r   rZ   r  r  staticmethodr+  r,  r  rN  rU  r\  rh  r   r   r   r   r   r    s&      
L*  
!3A9r  )r   r   r   gQ?)r]  g?g?g
ףp=
?)r*  r   r   r+  r,  r  rS   rQ  rR  rS  rT  r  r  r7   r-  r.  r'  r  c                K   sL   t rtdt| ||||||||||d}|jf |||||	|
||d|S )a0  
    Plot a matrix dataset as a hierarchically-clustered heatmap.

    This function requires scipy to be available.

    Parameters
    ----------
    data : 2D array-like
        Rectangular data for clustering. Cannot contain NAs.
    pivot_kws : dict, optional
        If `data` is a tidy dataframe, can provide keyword arguments for
        pivot to create a rectangular dataframe.
    method : str, optional
        Linkage method to use for calculating clusters. See
        :func:`scipy.cluster.hierarchy.linkage` documentation for more
        information.
    metric : str, optional
        Distance metric to use for the data. See
        :func:`scipy.spatial.distance.pdist` documentation for more options.
        To use different metrics (or methods) for rows and columns, you may
        construct each linkage matrix yourself and provide them as
        `{row,col}_linkage`.
    z_score : int or None, optional
        Either 0 (rows) or 1 (columns). Whether or not to calculate z-scores
        for the rows or the columns. Z scores are: z = (x - mean)/std, so
        values in each row (column) will get the mean of the row (column)
        subtracted, then divided by the standard deviation of the row (column).
        This ensures that each row (column) has mean of 0 and variance of 1.
    standard_scale : int or None, optional
        Either 0 (rows) or 1 (columns). Whether or not to standardize that
        dimension, meaning for each row or column, subtract the minimum and
        divide each by its maximum.
    figsize : tuple of (width, height), optional
        Overall size of the figure.
    cbar_kws : dict, optional
        Keyword arguments to pass to `cbar_kws` in :func:`heatmap`, e.g. to
        add a label to the colorbar.
    {row,col}_cluster : bool, optional
        If ``True``, cluster the {rows, columns}.
    {row,col}_linkage : :class:`numpy.ndarray`, optional
        Precomputed linkage matrix for the rows or columns. See
        :func:`scipy.cluster.hierarchy.linkage` for specific formats.
    {row,col}_colors : list-like or pandas DataFrame/Series, optional
        List of colors to label for either the rows or columns. Useful to evaluate
        whether samples within a group are clustered together. Can use nested lists or
        DataFrame for multiple color levels of labeling. If given as a
        :class:`pandas.DataFrame` or :class:`pandas.Series`, labels for the colors are
        extracted from the DataFrames column names or from the name of the Series.
        DataFrame/Series colors are also matched to the data by their index, ensuring
        colors are drawn in the correct order.
    mask : bool array or DataFrame, optional
        If passed, data will not be shown in cells where `mask` is True.
        Cells with missing values are automatically masked. Only used for
        visualizing, not for calculating.
    {dendrogram,colors}_ratio : float, or pair of floats, optional
        Proportion of the figure size devoted to the two marginal elements. If
        a pair is given, they correspond to (row, col) ratios.
    cbar_pos : tuple of (left, bottom, width, height), optional
        Position of the colorbar axes in the figure. Setting to ``None`` will
        disable the colorbar.
    tree_kws : dict, optional
        Parameters for the :class:`matplotlib.collections.LineCollection`
        that is used to plot the lines of the dendrogram tree.
    kwargs : other keyword arguments
        All other keyword arguments are passed to :func:`heatmap`.

    Returns
    -------
    :class:`ClusterGrid`
        A :class:`ClusterGrid` instance.

    See Also
    --------
    heatmap : Plot rectangular data as a color-encoded matrix.

    Notes
    -----
    The returned object has a ``savefig`` method that should be used if you
    want to save the figure object without clipping the dendrograms.

    To access the reordered row indices, use:
    ``clustergrid.dendrogram_row.reordered_ind``

    Column indices, use:
    ``clustergrid.dendrogram_col.reordered_ind``

    Examples
    --------

    .. include:: ../docstrings/clustermap.rst

    z)clustermap requires scipy to be available)
r*  r  r  r  r+  r,  r7   r-  r.  r'  )r   r   rg  rQ  rR  rS  rT  r  )r
  r  r  r   )r6   r*  r   r   r+  r,  r  rS   rQ  rR  rS  rT  r  r  r7   r-  r.  r'  r  r   r   r   r   r   r   z  s     g
))r   r   
matplotlibr(   matplotlib.collectionsr   matplotlib.pyplotpyplotr   r   numpyr.   pandasr   Zscipy.clusterr   r
  r   r<   r   axisgridr   _compatr   utilsr	   r
   r   r   r   __all__r   r#   r+   r9   r:   r   r   r   r  r   r   r   r   r   <module>   s`   
	%  
l 66   G