当前位置: 首页>>代码示例>>Python>>正文


Python seaborn.clustermap方法代码示例

本文整理汇总了Python中seaborn.clustermap方法的典型用法代码示例。如果您正苦于以下问题:Python seaborn.clustermap方法的具体用法?Python seaborn.clustermap怎么用?Python seaborn.clustermap使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在seaborn的用法示例。


在下文中一共展示了seaborn.clustermap方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _normalize_table

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def _normalize_table(table, method):
    '''
    Normalize column data in a dataframe for plotting in clustermap.

    table: pd.DataFrame
        Input data.
    method: str
        Normalization method to use.

    Returns normalized table as pd.DataFrame
    '''
    if 'col' in method:
        axis = 0
    elif 'row' in method:
        axis = 1
    if 'z_score' in method:
        res = table.apply(lambda x: (x - x.mean()) / x.std(), axis=axis)
    elif 'rel' in method:
        res = table.apply(lambda x: x / x.sum(), axis=axis)
    elif method == 'log10':
        res = table.apply(lambda x: np.log10(x + 1))
    return res.fillna(0) 
开发者ID:biocore,项目名称:mmvec,代码行数:24,代码来源:heatmap.py

示例2: clustermap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def clustermap(gene_values, out_pdf, color=None, table=False):
  """ Generate a clustered heatmap using seaborn. """

  if table:
    np.save(out_pdf[:-4], gene_values)

  plt.figure()
  g = sns.clustermap(
      gene_values,
      metric='euclidean',
      cmap=color,
      xticklabels=False,
      yticklabels=False)
  g.ax_heatmap.set_xlabel('Experiments')
  g.ax_heatmap.set_ylabel('Genes')
  plt.savefig(out_pdf)
  plt.close() 
开发者ID:calico,项目名称:basenji,代码行数:19,代码来源:basenji_test_genes.py

示例3: main

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def main():
    args = parser.parse_args()
    data = pd.read_table(args.tsv, index_col=args.row if args.row else 0, sep=args.delimiter, encoding='utf-8')
    if args.cols:
        try:
            data = data.loc[:,args.cols.split(',')]
        except KeyError:
            data = data.iloc[:,[int(i)-1 for i in args.cols.split(',')]]
    if len(data.columns) > 50:
        raise BaseException('Too many columns')
    data = np.log2(data) if args.log_normalize else data
    data[data==-1*np.inf] = data[data!=-1*np.inf].min().min()
    width = 5+0 if len(data.columns)<50 else (len(data.columns)-50)/100
    row_cutoff = 1000
    height = 15+0 if len(data)<row_cutoff else (len(data)-row_cutoff)/75.0
    seaborn_map = sns.clustermap(data, figsize=(width, height))
    seaborn_map.savefig('{}_heatmap.png'.format(os.path.split(args.tsv.name)[1]))
    seaborn_map.data2d.to_csv('{}_heatmap.tsv'.format(os.path.split(args.tsv.name)[1]), sep='\t') 
开发者ID:Chris7,项目名称:django-djangui,代码行数:20,代码来源:heatmap.py

示例4: plot_heatmap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def plot_heatmap(outpath, df, sample_linkage, sample_colors, event_linkage, desc, sample_color_lut):

    assert desc.lower().startswith('altsplice') or desc.lower().startswith('expression')
    is_altsplice = desc.lower().startswith('altsplice')

    sys.setrecursionlimit(100000)
    print "Plotting data ... "
    graph = sns.clustermap(df.T,
                       col_colors=sample_colors,
                       col_linkage=sample_linkage, row_linkage=event_linkage,
                       cmap = sns.cubehelix_palette(as_cmap=True))
    graph.ax_heatmap.axis('off')
    graph.ax_col_dendrogram.set_title("%s Clustering" %' '.join(desc.split('_')).title())
    graph.ax_heatmap.set_xlabel("Events")
    graph.ax_heatmap.set_ylabel("Samples")
    if is_altsplice: graph.cax.set_title("psi")
    else: graph.cax.set_title("log(counts)")
    add_legend(graph, sample_color_lut)
    plot_utils.save(outpath)
    return 
开发者ID:ratschlab,项目名称:pancanatlas_code_public,代码行数:22,代码来源:plot_heatmaps.py

