Main
Main

Reputation: 160

Python: Seaborn: Sorting based on Y Axis instead of X Axis

I have the following data

Index   ID          Amount
360822  96996965    452456
385861  97122362    388764
574798  17681255    428909
633610  17841255    425101
806930  18373304    1049287
814809  18406524    614720
877178  15683610    485065
996266  16123139    434727
1279340 16934859    403961
1356620 17167658    544570

Index column is the index of dataframe. I have plotted the ID (X Axis) vs amount (Y Axis) in the graph. ID gets sorted in ascending order.

import seaborn as sns

plot = sns.barplot(x='ID', y='Amount', data=df)

Is there a way to sort the plot with respect to Y axis so that the ID with largest Amount is on the leftmost and one with smallest value of Amount is in right most.

Upvotes: 3

Views: 12598

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40707

You can pass an order= parameter to barplot to change the order of the bars. If you sort your dataframe in descending Amounts and get the corresponding IDs then you can use that in the call to barplot

plot_order = df.sort_values(by='Amount', ascending=False).ID.values
plot = sns.barplot(x='ID', y='Amount', data=df, order=plot_order)

enter image description here

Upvotes: 6

Related Questions