order bars in bar chart by value in descending order with plotly-express
Asked Answered
A

3

10

I need to make a plotly bar chart with bars ordered by value in descending order. I first order the dataframe by value in descending order. Then I use plotly.express to generate interactive bar chart. However, I found the bars are still in ascending order. Does anyone know what I did wrong? Thanks a lot for help.

import plotly.express as px
dat = pd.DataFrame({'word': ['apple', 'grape', 'orange', 'pear'],
                     'counts': [20, 5, 25, 10] } )
dat = dat.sort_values('counts', ascending=False)
px.bar(dat, x = 'counts',y='word', orientation='h')
Acolyte answered 3/11, 2019 at 5:32 Comment(0)
B
15

In the latest version of plotly 5.5.0, you can use categoryorder without the need for sorting the dataframe:

import plotly.express as px
dat = pd.DataFrame({'word': ['apple', 'grape', 'orange', 'pear'],
                     'counts': [20, 5, 25, 10] } )

fig = px.bar(dat, x = 'counts',y='word', orientation='h')
fig.update_layout(yaxis={'categoryorder':'total ascending'}) # add only this line

enter image description here

Breeze answered 12/3, 2022 at 18:36 Comment(0)
A
4

You should set ascending to True: The values of the y axis are ascending from bottom to top.

Antipope answered 3/11, 2019 at 10:29 Comment(0)
P
0

This method breaks down (fails) when the y-category name is a number, while it works if it is a string.

import plotly.express as px
dat = pd.DataFrame({'index': [1,2, 4, 3],
                 'counts': [20, 5, 25, 10] } )
fig = px.bar(dat, x = 'counts',y='index', orientation='h')
fig.update_layout(yaxis={'categoryorder':'total ascending'}) 
Potato answered 25/7 at 9:36 Comment(2)
Your wording is quite confusing. Can you explain, how your answer answers the question?Uhland
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Megacycle

© 2022 - 2024 — McMap. All rights reserved.