gpt4 book ai didi

python - 从 seaborn clustermap 结果中重新排序高级集群

转载 作者:行者123 更新时间:2023-12-05 07:23:03 24 4
gpt4 key购买 nike

有没有办法从ab在下图中用脚本?我正在使用 seaborn.clustermap()a (即保留行的顺序。但是,列顺序仅在第二高级别发生变化)。

我想知道是否可以使用 seaborn.matrix.ClusterGrid seaborn.clustermap() 返回的, 对其进行修改并绘制修改后的结果。 enter image description here bP.S. 我问这个的原因是顺序有一个含义(先是蓝色,然后是绿色,最后是红色)。

更新:下面是一个小数据集生成的情况:

df = pd.DataFrame([[1, 1.1, 0.9, 1.9, 2, 2.1, 2.8, 3, 3.1], 
[1.8, 2, 2.1, 0.7, 1, 1.1, 2.7, 3, 3.3]],
columns = ['d1', 'd2', 'd3',
'l3', 'l2', 'l1',
'b1', 'b2', 'b3'],
index = ['p1', 'p2'])

cg = sns.clustermap(df); ## returns a ClusterGrid

输出是这样的:

enter image description here

我们可以考虑以 b 开头的列作为早餐,l作为午餐和d作为晚餐。现在,订单是 breakfast -> dinner -> lunch .我想去 breakfast -> lunch -> dinner .

最佳答案

这就是我解决问题的方法。它可以工作,但可能不如人们希望的那么优雅!

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram

# set the desired order of groups eg: breakfast, lunch, dinner
groups = ['b', 'l', 'd']

# reorder indexes/indices besed on the desired order
new_order = []
for group in groups:
indexes = cg.data2d.columns.str.startswith(group)
indexes_locs = np.where(indexes)[0].tolist()
new_order += indexes_locs

## reorder df based on the new order
ordered_df = cg.data2d.iloc[:, new_order]

## Run clustermap on the reordered dataframe by disabling
## the clustering for both rows and columns
ocg = sns.clustermap(ordered_df,
row_cluster=False,
col_cluster=False,
);

## draw dendrogram x-axis
axx = ocg.ax_col_dendrogram.axes
axx.clear()

with plt.rc_context({'lines.linewidth': 0.5}):

link = cg.dendrogram_col.linkage ## extract the linkage information

## manualy inspect the linkage and determine the new desired order
link[[4, 2]] = link[[2, 4]] ## swaping the two groups of higher hierarchy

## draw the the dendrogram on the x-axis
dendrogram(link,
color_threshold=0,
ax=axx,
truncate_mode='lastp',
orientation='top',
link_color_func=lambda x: 'k'
);

axx.set_yticklabels(['']*len(axx.get_yticklabels()))
axx.tick_params(color='w')

## draw dendrogram y-axis (no chage here)
axy = ocg.ax_row_dendrogram.axes
axy.clear()

with plt.rc_context({'lines.linewidth': 0.5}):

## draw the the dendrogram on the y-axis
dendrogram(cg.dendrogram_row.linkage,
color_threshold=0,
ax=axy,
truncate_mode='lastp',
orientation='left',
link_color_func=lambda x: 'k',
);

axy.set_xticklabels(['']*len(axy.get_yticklabels()))
axy.tick_params(color='w')
# axy.invert_yaxis() # we might need to invert y-axis

输出如下所示: enter image description here

关于python - 从 seaborn clustermap 结果中重新排序高级集群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com