如何在sns clustermap中标记集群 [英] How can I label the clusters in sns clustermap
问题描述
我正在使用以下代码创建一个簇图.
I am creating a clustermap with the following code.
import numpy as np
import pandas as pd
import seaborn as sns
all_net_names = ['early_vis', 'face', 'motion', 'scene', 'scene', 'scene',
'dmn', 'dmn', 'dmn', 'dmn', 'dmn', 'dmn', 'reward', 'reward',
'reward', 'reward', 'reward', 'ofc', 'ofc', 'ofc', 'ofc']
roi_names = ['E', 'F', 'M', 'S1', 'S2', 'S3', 'D1', 'D2', 'D3', 'D4', 'D5',
'D6', 'R1', 'R2', 'R3', 'R4', 'R5','O1', 'O2', 'O3', 'O4']
n_roi = len(roi_names)
M = np.random.rand(n_roi, n_roi) # array to plot
net_ind = sorted(np.unique(all_net_names, return_index=True)[1])
net_names = [all_net_names[index] for index in sorted(net_ind)]
network_pal = sns.husl_palette(len(net_names), s=.45)
network_lut = dict(zip(map(str, np.unique(all_net_names)), network_pal))
network_colors = pd.Series(all_net_names).map(network_lut)
network_colors = np.asarray(network_colors)
g = sns.clustermap(M, center=0, cmap="vlag",
row_cluster=False,
col_cluster=False,
row_colors=network_colors,
col_colors=network_colors,
linewidths=0, figsize=(10, 10))
g.ax_heatmap.set_xticklabels(roi_names, rotation=90)
g.ax_heatmap.set_yticklabels(roi_names, rotation=0)
它可以正常工作并提供以下输出:
It works and gives this output:
我可以添加与每个单元格相对应的标签,但是我还想用唯一的网络名称来标记每个群集,如下所示:
I could add labels corresponding to each cell but I also want to label each cluster with the unique network names as in here:
有什么想法可以实现这一目标吗?
Any ideas how to achieve that?
推荐答案
也许在代码末尾添加它?
Maybe adding this at the end of the code?
g.ax_row_colors.set_yticks(0.5 * (np.array(net_ind) + np.array(net_ind[1:] + [len(all_net_names)])))
g.ax_row_colors.set_yticklabels(net_names)
g.ax_row_colors.yaxis.set_tick_params(size=0) # make tick marks invisible
每个组的开始由 net_ind
给出.为了使标签很好地居中,应将标签放置在其下一个标签的起始位置和起始位置的中间.由于最后一组没有下一个标签,因此我们将 all_net_names
的长度作为最后一组的结尾.
The start of each group is given by net_ind
. To put the labels nicely centered, they should be placed just in the middle of their start position and the start position of the next label. As the last group doesn't have a next label, we take the length of all_net_names
as the end of the last group.
对列也可以这样做:
g.ax_col_colors.set_xticks(0.5 * (np.array(net_ind) + np.array(net_ind[1:] + [len(all_net_names)])))
g.ax_col_colors.set_xticklabels(net_names, rotation=90)
g.ax_col_colors.xaxis.set_tick_params(size=0) # make tick marks invisible
g.ax_col_colors.xaxis.tick_top()
这篇关于如何在sns clustermap中标记集群的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!