使用 seaborn 的水平箱线图

时间:2021-07-14 13:24:43

标签: python plot seaborn cluster-analysis

我有一个包含 30 名学生的数据集,每个学生有 7 个代表技能(艺术、数学等)的特征。在应用 k-means 算法后,这些学生被分为 3 个集群。 0, 1, 2 是标签:

Id CCL CMCT CD CPAA CSC SIE CEC labels
1    2    5  4  5.5   6 2.5   5      0
etc 

我想用 3 个不同的箱线图表示它,每个箱线图一个。我认为最好有一个水平图,其中“y”是七个技能,“x”是资格。我不确定如何使用 sns.boxplot() 实现这一点。

提前致谢。

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您会希望从融合数据帧开始,因为它目前是宽格式和 Seaborn prefers long or tidy format

然后您可以使用 sns.catplot() 使您拥有三个绘图,而不是一个。来自docs

<块引用>

使用 catplot() 组合 boxplot() 和 FacetGrid。这允许 在其他分类变量中分组。使用 catplot() 是 比直接使用 FacetGrid 更安全,因为它确保同步 跨方面的可变顺序:

### Make dummy dataframe
id = np.arange(1,10,1)
np.random.seed(0)
CCL = list(np.random.randint(5, size=len(id)))
CMCT = list(np.random.randint(8, size=len(id)))
CD = list(np.random.randint(5, size=len(id)))
CPAA = list(np.random.randint(9, size=len(id)))
CSC = list(np.random.randint(12, size=len(id)))
SIE = list(np.random.randint(5, size=len(id)))
CEC = list(np.random.randint(7, size=len(id)))
labels = list(np.random.randint(3, size=len(id)))
df = pd.DataFrame(list(zip(id, CCL, CMCT, CD, CPAA, CSC, SIE, CEC, labels)), 
    columns =['id', 'CCL', 'CMCT', 'CD', 'CPAA', 'CSC', 'SIE', 'CEC', 'labels']
    )
print(df)

enter image description here

### Now melt and plot
df_melt = pd.melt(df, id_vars=['id', 'labels'], 
            value_vars=['CCL', 'CMCT', 'CD', 'CPAA', 'CSC', 'SIE', 'CEC']
            )
print(df_melt)

sns.catplot(data=df_melt, x='value', y='variable', col='labels', kind='box')
plt.show()

enter image description here enter image description here

相关问题