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

mplfinance设置刻度定位器后X轴日期显示为1970问题排查

解决mplfinance绘图后X轴日期显示为1970的问题

问题根源

mplfinance在外部Axes上绘图时,默认将X轴设置为DataFrame的整数索引(0、1、2...),而非matplotlib可识别的日期对象。直接使用mdates的刻度定位器时,这些整数会被解析为Unix纪元(1970-01-01)的时间偏移量,导致日期显示混乱。

修正方案

需要手动将整数索引映射回原始的DateTimeIndex,再配置刻度规则,同时确保次坐标轴与主坐标轴的日期范围同步。

修正后的完整代码

import yfinance as yf
import mplfinance as mpf
from datetime import datetime
import matplotlib.pylab as plt
from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates

# 下载样本数据
start_date = datetime(2019, 12, 1)
end_date = datetime(2020, 1, 31)
df = yf.download('AAPL', start=start_date, end=end_date)

# 创建绘图对象并绘制K线图
fig, ax = plt.subplots(figsize=(20, 10))
mpf.plot(df, ax=ax, type='candle', style='charles')

# -------------------------- 关键修正部分 --------------------------
# 获取原始日期索引,并转换为matplotlib可识别的日期数值
date_values = mdates.date2num(df.index.to_pydatetime())
# 替换X轴的整数刻度为实际日期值
ax.set_xticks(date_values)
ax.set_xticklabels(df.index.strftime('%Y-%m-%d'))

# 配置主X轴:月份为主刻度,日期为次刻度
months_locator = mdates.MonthLocator()
months_formatter = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(months_locator)
ax.xaxis.set_major_formatter(months_formatter)

days_locator = mdates.DayLocator(interval=1)
days_formatter = mdates.DateFormatter('%d')
ax.xaxis.set_minor_locator(days_locator)
ax.xaxis.set_minor_formatter(days_formatter)

# 配置次X轴(年份):同步主轴的日期范围
sec_xaxis = ax.secondary_xaxis(-0.08)
# 设置次轴的刻度范围与主轴一致
sec_xaxis.set_xlim(ax.get_xlim())
# 使用年份定位器和格式化器
years_locator = mdates.YearLocator()
years_formatter = mdates.DateFormatter('%Y')
sec_xaxis.xaxis.set_major_locator(years_locator)
sec_xaxis.xaxis.set_major_formatter(years_formatter)
# -----------------------------------------------------------------

# 调整刻度样式
plt.tick_params(pad=10)
sec_xaxis.spines['bottom'].set_visible(False)
sec_xaxis.tick_params(length=0, pad=10, labelsize=15)

plt.show()

关键说明

  • 用mdates.date2num()将DateTimeIndex转换为matplotlib兼容的日期数值,替换原有的整数X轴刻度
  • 次坐标轴通过set_xlim(ax.get_xlim())与主坐标轴同步日期范围,确保年份刻度正确对应数据区间
  • 保留了原需求的双X轴格式:主轴显示月份+日期,次轴显示年份

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 15:00:13