I am trying to plot the below line chart in plotly, but my x axis is a quarter such as
df['quarter'] = pd.PeriodIndex(df.date, freq='Q')
quarter
2017Q1
2017Q2
...
fig = px.line(qtrly_comp, x="quarter", y="counts",template=template_style,markers = True)
fig.show()
I am getting error that reads - TypeError: Object of type Period is not JSON` serializable
datatype of the column is period[Q-DEC]
Is there anyway I can get plotly to read the x axis ? Thanks!
You have two options to overcome this problem either to_timestamp() or .strftime('%m-%Y'):
import pandas as pd
import plotly.express as px
df = pd.DataFrame({'Quarter':['2021Q1','2021Q2','2021Q3','2021Q4','2022Q1','2022Q2'],
'Values':[2,4,1,5,8,1]})
df['date'] = pd.PeriodIndex(df['Quarter'], freq='Q').strftime('%m-%Y')
df = df.sort_values(by='Quarter', ascending=True)
fig = px.line(df, x='date', y='Values')
fig.show()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With