Bar chart doesn't display in descending order

I have a dataframe with some data. See screenshot below.
image
As shown the dataframe is already sorted in descending order. I then use the below code to build a horizontal barchart.

import plotly.graph_objects as go

test = df.head(10).copy()

fig = go.Figure(go.Bar(x=test['Published_Count'], y=test['Author'], orientation='h'))
fig.update_layout(barmode='stack', yaxis={'categoryorder':'total descending'})
fig.show()

The output I get is

I tried this with plotly express as well:

import plotly.express as px

test = df.head(10).copy()

fig = px.bar(test, x="Published_Count", y="Author", orientation='h')
fig.show()

What am I doing wrong? I tried categoryorder, categoryarray and everything I could find.

Hi,

I think your confusion is in what is the order the bars are placed by default. The direction is from bottom to top and not the other way around. That’s why you get the image you’ve shown, where the value for the first row in the dataframe is in the bottom.

If you want the biggest total on top and ordered values “descending down”, you need to use yaxis={'categoryorder':'total ascending'}

2 Likes

That worked. Thank you. It was counter intuitive though.

Agree.

@adamschroeder, maybe something to be added in the docs…?

Good point. Thank you @jlfsjunior . I’ll bring it to the attention of our technical writers.

1 Like