python - 绘制季度数据 - Plotly

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

我正在尝试绘制下面的折线图,但我的 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()

enter image description here

关于python - 绘制季度数据 - Plotly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73851229/

相关文章:

javascript - Plotly:基于 GeoJSON 文件创建 map

Python 继承 : what is the difference?

python - 如何在 python numpy 中并行化求和计算?

python - tkinter - ttk TreeView : see column text

python - 双重包装斐波那契

javascript - Plotly.js x 轴无法删除线

r - 在单个图中获取 geom_hex 中的观测值( Shiny )

python - 垃圾收集器是否跟踪所有 Python 对象?

python - 装饰链

python - QObject 实例化时的 PySide 段错误