示例5: plot_corr_matrix

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def plot_corr_matrix(self, save_path=None, show_chart=True, cmap='vlag', linewidth=0, figsize=(10, 10)):
        """
        Plots the correlation matrix
        :param save_path: local directory to save file. If provided, saves a png of the image to the address.
        :param show_chart: If True, shows the chart.
        :param cmap: matplotlib colormap.
        :param linewidth: witdth of the grid lines of the correlation matrix.
        :param figsize: tuple with figsize dimensions.
        """

        sns.clustermap(self.corr, method=self.method, metric=self.metric, cmap=cmap,
                       figsize=figsize, linewidths=linewidth,
                       col_linkage=self.link, row_linkage=self.link)

        plt.tight_layout()

        if not (save_path is None):
            plt.savefig(save_path,
                        pad_inches=1,
                        dpi=400)

        if show_chart:
            plt.show()

        plt.close() 
开发者ID:Finance-Hub,项目名称:FinanceHub,代码行数:27,代码来源:construction.py

示例6: __call__

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def __call__(self, data, path):

        colorbar, factors, unique, xkcd = self.getColorBar(data)
        n_samples = data.shape[0]
        data = data.iloc[:, :n_samples]
        col_dict = dict(list(zip(unique, xkcd)))

        print(data.head())
        seaborn.set(font_scale=.5)
        ax = seaborn.clustermap(data,
                                row_colors=colorbar, col_colors=colorbar)
        plt.setp(ax.ax_heatmap.yaxis.set_visible(False))

        for label in unique:
            ax.ax_col_dendrogram.bar(
                0, 0, color=seaborn.xkcd_rgb[col_dict[label]],
                label=label, linewidth=0)
        ax.ax_col_dendrogram.legend(loc="center", ncol=len(unique))

        return ResultBlocks(ResultBlock(
            '''#$mpl %i$#\n''' % ax.cax.figure.number,
            title='ClusterMapPlot')) 
开发者ID:CGATOxford,项目名称:CGATPipelines,代码行数:24,代码来源:RnaseqqcReport.py

示例7: _parse_heatmap_metadata_annotations

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def _parse_heatmap_metadata_annotations(metadata_column, margin_palette):
    '''
    Transform feature or sample metadata into color vector for annotating
    margin of clustermap.
    Parameters
    ----------
    metadata_column: pd.Series of metadata for annotating plots
    margin_palette: str
        Name of color palette to use for annotating metadata
        along margin(s) of clustermap.
    Returns
    -------
    Returns vector of colors for annotating clustermap and dict mapping colors
    to classes.
    '''
    # Create a categorical palette to identify md col
    metadata_column = metadata_column.astype(str)
    col_names = sorted(metadata_column.unique())

    # Select Color palette
    if margin_palette == 'colorhelix':
        col_palette = sns.cubehelix_palette(
            len(col_names), start=2, rot=3, dark=0.3, light=0.8, reverse=True)
    else:
        col_palette = sns.color_palette(margin_palette, len(col_names))
    class_colors = dict(zip(col_names, col_palette))

    # Convert the palette to vectors that will be drawn on the matrix margin
    col_colors = metadata_column.map(class_colors)

    return col_colors, class_colors 
开发者ID:biocore,项目名称:mmvec,代码行数:33,代码来源:heatmap.py

示例8: _parse_taxonomy_strings

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def _parse_taxonomy_strings(taxonomy_series, level):
    '''
    taxonomy_series: pd.Series of semicolon-delimited taxonomy strings
    level: int
        taxonomic level for annotating clustermap.
     Returns
     -------
    Returns a pd.Series of taxonomy names at specified level,
        or terminal annotation
    '''
    return taxonomy_series.apply(lambda x: x.split(';')[:level][-1].strip()) 
开发者ID:biocore,项目名称:mmvec,代码行数:13,代码来源:heatmap.py

