【问题标题】:Plotting Quarterly Data - Plotly绘制季度数据 - Plotly
【发布时间】:2022-09-27 15:32:55
【问题描述】:

我正在尝试绘制下面的折线图,但我的 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:Period 类型的对象不是 JSON` 可序列化的

该列的数据类型为period[Q-DEC]

无论如何我可以有情节地阅读x轴吗?谢谢!

    标签: python python-3.x plotly data-science plotly-python


    【解决方案1】:

    您有两个选项可以解决此问题,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')
    
    fig = px.line(df, x='date', y='Values')
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2019-04-16
      • 2020-01-27
      • 2023-01-18
      相关资源
      最近更新 更多