You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly绘制季度数据遇JSON序列化错误,如何让其识别x轴?

解决Plotly无法识别pandas Period类型x轴的问题

因为Plotly渲染时需要将数据序列化为JSON,而pandas的Period对象不支持JSON序列化,所以需要把quarter列转换为Plotly可识别的类型,以下是两种可行方案:

方案1:将Period转换为字符串类型

直接把季度列转为字符串,保留原2017Q1这类格式:

# 转换为字符串类型
qtrly_comp['quarter'] = qtrly_comp['quarter'].astype(str)

# 绘制折线图
fig = px.line(qtrly_comp, x="quarter", y="counts", template=template_style, markers=True)
fig.show()

方案2:将Period转换为Timestamp(时间戳)类型

如果需要保留时间的时序特性(比如后续做时间轴缩放、筛选),可以转为Timestamp,默认取季度起始时间,也可指定取结束时间:

# 转换为季度起始时间的Timestamp
qtrly_comp['quarter'] = qtrly_comp['quarter'].dt.to_timestamp()

# 可选:转换为季度结束时间
# qtrly_comp['quarter'] = qtrly_comp['quarter'].dt.to_timestamp(how='end')

# 绘制折线图,可自定义x轴显示格式
fig = px.line(qtrly_comp, x="quarter", y="counts", template=template_style, markers=True)
# 设置x轴显示为季度格式
fig.update_layout(xaxis=dict(tickformat="%YQ%q"))
fig.show()

内容的提问来源于stack exchange,提问作者Chris90

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:41:05