Plotly express Line chart issue in getting months in order

Hello,
May I know how to get the months in order in express in line chart!
To access the line chart:
Plotly_data|690x153

Code is:
import plotly.graph_objs as go
fig = go.FigureWidget()

df_long=pd.melt(final_line_data, id_vars=[‘Month’], value_vars=[‘Amount_2016’, ‘Amount_2017’, ‘Amount_2018’, ‘Amount_2019’])
fig = px.line(df_long, x=‘Month’, y=‘value’, color=‘variable’)

fig.layout.xaxis.tickvals = pd.date_range(‘2016-01-01’, ‘2019-12-31’, freq=‘MS’)

fig.layout.xaxis.tickformat = ‘%y’

fig.show()

Earlier response is highly appreciated

final_line_data :

Month Amount_2016 Year_2016 Amount_2017 Year_2017 Amount_2018 Year_2018 Amount_2019 Year_2019
0 Apr 1395463.0 2016.0 NaN NaN NaN NaN NaN NaN
1 Aug 2016836.0 2016.0 NaN NaN NaN NaN NaN NaN
2 Dec 2300493.0 2016.0 NaN NaN NaN NaN NaN NaN
3 Jul 2098968.0 2016.0 NaN NaN NaN NaN NaN NaN
4 Jun 1748118.0 2016.0 NaN NaN NaN NaN NaN NaN

You can add the argument category_orders={"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]} to your px.line() call.

Hey Nicolas,
Great!

It’s working for me now. Thanks a lot.

Regards,
Bhagwat

Hi.

In line and area charts, it seems like Plotly is ignoring the category_orders parameter.

Plotly verison: 4.14.3

import plotly.express as px

df = px.data.tips().groupby('day').sum().reset_index('day')

px.line(
    x=df.day,
    y=df.total_bill,
    category_orders={"day": ["Thur", "Fri", "Sat", "Sun"]}
)

The order of the x-axis is expected to be “Thur”, “Fri”, “Sat”, “Sun”, however, we can see “Fri”, “Sat”, “Sun”, “Thur” in the chart.

Hello!

Plus one method, how create bar or line chart monthly, by order month.
Trics here is in order your grouped DataFrame by number month without additional sorting.

step 1 - add to your DataFrame column with month Number

df['month'] = df.net.dt.month

step 2 - add to your DataFrame column with month Name

df['month_name'] = df['date'].dt.month_name() 

step 3 - Group your DataFrame by first by month Number and second by month Name

df2 = df.groupby(['month', 'month_name'], as_index=False)['counts'].count()

step 4 - create chart where x axis is month name

fig = px.line(df2, x="month_name", y="counts", text='counts')         
fig.update_xaxes(tickformat='%b')