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

Pandas重采样后无法格式化X轴刻度全显示1970如何解决

问题根因

pandas的plot.bar()在处理时间索引数据时,不会将X轴识别为连续的时间序列,而是将每个索引值作为独立分类标签,X轴的底层坐标实际是0、1、2...的整数位置,并非时间戳数值。你调用dates.DateFormatter('%Y')时,会直接将整数坐标解析为Unix时间戳,而整数0对应的就是Unix纪元起始时间1970年1月1日,因此所有刻度都会错误显示为1970。

解决方案

这里提供两种常用的可行方案:

方案1:提前转换索引为年份(推荐,写法最简单)

在绘图前直接将重采样后的索引转换为年份值,不需要额外配置刻度格式化器:

# 先完成重采样计算
yearly_df = umtmvsDF.resample('A').mean()
# 替换索引为年份
yearly_df.index = yearly_df.index.year
# 直接绘图即可
ax = yearly_df.plot.bar(title='Average value per year',grid=True,color=(.21,.42,.12),figsize=(12,10))
ax.set(xlabel=Constants.TIME,ylabel=Constants.USD)
plt.show()

方案2:手动设置柱状图刻度标签

如果需要保留原时间索引,可直接获取柱状图的刻度标签后替换为年份:

yearly_df = umtmvsDF.resample('A').mean()
ax = yearly_df.plot.bar(title='Average value per year',grid=True,color=(.21,.42,.12),figsize=(12,10))
ax.set(xlabel=Constants.TIME,ylabel=Constants.USD)
# 手动将刻度标签替换为对应年份
ax.set_xticklabels(yearly_df.index.year)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 19:36:04