A simple question:
Instead of expliciting categories every time in plotly express, like:
JavaScript
x
8
1
fig = px.box(df, x="x_var", y="y_var",
2
category_orders={'x_var': ["categorie_1",
3
"categorie_2",
4
5
"categorie_n"]})
6
7
fig.show()
8
Can plotly inherit categorical order already setted in pandas? like:
JavaScript
1
8
1
df['x_var'] = pd.Categorical( df['x_var'],
2
categories = ["categorie_1",
3
"categorie_2",
4
5
"categorie_n"],
6
7
ordered=True)
8
So in the end will be just:
JavaScript
1
3
1
fig = px.box(df, x="x_var", y="y_var")
2
fig.show()
3
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
1
2
1
categoryorders = {'day': list(df['category'].cat.categories)}
2
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)}
Plot 2 – Without categoryorders = {'day': list(df['category'].cat.categories)}
Complete code:
JavaScript
1
6
1
import plotly.express as px
2
df = px.data.tips()
3
df['day'] = pd.Categorical(df['day'], categories = ['Thur', 'Fri', 'Sat', 'Sun'], ordered = True)
4
fig = px.box(df, x='day', y='tip', category_orders = {'day':list(df.day.cat.categories)})
5
fig.show()
6