emilaz
emilaz

Reputation: 2062

Seaborn Violinplot change order of hue

I'm trying to draw split violins to compare them across the hue variable. The plotting itself works fine, but I would like to have the order of the hue variables changed (i.e. 'True' being on the left side of the split instead of on the right). A small working example is this:

import pandas as pd
import seaborn as sns
df = pd.DataFrame({'my_bool': pd.Series(np.random.choice([True,False],20),dtype='bool'),
                'value': pd.Series(np.random.choice(200,20),dtype='int'),
                'my_group': np.random.choice(['A','B'],20)})
sns.violinplot(x='my_group',data=df,y='value',hue='my_bool',split=True, palette = {True:'blue', False:'red'})

This is how the output looks like:

What I want to achieve is having the False entries on the right of each split, the True entries on the left. Is there any way to achieve that?

Upvotes: 6

Views: 4958

Answers (1)

Fourier
Fourier

Reputation: 2983

You need to set hue_order:

import pandas as pd
import seaborn as sns
import numpy as np

df = pd.DataFrame({'my_bool': pd.Series(np.random.choice([True,False],20),dtype='bool'),
                'value': pd.Series(np.random.choice(200,20),dtype='int'),
                'my_group': np.random.choice(['A','B'],20)})
sns.violinplot(x='my_group',data=df,y='value',hue='my_bool', hue_order= [True, False], split=True, palette = {True:'blue', False:'red'})

Upvotes: 10

Related Questions