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

Matplotlib使用datetime数据时ax.twiny()第二X轴刻度定位问题

解决方案

核心思路是让顶部双X轴和底部时间轴共享完全一致的数值坐标体系(matplotlib内部会将datetime类型自动转换为浮点型时间戳),仅自定义顶部轴的刻度位置和显示标签,不需要做额外的坐标映射,彻底避免定位偏差。

完整修改后代码

from datetime import timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# 新增导入刻度定位工具
from matplotlib.ticker import FixedLocator

gfg = np.array(np.datetime64('2019-08-26 18:00'))
forecast_time = []
forecast_time.append(gfg)
df_forecast_time = pd.DataFrame(forecast_time)
forecast_data = []
forecast_data.append(0)
for i in range(1,10):
    df_forecast_time=df_forecast_time.append(df_forecast_time.loc[i-1]+timedelta(hours=1),ignore_index=True)
    forecast_data.append(i)

forecast_time_arr = np.array(df_forecast_time)
forecast_data_arr = np.array(forecast_data)

event_time = np.array(np.datetime64('2019-08-27 01:25'))
lead_time = []
lead_time.append(event_time)
df_lead_time = pd.DataFrame(lead_time)
for i in range(1,5):
    df_lead_time=df_lead_time.append(df_lead_time.loc[i-1]+timedelta(hours=-1),ignore_index=True)

lead_time_arr = np.array(df_lead_time)

##################################
fig=plt.figure()
plt.plot(forecast_time_arr,forecast_data_arr)

ax = plt.gca()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

ax.set_xlim([forecast_time_arr[0],forecast_time_arr[-1]]) 

plt.xlabel('预测时间(Forecast time)')
plt.ylabel('预测数据(Forecast data)')

plt.vlines(event_time, forecast_data_arr[0], forecast_data_arr[-1], color='red')

plt.grid(True, color = "grey", linewidth = ".4", linestyle = "-.")

# ========== 新增顶部前置时间轴代码 START ==========
ax2 = ax.twiny()
# 顶部轴和底部轴保持完全相同的数值范围,避免坐标错位
ax2.set_xlim(ax.get_xlim())
# 将前置时间对应的datetime转换为matplotlib内部数值作为刻度位置
lead_ticks = mdates.date2num(lead_time_arr.flatten())
# 自定义刻度标签:事件点为0h,往前1小时为1h,可根据需求调整格式
lead_labels = [f"{i}h" for i in range(len(lead_time_arr))]
# 设置顶部轴的刻度和标签
ax2.xaxis.set_major_locator(FixedLocator(lead_ticks))
ax2.set_xticklabels(lead_labels)
ax2.set_xlabel('前置时间(Lead time)')
# ========== 新增顶部前置时间轴代码 END ==========

plt.show()

关键修改说明

  • 调用twiny()创建顶部轴后,直接同步底部轴的x轴范围,保证两个轴的坐标体系完全一致
  • 你已生成的lead_time_arr存储了所有需要展示前置时间对应的真实datetime值,直接通过mdates.date2num转换为matplotlib可识别的刻度位置,100%匹配底部时间轴的坐标
  • 自定义刻度标签为对应小时数即可,不需要额外做时间换算,彻底解决datetime格式下的刻度定位偏差问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:15:04