gpt4 book ai didi

python - 根据聚类按行划分seaborn矩阵

转载 作者:太空宇宙 更新时间:2023-11-03 11:25:49 25 4
gpt4 key购买 nike

This paper通过绘制二维矩阵并根据聚类对值进行排序,可以很好地可视化具有二元特征的数据集的聚类。

clusters

在这种情况下,有三个集群,如黑色分界线所示;行已排序,并显示每个聚类中有哪些示例,列是每个示例的特征。

给定一个集群分配向量和一个 pandas DataFrame,我如何使用 Python 库(例如 seaborn)复制它?使用 seaborn 绘制 DataFrame 并不困难,对 DataFrame 的行进行排序以与集群分配对齐也不难。我最感兴趣的是如何显示那些描绘每个集群的黑色分界线。

虚拟数据:

"""
col1 col2
x1_c0 0 1
x2_c0 0 1
================= I want a line drawn here
x3_c1 1 0
================= and here
x4_c2 1 0
"""
import pandas as pd
import seaborn as sns

df = pd.DataFrame(
data={'col1': [0, 0, 1, 1], 'col2': [1, 1, 0, 0]},
index=['x1_c0', 'x2_c0', 'x3_c1', 'x4_c2']
)
clus = [0, 0, 1, 2] # This is the cluster assignment

sns.heatmap(df)

enter image description here

最佳答案

mwaskom 在评论中发布的链接是一个很好的起点。诀窍是弄清楚垂直线和水平线的坐标是什么。

为了说明代码的实际作用,值得单独绘制所有线条

%matplotlib inline

import pandas as pd
import seaborn as sns

df = pd.DataFrame(data={'col1': [0, 0, 1, 1], 'col2': [1, 1, 0, 0]},
index=['x1_c0', 'x2_c0', 'x3_c1', 'x4_c2'])

f, ax = plt.subplots(figsize=(8, 6))

sns.heatmap(df)

ax.axvline(1, 0, 2, linewidth=3, c='w')
ax.axhline(1, 0, 1, linewidth=3, c='w')
ax.axhline(2, 0, 1, linewidth=3, c='w')
ax.axhline(3, 0, 1, linewidth=3, c='w')

f.tight_layout()

enter image description here

axvline 方法的工作方式是第一个参数是直线的 x 位置,然后是直线的下限和上限(在本例中为 1、0、2) .水平线采用 y 位置,然后是该线的 x 起点和 x 终点。默认值将为整个绘图创建线条,因此您通常可以将它们省略。

上面的代码为数据框中的每个 值创建了一行。如果要为热图创建组,则需要在数据框中创建一个索引,或者要循环遍历的其他一些值列表。例如,使用来自 this example 的代码的更复杂示例:

df = pd.DataFrame(data={'col1': [0, 0, 1, 1, 1.5], 'col2': [1, 1, 0, 0, 2]},
index=['x1_c0', 'x2_c0', 'x3_c1', 'x4_c2', 'x5_c2'])

df['id_'] = df.index
df['group'] = [1, 2, 2, 3, 3]
df.set_index(['group', 'id_'], inplace=True)
df

col1 col2
group id_
1 x1_c0 0.0 1
2 x2_c0 0.0 1
x3_c1 1.0 0
3 x4_c2 1.0 0
x5_c2 1.5 2

然后用组绘制热图:

f, ax = plt.subplots(figsize=(8, 6))

sns.heatmap(df)

groups = df.index.get_level_values(0)

for i, group in enumerate(groups):
if i and group != groups[i - 1]:
ax.axhline(len(groups) - i, c="w", linewidth=3)

ax.axvline(1, c="w", linewidth=3)

f.tight_layout()

enter image description here

因为您的热图不对称,您可能需要为列使用单独的 for 循环

关于python - 根据聚类按行划分seaborn矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34260084/

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