Example #1
0
def plot_clustering_heatmap(clust_object, folder, figsize=(15.5, 9.5)):
    """Hierarchical clustering heatmap"""
    plt.figure(41, figsize=figsize)
    # colInds = plotHColCluster(ds[s].cyDf, method='complete', metric='pearson-signed', col_labels=ds[s].labels, col_dmat=ds[s].dmatDf)
    colInds = plotHColCluster(clust_object.cyDf,
                              method='complete',
                              metric='pearson-signed',
                              col_labels=clust_object.labels,
                              figsize=figsize,
                              save_path=os.path.join(
                                  folder, '%s_hierchical_clust_heatmap.png' %
                                  clust_object.name))
   #         filename = "".join([FIG_PATH, p,  "_bar_median_responses_clusters_", str(i[0]), "_",str(i[1]), ".png"])
#         f.savefig(filename, dpi=200)


# plot correlation matrix of HA and NA clustering on Shanghai
# for p in ['SHA_ha', 'SHA_na']:

#     col_ind = np.argsort(clusters[p])
#     f = plt.figure()
#     ax_matrix = f.add_axes([0.3,0.1,0.6,0.6])
#     my_norm = mpl.colors.Normalize(vmin=0.4, vmax=1)
#     im = ax_matrix.matshow(dMat[p][colInd,:][:,colInd].T,aspect='auto', origin='upper', cmap=cm.RdBu_r,norm=my_norm)
#     ax_matrix.set_xticks([])

#     c_inds = []
#     c_inds = [len(np.where(clusters[p]==i)[0]) for i in np.arange(1,num_clusters+1)]
#     ax_matrix.set_yticks(np.cumsum(c_inds)[:-1])
#     ax_matrix.set_xticks(np.cumsum(c_inds)[:-1])
#     # Plot colorbar.
#     ax_color = f.add_axes([0.91,0.1,0.02,0.6])
#     plt.colorbar(im, cax=ax_color)


# plot correlation matrix with dendrogram overlayed:
for p, s in zip(['SHA_ha', 'SHA_na'], ['H7', 'N9']):
    colInd = hcp.plotHColCluster(arr_df[post_inds][ind_dict[p]].T,method='complete', metric='spearman',titleStr=s,vRange=(0, 1))
    #, \col_labels=arr_df[post_inds].group)
    f = gcf()
    filename = "".join([FIG_PATH + p + "postBoost_clustering_matrix_and_dendrogram"])
    f.savefig(filename, dpi=200)
#         filename = "".join([FIG_PATH, p,  "_bar_median_responses_clusters_", str(i[0]), "_",str(i[1]), ".png"])
#         f.savefig(filename, dpi=200)


# plot correlation matrix of HA and NA clustering on Shanghai
# for p in ['SHA_ha', 'SHA_na']:

#     col_ind = np.argsort(clusters[p])
#     f = plt.figure()
#     ax_matrix = f.add_axes([0.3,0.1,0.6,0.6])
#     my_norm = mpl.colors.Normalize(vmin=0.4, vmax=1)
#     im = ax_matrix.matshow(dMat[p][colInd,:][:,colInd].T,aspect='auto', origin='upper', cmap=cm.RdBu_r,norm=my_norm)
#     ax_matrix.set_xticks([])

#     c_inds = []
#     c_inds = [len(np.where(clusters[p]==i)[0]) for i in np.arange(1,num_clusters+1)]
#     ax_matrix.set_yticks(np.cumsum(c_inds)[:-1])
#     ax_matrix.set_xticks(np.cumsum(c_inds)[:-1])
#     # Plot colorbar.
#     ax_color = f.add_axes([0.91,0.1,0.02,0.6])
#     plt.colorbar(im, cax=ax_color)


# plot correlation matrix with dendrogram overlayed:
for p in ["SHA_ha", "SHA_na"]:
    colInd = hcp.plotHColCluster(arr_df[ind_dict[p]].T, method="complete", metric="spearman", titleStr=p, vRange=(0, 1))
    # , \col_labels=arr_df[post_inds].group)
    f = plt.gcf()
    filename = "".join([FIG_PATH + p + "postBoost_clustering_matrix_and_dendrogram"])
    f.savefig(filename, dpi=200)
