plotly.py: update_xaxes(categoryorder="total descending") does not work correctly on px.histogram

Hello, When using update_xaxes(categoryorder="total descending") on a histogram, I expect the bars to be reordered by size. The following example, tested in a Notebook, will not work according to my expectation:

import pandas as pd
import plotly.express as px

data =[['A','left'],['B','left'],['C','right'],['D','up'],['E','right'],['F','down'],
       ['A','right'],['B','righ'],['B','right'],['B','up'],['A','left'],['F','up'],
       ['B','left'],['F','left'],['B','right'],['A','up'],['A','right'],['F','down'],
      ]
df = pd.DataFrame(data, columns=['letter','direction'])
px.histogram(df, x='letter', color='direction').update_xaxes(categoryorder="total descending")

image

Note that the behavior is unclear to me. In certain condition, the order might be correct. For instance, if you change the last row to ['E','down'], then the order of the plot is correct.

In any case, I would expect the same result than the following:

import pandas as pd
import plotly.express as px

data =[['A','left'],['B','left'],['C','right'],['D','up'],['E','right'],['F','down'],
       ['A','right'],['B','righ'],['B','right'],['B','up'],['A','left'],['F','up'],
       ['B','left'],['F','left'],['B','right'],['A','up'],['A','right'],['E','down'],
      ]

df = pd.DataFrame(data, columns=['letter','direction'])
df['count'] = 1
df = df.groupby(['letter','direction'])['count'].sum().reset_index()
px.bar(df, x='letter', y='count', color='direction').update_xaxes(categoryorder="total descending")

image

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 18 (6 by maintainers)

Most upvoted comments

@nicolaskruchten I’m testing in a Dash App and with Terminal with same result.

I’m working with data in this attach file ( test_dataframe.txt ) and running the following exmeple :

col = ['lib','type','year','sup']

# Get data with attach file
df = pd.DataFrame(data, columns=col)

fig1 = px.histogram(df, x='year', y='sup', color='type').update_xaxes(type="category", categoryorder="total descending")

fig1.show()

fig2 = px.histogram(df, x='lib', y='sup', color='type').update_xaxes(type="category", categoryorder="total descending")

fig2.show()

fig1 is always displaying in the right order and fig2 always displaying in the wrong order 2020-10-27_10h21_16