- # Control order of boxplot
- #35 Control order of boxplot
Boxplots often give more information if you order group in a specific order. This is feasible with seaborn.
Here are 2 examples explaining the 2 main needs you can have:
- Use a specific order
-
# library & dataset import seaborn as sns df = sns.load_dataset('iris') # specific order p1=sns.boxplot(x='species', y='sepal_length', data=df, order=["virginica", "versicolor", "setosa"]) #sns.plt.show()
- By decreasing median
-
# library & dataset import seaborn as sns df = sns.load_dataset('iris') # Find the order my_order = df.groupby(by=["species"])["sepal_length"].median().iloc[::-1].index # Give it to the boxplot sns.boxplot(x='species', y='sepal_length', data=df, order=my_order) #sns.plt.show()
The above example for ordering by decreasing medians unfortunately does not work. It orders by the index instead.
Suggested correction:
my_order = df.groupby(by=[“species”])[“sepal_length”].median().sort_values(ascending=False).index
thanks, this worked. But how to get only top 10 bars.
Thanks!!