Horizontal boxplot using seaborn

Viewed 188

I have a dataset of 30 students with 7 features each that represent skills (art, mathematics, etc). After applying k-means algorithm, these students were divided in 3 clusters. 0, 1, 2 are the labels:

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

I would like to represent it in 3 different boxplots, one for each cluster. I thought that it would be good to have an horizontal plot where "y" was the seven skills and "x" was the qualification. I am not sure how to achieve this with sns.boxplot().

Thanks in advance.

1 Answers

If I understand correctly, you would want to start by melting your dataframe because it is currently in wide format and Seaborn prefers long or tidy format.

Then you can use sns.catplot() so that you have three plots, instead of one. From the docs:

Use catplot() to combine a boxplot() and a FacetGrid. This allows grouping within additional categorical variables. Using catplot() is safer than using FacetGrid directly, as it ensures synchronization of variable order across facets:

### 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

Related