Skip to content
Advertisement

Plotly (Python) – Can plotly inherit categories order setted in pandas?

A simple question:

Instead of expliciting categories every time in plotly express, like:

JavaScript

Can plotly inherit categorical order already setted in pandas? like:

JavaScript

So in the end will be just:

JavaScript

Advertisement

Answer

To my knowledge, the order of the categories is not automatically implemented for the x-axis. But you don’t have to hard-code it like you’ve done in your example. Instead you can retrieve the order of the categories from your df with, for example:

JavaScript

Here’s an example where the categories in question are the days ['Thur', 'Fri', 'Sat', 'Sun'] from the px.data.tips() dataset:

Plot 1 – With categoryorders = {'day': list(df['category'].cat.categories)}

enter image description here

Plot 2 – Without categoryorders = {'day': list(df['category'].cat.categories)}

enter image description here

Complete code:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement