我正在尝试绘制下面的折线图,但我的 x 轴是四分之一,例如
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()
我收到错误消息 - TypeError: Object of type period is not JSON`可序列化
列的数据类型为period[Q-DEC]
有没有办法可以读取 x 轴?谢谢!
最佳答案
您有两种选择来解决此问题:to_timestamp()
或 .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()
关于python - 绘制季度数据 - Plotly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73851229/