Isbister
Isbister

Reputation: 946

Seaborn violin plot - compare all to one

I have a plot like the one below produced by the Seaborn docs: https://seaborn.pydata.org/generated/seaborn.violinplot.html

enter image description here

Lets not mind the actual data and labels here, its just for demonstration. What I would like to do is create all the orange distributions from the same data (as a baseline).

So all the blue distributions would be plotted against the same orange distribution for every weekday in this case.

Is this possible with the built in functionalities in Seaborn?

Upvotes: 0

Views: 626

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40697

I don't think there is anything "built-in" to do what you want, but it's fairly easy to do if you don't mind being a bit creative with your dataframe, but you'd have to provide the structure of your dataframe to make sure.

Here's a (very inefficient) way to do it with the tips dataset from seaborn

target_var = 'total_bill'
hue_var = 'smoker'
hue_value = 'Yes'
cat_var = 'day'
grouped_value = 'ALL WEEK'

tips = sns.load_dataset("tips")
tips2 = tips.loc[tips[hue_var]==hue_value]
for cat in tips[cat_var].unique():
    temp = tips.loc[:,[target_var]]
    temp[cat_var] = cat
    temp[hue_var] = grouped_value
    tips2 = tips2.append(temp, ignore_index=True, sort=False)

fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4))
sns.violinplot(x=cat_var, y=target_var, hue=hue_var, hue_order=['Yes','No'], 
               order=['Thur','Fri','Sat','Sun'],
               data=tips, palette="muted", split=True, ax=ax1)
sns.violinplot(x=cat_var, y=target_var, hue=hue_var, hue_order=[hue_value,grouped_value], 
               order=['Thur','Fri','Sat','Sun'],
               data=tips2, palette="muted", split=True, ax=ax2)

enter image description here

Upvotes: 1

Related Questions