示例9: plot_clustermap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def plot_clustermap(D, xticklabels=None, yticklabels=None):
    import seaborn as sns
    if xticklabels is None: xticklabels = range(D.shape[0])
    if yticklabels is None: yticklabels = range(D.shape[1])
    zmat = sns.clustermap(
        D, yticklabels=yticklabels, xticklabels=xticklabels,
        linewidths=0.2, cmap='BuGn')
    plt.setp(zmat.ax_heatmap.get_yticklabels(), rotation=0)
    plt.setp(zmat.ax_heatmap.get_xticklabels(), rotation=90)
    return zmat 
开发者ID:probcomp,项目名称:cgpm,代码行数:12,代码来源:plots.py

示例10: plot_target_corr

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def plot_target_corr(filter_outs, seq_targets, filter_names, target_names, out_pdf, seq_op='mean'):
  num_seqs = filter_outs.shape[0]
  num_targets = len(target_names)

  if seq_op == 'mean':
    filter_outs_seq = filter_outs.mean(axis=2)
  else:
    filter_outs_seq = filter_outs.max(axis=2)

  # std is sequence by filter.
  filter_seqs_std = filter_outs_seq.std(axis=0)
  filter_outs_seq = filter_outs_seq[:, filter_seqs_std > 0]
  filter_names_live = filter_names[filter_seqs_std > 0]

  filter_target_cors = np.zeros((len(filter_names_live), num_targets))
  for fi in range(len(filter_names_live)):
    for ti in range(num_targets):
      cor, p = spearmanr(filter_outs_seq[:, fi], seq_targets[:num_seqs, ti])
      filter_target_cors[fi, ti] = cor

  cor_df = pd.DataFrame(
      filter_target_cors, index=filter_names_live, columns=target_names)

  sns.set(font_scale=0.3)
  plt.figure()
  sns.clustermap(cor_df, cmap='BrBG', center=0, figsize=(8, 10))
  plt.savefig(out_pdf)
  plt.close()


################################################################################
# plot_filter_seq_heat
#
# Plot a clustered heatmap of filter activations in
#
# Input
#  param_matrix: np.array of the filter's parameter matrix
#  out_pdf:
################################################################################ 
开发者ID:calico,项目名称:basenji,代码行数:41,代码来源:basenji_motifs.py

示例11: cluster_heatmap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def cluster_heatmap(data, clusters, target, plot_name=None, **kwargs):
    """
    Visualizes feature usage with heatmap.

    Parameters
    --------
    data: pd.DataFrame
        Feature matrix.
    clusters: np.array
        Array of cluster IDs.
    target: np.array
        Boolean vector, if ``True``, then user has `positive_target_event` in trajectory.
    plot_name: str, optional
        Name of plot to save. Default: ``'clusters_heatmap_{timestamp}.svg'``

    Returns
    -------
    Saves plot to ``retention_config.experiments_folder``

    Return type
    -------
    PNG
    """
    heatmap = sns.clustermap(data.values,
                             cmap="BrBG",
                             xticklabels=data.columns,
                             yticklabels=False,
                             row_cluster=True,
                             col_cluster=False)

    heatmap.ax_row_dendrogram.set_visible(False)
    heatmap = heatmap.ax_heatmap

    plot_name = plot_name or 'cluster_heatmap_{}'.format(datetime.now()).replace(':', '_').replace('.', '_') + '.svg'
    plot_name = data.retention.retention_config['experiments_folder'] + '/' + plot_name
    return heatmap, plot_name, None, data.retention.retention_config 
开发者ID:retentioneering,项目名称:retentioneering-tools,代码行数:38,代码来源:plot.py

示例12: expression_clustermap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def expression_clustermap(counts, freq=0.8):

    scols,ncols = base.get_column_names(counts)
    X = counts.set_index('name')[ncols]
    X = np.log(X)
    v = X.std(1).sort_values(ascending=False)
    X = X[X.isnull().sum(1)/len(X.columns)<0.2]
    X = X.fillna(0)
    cg = sns.clustermap(X,cmap='YlGnBu',figsize=(12,12),lw=0,linecolor='gray')
    mt = plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0, fontsize=9)
    mt = plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
    return cg 
开发者ID:dmnfarrell,项目名称:smallrnaseq,代码行数:14,代码来源:plotting.py

