WF30
WF30

Reputation: 253

How to custom order the x axis category orders in plotly express subplots

Below shown is the data to plot the bar chart in plotly express subplots

enter image description here

Below is the syntax is used to create the bar chart in plotly express subplots by using category_orders to customize the order of the x axis's.

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots


# Male Trace
trace1  = go.Bar(
                        x = df[df['Gender']=='Male']['Job_Satisfaction'],
                        y = df[df['Gender']=='Male']['count'],
                        name = 'Male',
                        text = ['{}, {:.0%}'.format(v, p/100) for v,p in zip( df[df['Gender']=='Male']['count'],  df[df['Gender']=='Male']['%'])],
                        textposition = 'inside',
                        marker_color = ['#06266B']*len(df['Job_Satisfaction']),
                        category_orders ={'Job_Satisfaction':['Low','Medium','High','Very High']},
                       )

# Female Trace
trace2  = go.Bar(
                        x = df[df['Gender']=='Female']['Job_Satisfaction'],
                        y = df[df['Gender']=='Female']['count'],
                        name = 'Female',
                        text = ['{}, {:.0%}'.format(v, p/100) for v,p in zip( df[df['Gender']=='Female']['count'],  df[df['Gender']=='Female']['%'])],
                        textposition = 'inside',
                        marker_color = ['#8F0396']*len(df['Job_Satisfaction']),
                        category_orders  ={'Job_Satisfaction':['Low','Medium','High','Very High']},
                       )


fig.append_trace(trace1,1,2)
fig.append_trace(trace2,1,2)

fig.show()

and I do get the below error message

enter image description here

How do I get a bar chart by customizing the orders in plotly express subplots from Job_Satisfaction column where the order of the x axis's should be 'Low','Medium','High','Very High'. And the Bar Chart should look shown below

enter image description here

Upvotes: 1

Views: 4560

Answers (1)

Redox
Redox

Reputation: 9967

To order categorical entries, you can update the dataframe by using pd.Categorical() and sorting the data you want to plot instead to doing it in the plot. You can comment out the two lines with category_orders ={..} and ad these two lines before plotting.

df['Job_Satisfaction'] = pd.Categorical(df['Job_Satisfaction'], ["Low", "Medium", "High", "Very High"])
df.sort_values(['Job_Satisfaction'], inplace=True)

This will give the plot as below. I used the same data as what was in the previous example.

enter image description here

Upvotes: 3

Related Questions