Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable plotly express from grouping bars based on color?

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.

like image 220
Asad Rauf Avatar asked Sep 17 '19 20:09

Asad Rauf


1 Answers

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')

like image 169
nicolaskruchten Avatar answered Nov 08 '22 15:11

nicolaskruchten