7

I have a pandas dataframe with 3 columns: name, group, value. I wanted to make a horizontal bar chart with plotly that is sorted from highest to lowest value and color each bar based on their value in the group column. The problem is that when I add the color argument, the bars get sorted by the colors as well. Is it possible to make the bars not get grouped together by color?

Here is what I have tried. When I run the code without specifying the color attribute, the bars are sorted correctly. The code without color:

import plotly.express as px
px.bar(df, x='value', y='name', orientation='h')
fig.show()

The output is just as expected:

Bars are sorted in descending order

However, when I add the color attribute, the bars get sorted by the color:

fig = px.bar(data, x='value', y='name', orientation='h', color='group')
fig.show()

The bars get a different sorting: The bars are grouped by colors

Is there a way to prevent this behavior of grouping of bars? I am using plotly version 4.1.1 with python 3.7. I want the bars sorted like the first code block but colored by the group column.

Asad Rauf
  • 743
  • 9
  • 17

1 Answers1

15

Your options here would be to either provide the desired ordering explicitly in category_orders e.g. category_orders=dict(group=["Tokyo", "Delhi", ...]) or if what you're after is simply to order them by value you can use set the Y-axis category order to be dynamic with fig.update_layout(yaxis_categoryorder = 'total ascending')

nicolaskruchten
  • 26,384
  • 8
  • 83
  • 101
  • Great, thanks. I thought you were wrong and then noticed I am using wrong axis :) BTW the docs are here https://plotly.com/python/reference/layout/yaxis/#layout-yaxis-categoryorder – shukshin.ivan May 19 '22 at 00:52