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

Matplotlib绘图X轴错误显示1970年1月日期,2021年小时级日期索引绘图异常如何解决?

问题原因

matplotlib.dates.DateFormatter仅支持识别matplotlib内部定义的日期数值格式(以公元元年为起点的天数浮点值),直接传入pandas datetime64类型索引作为x轴输入时,bar方法不会自动完成格式适配,会将datetime64底层存储的Unix时间戳数值直接作为天数解析,换算后对应时间为1970年1月附近,因此出现日期显示错误。

修复方案

方案1:转换日期格式后再绘图

调用mdates.date2num方法将索引转换为matplotlib兼容的日期数值即可,代码示例:

import matplotlib.dates as mdates

if __name__ == '__main__':
    df = generate_signal_df_hourly()
    # 转换为matplotlib兼容的日期格式
    plt_dates = mdates.date2num(df.index)

    fig, ax = plt.subplots()
    ax.bar(plt_dates, df['close'])
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
    plt.xticks(rotation=20, ha='left')
    plt.show()

方案2:直接使用pandas内置绘图接口

pandas的plot方法会自动处理日期索引的格式适配,无需手动配置日期格式化逻辑,代码更简洁:

if __name__ == '__main__':
    df = generate_signal_df_hourly()
    ax = df.plot(y='close', kind='bar', rot=20)
    # 自定义x轴刻度显示格式
    ax.set_xticklabels([t.strftime('%Y-%m-%d') for t in df.index])
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 18:57:02