def correlation_matrix(adata, groupby, show_correlation_numbers=False, dendrogram=True, figsize=None,
                       show=None, save=None, **kwds):
    """Plots the correlation matrix computed as part of `sc.tl.dendrogram`.

    Parameters
    ----------
    adata : :class:`~anndata.AnnData`
    groupby : `str`
        Categorical data column used to create the dendrogram
    show_correlation_numbers : `bool`, optional(default: `False`)
        If `show_correlation` is True, plot the correlation number on top of each cell.
    dendrogram: `bool` or `str`, optional (default: `False`)
        If True or a valid dendrogram key, a dendrogram based on the hierarchical clustering
        between the `groupby` categories is added. The dendrogram information is computed
        using :ref:`scanpy.tl.dendrogram`. If `tl.dendrogram` has not been called previously
        the function is called with default parameters.
    figsize : (`float`, `float`), optional (default: `None`)
        By default a figure size that aims to produce a squared correlation matrix plot is used.
        Format is (width, height)
    {show_save_ax}
    **kwds : keyword arguments
        Only if `show_correlation` is True: Are passed to `matplotlib.pyplot.pcolormesh` when plotting
        the correlation heatmap. Useful values to pas are `vmax`, `vmin` and `cmap`.

    Returns
    -------

    Examples
    --------
    >>> adata = sc.datasets.pbmc68k_reduced()
    >>> sc.tl.dendrogram(adata, 'bulk_labels')
    >>> sc.pl.correlation(adata, 'bulk_labels')
    """

    dendrogram_key = _get_dendrogram_key(adata, dendrogram, groupby)

    index = adata.uns[dendrogram_key]['categories_idx_ordered']
    corr_matrix = adata.uns[dendrogram_key]['correlation_matrix']
    # reorder matrix columns according to the dendrogram
    if dendrogram:
        assert(len(index)) == corr_matrix.shape[0]
        corr_matrix = corr_matrix[index, :]
        corr_matrix = corr_matrix[:, index]
        labels = list(adata.obs[groupby].cat.categories)
        labels = np.array(labels).astype('str')[index]
    else:
        labels = adata.obs[groupby].cat.categories
    num_rows = corr_matrix.shape[0]
    colorbar_height = 0.2
    if dendrogram:
        dendrogram_width = 1.8
    else:
        dendrogram_width = 0
    if figsize is None:
        corr_matrix_height = num_rows * 0.6
        height = corr_matrix_height + colorbar_height
        width = corr_matrix_height + dendrogram_width
    else:
        width, height = figsize
        corr_matrix_height = height - colorbar_height

    fig = pl.figure(figsize=(width, height))
    # layout with 2 rows and 2  columns:
    # row 1: dendrogram + correlation matrix
    # row 2: nothing + colormap bar (horizontal)
    gs = gridspec.GridSpec(nrows=2, ncols=2, width_ratios=[dendrogram_width, corr_matrix_height],
                           height_ratios=[corr_matrix_height, colorbar_height], wspace=0.01, hspace=0.05)

    axs = []
    corr_matrix_ax = fig.add_subplot(gs[1])
    if dendrogram:
        dendro_ax = fig.add_subplot(gs[0], sharey=corr_matrix_ax)
        _plot_dendrogram(dendro_ax, adata, groupby, dendrogram_key=dendrogram_key,
                         remove_labels=True, orientation='left',
                         ticks=np.arange(corr_matrix .shape[0]) + 0.5)
        axs.append(dendro_ax)
    # define some default pcolormesh parameters
    if 'edge_color' not in kwds:
        if corr_matrix.shape[0] > 30:
            # when there are too many rows it is better to remove
            # the black lines surrounding the boxes in the heatmap
            kwds['edgecolors'] = 'none'
        else:
            kwds['edgecolors'] = 'black'
            kwds['linewidth'] = 0.01
    if 'vmax' not in kwds and 'vmin' not in kwds:
        kwds['vmax'] = 1
        kwds['vmin'] = -1
    if 'cmap' not in kwds:
        # by default use a divergent color map
        kwds['cmap'] = 'bwr'

    img_mat = corr_matrix_ax.pcolormesh(corr_matrix, **kwds)
    corr_matrix_ax.set_xlim(0, num_rows)
    corr_matrix_ax.set_ylim(0, num_rows)

    corr_matrix_ax.yaxis.tick_right()
    corr_matrix_ax.set_yticks(np.arange(corr_matrix .shape[0]) + 0.5)
    corr_matrix_ax.set_yticklabels(labels)

    corr_matrix_ax.xaxis.set_tick_params(labeltop=True)
    corr_matrix_ax.xaxis.set_tick_params(labelbottom=False)
    corr_matrix_ax.set_xticks(np.arange(corr_matrix .shape[0]) + 0.5)
    corr_matrix_ax.set_xticklabels(labels, rotation=45, ha='left')

    corr_matrix_ax.tick_params(
        axis='x',
        which='both',
        bottom=False,
        top=False)

    corr_matrix_ax.tick_params(
        axis='y',
        which='both',
        left=False,
        right=False)
    print(corr_matrix_ax.get_ylim())

    if show_correlation_numbers:
        for row in range(num_rows):
            for col in range(num_rows):
                corr_matrix_ax.text(row + 0.5, col + 0.5,
                              "{:.2f}".format(corr_matrix[row, col]),
                              ha='center', va='center')

    axs.append(corr_matrix_ax)

    # Plot colorbar
    colormap_ax = fig.add_subplot(gs[3])
    cobar = pl.colorbar(img_mat, cax=colormap_ax, orientation='horizontal')
    cobar.solids.set_edgecolor("face")
    axs.append(colormap_ax)

    return axs