# Output clustering results
if do_recalculate:
    for cyto_object in cyto_modules.values():
        cyplot.plotMeanCorr(
            cyto_object.withMean,
            cyto_object.meanS.name,
            cyList=sorted(cyto_object.cyDf.columns),
            figsize=(10, 6),
            save_path=os.path.join(
                args.paths['correlation_figures'],
                '%s_cy_mean_correlation.png' % cyto_object.name))

        plotHColCluster(cyto_object.cyDf,
                        method='complete',
                        metric='pearson-signed',
                        figsize=(10, 6),
                        save_path=os.path.join(
                            args.paths['correlation_figures'],
                            '%s_correlation_heatmap.png' % cyto_object.name))

        cytomod.io.write_modules(cyto_object, args.paths['clustering_info'])
        cytomod.io.plot_modules(cyto_object,
                                args.paths['clustering_figures'],
                                heatmap_figsize=(10, 6))

########### ------------ Associations ------------- ###########

# standardize numeric covariates
if args.covariates != []:
    standardizeFunc = lambda col: (col - np.nanmean(col)) / np.nanstd(col)
Example #5
0
def plot_modules(clust_object, folder):
    '''Plot cytomod object modules information'''
    """Hierarchical clustering heatmap"""
    plt.figure(41, figsize=(15.5, 9.5))
    # colInds = plotHColCluster(ds[s].cyDf, method='complete', metric='pearson-signed', col_labels=ds[s].labels, col_dmat=ds[s].dmatDf)
    colInds = plotHColCluster(clust_object.cyDf,
                              method='complete',
                              metric='pearson-signed',
                              col_labels=clust_object.labels,
                              save_path=os.path.join(
                                  folder, '%s_hierchical_clust_heatmap.png' %
                                  clust_object.name))
    # plt.figure(41).savefig(os.path.join(folder, '%s_hierchical_clust_heatmap.png' % clust_object.name))
    """Heatmaps of pairwise reliability"""
    plt.figure(43, figsize=(15.5, 9.5))
    colInds = cyplot.plotHierClust(1 - clust_object.pwrel,
                                   clust_object.Z,
                                   labels=clust_object.labels,
                                   titleStr='Pairwise reliability (%s)' %
                                   clust_object.name.replace('_', ' '),
                                   vRange=(0, 1))
    plt.figure(43).savefig(os.path.join(folder,
                                        '%s_pwrel.png' % clust_object.name),
                           dpi=300)
    """color_label_legend"""
    plt.figure(48, figsize=(3, 3))
    plt.clf()
    axh = plt.subplot(1, 1, 1)
    colorLegend(palettable.colorbrewer.qualitative.Set3_6.mpl_colors,
                ['%s' % s for s in clust_object.modDf.columns],
                loc=10)
    axh.spines['right'].set_color('none')
    axh.spines['left'].set_color('none')
    axh.spines['top'].set_color('none')
    axh.spines['bottom'].set_color('none')
    axh.set_xticks([])
    axh.set_yticks([])
    axh.set_facecolor('white')

    plt.figure(48).savefig(os.path.join(folder, 'color_label_legend.png'),
                           dpi=300)
    """Plot intra-module correlation"""
    plt.figure(50, figsize=(15, 9))
    for lab in list(
            cy.labels2modules(clust_object.labels,
                              clust_object.dropped).keys()):
        cyplot.plotModuleCorr(clust_object.cyDf,
                              clust_object.labels,
                              lab,
                              dropped=clust_object.dropped)
        plt.figure(50).savefig(os.path.join(
            folder, '%s_mod_corr_%s.png' % (clust_object.name, lab)),
                               dpi=300)
    """Cytokine embedding"""
    plt.figure(901, figsize=(13, 9.7))
    cyplot.plotModuleEmbedding(clust_object.dmatDf,
                               clust_object.labels,
                               method='kpca')
    colors = palettable.colorbrewer.get_map(
        'Set1', 'qualitative', len(np.unique(clust_object.labels))).mpl_colors
    colorLegend(colors, [
        '%s%1.0f' % (clust_object.sampleStr, i)
        for i in np.unique(clust_object.labels)
    ],
                loc='lower left')
    plt.figure(901).savefig(os.path.join(folder,
                                         '%sembed.png' % clust_object.name),
                            dpi=300)