How to split a grouped plot in Seaborn Python?

Viewed 49

I have a data frame like this:

df:
Type   Col-1  Col-2
A        3      8
A        4      7
A        5      9
A        6      6
A        7      7
B        4      8
B        2      7
B        6      6
B        4      9
B        5      7

I have 2 violin plots for Col-1 & Col-2. Now, I want to create a single violin plot with 2 violin images for Type A & B. In the violin plot, I want to split every violin such that the left half of the violin denotes Col-1 & right half of the violin denotes Col-2. I created two separate violin plots for col-1 and col-2 but now I want to make it a single plot and represent 2 columns at a time by splitting. How can I do it?

This is my code for separate plots:

def violin(data):
    for col in data.columns:    
        x = data[col].to_frame().reset_index()
        ax = sns.violinplot(data=x, x='type',y=col,inner='quart',split=True)
        plt.show()
violin(df)

This is what my current violin plots look like. I want to make them in single plot:

This is how my plots look now

Can anyone help me with this?

1 Answers

Seaborn works easiest with data in "long form", combining the value columns.

Here is how the code could look like:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

df = pd.DataFrame({'Type': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
                   'Col-1': [4, 3, 5, 6, 7, 4, 2, 6, 4, 5],
                   'Col-2': [7, 8, 9, 6, 7, 8, 7, 6, 9, 7]})
df_long = df.melt(id_vars=['Type'], value_vars=['Col-1', 'Col-2'], var_name='Col', value_name='Value')

plt.figure(figsize=(12, 5))
sns.set()
sns.violinplot(data=df_long, x='Type', y='Value', hue='Col', split=True, palette='spring')
plt.tight_layout()
plt.show()

seaborn split violinplot

Related