def correlation_matrix ( adata , groupby , show_correlation_numbers = False , dendrogram = True , figsize = None , show = None , save = None , ** kwds ) : dendrogram_key = _get_dendrogram_key ( adata , dendrogram , groupby ) index = adata . uns [ dendrogram_key ] [ 'categories_idx_ordered' ] corr_matrix = adata . uns [ dendrogram_key ] [ 'correlation_matrix' ] if dendrogram : assert ( len ( index ) ) == corr_matrix . shape [ 0 ] corr_matrix = corr_matrix [ index , : ] corr_matrix = corr_matrix [ : , index ] labels = list ( adata . obs [ groupby ] . cat . categories ) labels = np . array ( labels ) . astype ( 'str' ) [ index ] else : labels = adata . obs [ groupby ] . cat . categories num_rows = corr_matrix . shape [ 0 ] colorbar_height = 0.2 if dendrogram : dendrogram_width = 1.8 else : dendrogram_width = 0 if figsize is None : corr_matrix_height = num_rows * 0.6 height = corr_matrix_height + colorbar_height width = corr_matrix_height + dendrogram_width else : width , height = figsize corr_matrix_height = height - colorbar_height fig = pl . figure ( figsize = ( width , height ) ) gs = gridspec . GridSpec ( nrows = 2 , ncols = 2 , width_ratios = [ dendrogram_width , corr_matrix_height ] , height_ratios = [ corr_matrix_height , colorbar_height ] , wspace = 0.01 , hspace = 0.05 ) axs = [ ] corr_matrix_ax = fig . add_subplot ( gs [ 1 ] ) if dendrogram : dendro_ax = fig . add_subplot ( gs [ 0 ] , sharey = corr_matrix_ax ) _plot_dendrogram ( dendro_ax , adata , groupby , dendrogram_key = dendrogram_key , remove_labels = True , orientation = 'left' , ticks = np . arange ( corr_matrix . shape [ 0 ] ) + 0.5 ) axs . append ( dendro_ax ) if 'edge_color' not in kwds : if corr_matrix . shape [ 0 ] > 30 : kwds [ 'edgecolors' ] = 'none' else : kwds [ 'edgecolors' ] = 'black' kwds [ 'linewidth' ] = 0.01 if 'vmax' not in kwds and 'vmin' not in kwds : kwds [ 'vmax' ] = 1 kwds [ 'vmin' ] = - 1 if 'cmap' not in kwds : kwds [ 'cmap' ] = 'bwr' img_mat = corr_matrix_ax . pcolormesh ( corr_matrix , ** kwds ) corr_matrix_ax . set_xlim ( 0 , num_rows ) corr_matrix_ax . set_ylim ( 0 , num_rows ) corr_matrix_ax . yaxis . tick_right ( ) corr_matrix_ax . set_yticks ( np . arange ( corr_matrix . shape [ 0 ] ) + 0.5 ) corr_matrix_ax . set_yticklabels ( labels ) corr_matrix_ax . xaxis . set_tick_params ( labeltop = True ) corr_matrix_ax . xaxis . set_tick_params ( labelbottom = False ) corr_matrix_ax . set_xticks ( np . arange ( corr_matrix . shape [ 0 ] ) + 0.5 ) corr_matrix_ax . set_xticklabels ( labels , rotation = 45 , ha = 'left' ) corr_matrix_ax . tick_params ( axis = 'x' , which = 'both' , bottom = False , top = False ) corr_matrix_ax . tick_params ( axis = 'y' , which = 'both' , left = False , right = False ) print ( corr_matrix_ax . get_ylim ( ) ) if show_correlation_numbers : for row in range ( num_rows ) : for col in range ( num_rows ) : corr_matrix_ax . text ( row + 0.5 , col + 0.5 , "{:.2f}" . format ( corr_matrix [ row , col ] ) , ha = 'center' , va = 'center' ) axs . append ( corr_matrix_ax ) colormap_ax = fig . add_subplot ( gs [ 3 ] ) cobar = pl . colorbar ( img_mat , cax = colormap_ax , orientation = 'horizontal' ) cobar . solids . set_edgecolor ( "face" ) axs . append ( colormap_ax ) return axs
Plots the correlation matrix computed as part of `sc.tl.dendrogram`.

    Parameters
    ----------
    adata : :class:`~anndata.AnnData`
    groupby : `str`
        Categorical data column used to create the dendrogram
    show_correlation_numbers : `bool`, optional(default: `False`)
        If `show_correlation` is True, plot the correlation number on top of each cell.
    dendrogram: `bool` or `str`, optional (default: `False`)
        If True or a valid dendrogram key, a dendrogram based on the hierarchical clustering
        between the `groupby` categories is added. The dendrogram information is computed
        using :ref:`scanpy.tl.dendrogram`. If `tl.dendrogram` has not been called previously
        the function is called with default parameters.
    figsize : (`float`, `float`), optional (default: `None`)
        By default a figure size that aims to produce a squared correlation matrix plot is used.
        Format is (width, height)
    {show_save_ax}
    **kwds : keyword arguments
        Only if `show_correlation` is True: Are passed to `matplotlib.pyplot.pcolormesh` when plotting
        the correlation heatmap. Useful values to pas are `vmax`, `vmin` and `cmap`.

    Returns
    -------

    Examples
    --------
    >>> adata = sc.datasets.pbmc68k_reduced()
    >>> sc.tl.dendrogram(adata, 'bulk_labels')
    >>> sc.pl.correlation(adata, 'bulk_labels')