I'm trying to create a seaborn barplot of a groupby object. Here is an example:
data = {'ID':[1, 2, 3, 1, 2, 3],
'value':[10, 20, 30, 100, 200, 300],
'other': ['a', 'b', 'c', 'd', 'e','f']
}
data = pd.DataFrame(data)
I want to use groupby()
to group the data by ID
, calculate the mean value
, and sort in descending order by value
:
grouped = data.groupby('ID').mean()
grouped = grouped.sort_values(by='value', ascending=False)
grouped
Now I want to plot this using seaborn's barplot:
sns.barplot(x=grouped.index, y=grouped['value'])
This is the result:
The plot retains the original order and ignores the fact that I reassigned grouped
to change the order.
Why does this happen? I've tried so many different approaches, and it always yields the same results.
You can always force the order:
sns.barplot(x=grouped.index, y=grouped['value'], order=grouped.index)