Manage the order of groups in seaborn violinplot

logo of a chart:Violin

One could decide to change the order in which groups appear in a given plot, wether it be for the sake of clarity or other reasons. This can be performed with the 'order' parameter, either by specifying directly the order of the groups through a list, or by generating an ordered list based on the groups corresponding mean for example.

Directly specyfing a list

Thanks to the 'order' parameter of the violinplot function, you can set the order in which you expect the distributions to appear on the figure.

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
  
sns.set_theme(style="darkgrid")
df = sns.load_dataset('iris')

# specifying the group list as 'order' parameter and plotting
sns.violinplot(x='species', y='sepal_length', data=df, order=[ "versicolor", "virginica", "setosa"])
plt.show()

Ordering by decreasing median

Instead of creating the list 'by hand' with various categories, you can also use the power of pandas operations (groupby, median or mean) in order to create a ranked list, which we stored in 'my_order' variable in the following example.

# libraries & dataset
import seaborn as sns
import matplotlib.pyplot as plt
  
sns.set_theme(style="darkgrid")
df = sns.load_dataset('iris')
 
# Using pandas methods and slicing to determine the order by decreasing median
my_order = df.groupby(by=["species"])["sepal_length"].median().sort_values().iloc[::-1].index
 
# Specifying the 'order' parameter with my_order and plotting
sns.violinplot(x='species', y='sepal_length', data=df, order=my_order)
plt.show()

🚨 Grab the Data To Viz poster!


Do you know all the chart types? Do you know which one you should pick? I made a decision tree that answers those questions. You can download it for free!

    dataviz decision tree poster