How to sorting bars inside Facet col/row Chart

Hi all,

I am trying to create faceted bar chart. Inside the faceted chart the bars are rendered in ascending or descending order.

Code

counting_edu = main_Dg.groupby([‘Education’,‘Gender’,‘Year’])[‘Numbers’].count().reset_index()
counting_edu.loc[counting_edu.Education == ‘Some college/university study without earning a bachelorâ\x80\x99s degree’,‘Education’] = ‘Without Degree’
edu = px.bar(y=counting_edu.Education,x=counting_edu.Numbers,animation_frame=counting_edu.Year)
edu.update_layout(height = 500,width = 800, title = ‘Educated Likewise’,
yaxis = {‘categoryorder’:‘total descending’})
#edu.update_yaxes(matches=None)
#edu.for_each_yaxis(lambda yaxis: yaxis.update(showticklabels=True))
edu.show()

Code End
Is there any way to achieve a sorted bars like shown below in the each facets?

Currently I have the facets like below

I have tried the following.

  1. working with the update_layout(xaxis ={‘categoryorder’:‘total descending’}) option.
  2. tried the category_order option in the px.bar() function.

Then I realized that the y-axis are common between multiple facets, so tried
3) fig.update_yaxes(matches=None)

Any ideas or thoughts would be greatly helpful.

I think you would want to sort the data source first – something like

df = df.sort_values('count_variable_in_your_chart',ascending=True)
1 Like

Thanks for looking into my challenge.

I tried the sorting the variables already. It is not providing the intended behaviour.

I am thinking of going with seperate graph objects bar charts, with subplots. I wanted to learn if plotly express has any option that I have missed.

Had the same issue, it is due to the fact the both plots share the y axis per default. if you sort your data first

df = df.sort_values('count_variable_in_your_chart',ascending=True)

and then facet plot with .update_yaxes(matches=None) as you had commented out it should give you teh intended behaviour. It worked at least for me
`(
px.bar(y=counting_edu.Education,x=counting_edu.Numbers,animation_frame=counting_edu.Year)

.update_layout(height = 500,width = 800, title = ‘Educated Likewise’,yaxis = {‘categoryorder’:‘total descending’})

.update_yaxes(matches=None)
)`

1 Like