示例13: cluster_map

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def cluster_map(data, names):
    """Cluster map of genes"""

    import seaborn as sns
    import pylab as plt
    data = data.ix[names]
    X = np.log(data).fillna(0)
    X = X.apply(lambda x: x-x.mean(), 1)
    cg = sns.clustermap(X,cmap='RdYlBu_r',figsize=(8,10),lw=.5,linecolor='gray')
    mt=plt.setp(cg.ax_heatmap.yaxis.get_majorticklabels(), rotation=0)
    mt=plt.setp(cg.ax_heatmap.xaxis.get_majorticklabels(), rotation=90)
    return cg 
开发者ID:dmnfarrell,项目名称:smallrnaseq,代码行数:14,代码来源:de.py

示例14: plot_heatmap

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def plot_heatmap(psi_df, meta_df, outpath):
    # Sort by cancer type
    psi_df = psi_df.copy().loc[meta_df['cnc'].sort_values().index]
    psi_df = psi_df.iloc[:, psi_df.columns.map(lambda x: _decode_event_name(x)[1]).argsort()]
    col_colors, col_cmap_lut = _get_heatmap_col_colors(psi_df)
    row_colors, row_cmap_lut = _get_heatmap_row_colors(meta_df, psi_df.index)
    method = 'ward'; metric = 'cosine'
    graph = sns.clustermap(psi_df, cmap='Purples',
                           row_colors=row_colors, col_colors=col_colors,
                           row_cluster=False, col_cluster=False,
                           xticklabels=psi_df.columns.map(lambda x:_decode_event_name(x)[2]),
                           linewidths=0,
                           mask=psi_df.isnull())
    _override_sns_row_colors(graph, row_colors.values)
    graph.ax_heatmap.set_yticks([])
    graph.ax_heatmap.set_xlabel("Events")
    graph.ax_heatmap.set_ylabel("Samples")
    graph.cax.set_title("psi")
    tumor_only_row_cmap_lut = {key:val for key,val in row_cmap_lut.items() if not 'Normal' in key}
    plotter.add_legend(graph, tumor_only_row_cmap_lut)
    plotter.add_col_legend(graph, col_cmap_lut)
    print "Writing: %s" %outpath
    plt.savefig(outpath, bbox_inches='tight')
    pdf_outpath = re.sub('.png$', '.pdf', outpath)
    print "Writing: %s" %pdf_outpath
    #plt.savefig(pdf_outpath, bbox_inches='tight')
    plt.close()
    return 
开发者ID:ratschlab,项目名称:pancanatlas_code_public,代码行数:30,代码来源:sf_heatmap.py

示例15: __init__

# 需要导入模块: import seaborn [as 别名]
# 或者: from seaborn import clustermap [as 别名]
def __init__(self, path, games, logger, suffix):
        super(WordCoocurence, self).__init__(path, self.__class__.__name__, suffix)

        questions = []
        word_counter = collections.Counter()

        NO_WORDS_TO_DISPLAY = 50

        for game in games:
            # split questions into words
            for q in game.questions:
                questions.append(q)
                q = re.sub('[?]', '', q)
                words = re.findall(r'\w+', q)

                for w in words:
                    word_counter[w.lower()] += 1


        # compute word co-coocurrence
        common_words = word_counter.most_common(NO_WORDS_TO_DISPLAY)
        common_words = [pair[0] for pair in common_words]
        corrmat = np.zeros((NO_WORDS_TO_DISPLAY, NO_WORDS_TO_DISPLAY))

        # compute the correlation matrices
        for i, question in enumerate(questions):
            for word in question:
                if word in common_words:
                    for other_word in question:
                        if other_word in common_words:
                            if word != other_word:
                                corrmat[common_words.index(word)][common_words.index(other_word)] += 1.

        # Display the cor matrix
        df = pd.DataFrame(data=corrmat, index=common_words, columns=common_words)
        f = sns.clustermap(df, standard_scale=0, col_cluster=False, row_cluster=True, cbar_kws={"label": "co-occurence"})
        f.ax_heatmap.xaxis.tick_top()

        plt.setp(f.ax_heatmap.get_xticklabels(), rotation=90)
        plt.setp(f.ax_heatmap.get_yticklabels(), rotation=0) 
开发者ID:GuessWhatGame,项目名称:guesswhat,代码行数:42,代码来源:word_coocurrence.py


注:本文中的seaborn.clustermap方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。