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

Matplotlib时间序列图顶部X轴标签错位问题求助

解决Matplotlib双X轴标签对齐问题

你的问题根源在于twiny()创建的顶部轴未与底部轴同步X轴范围,即便设置了相同刻度值,顶部轴仍会使用默认数值范围,导致标签位置错位。

修复方案

在创建顶部轴后添加范围同步代码,同时调整刻度的设置方式,确保上下轴刻度位置完全对应:

import matplotlib.pyplot as plt
import pandas as pd

# 构造示例数据(实际使用时替换为你的df即可)
date_range = pd.date_range("2022-07-31 00:00", "2022-07-31 23:59", freq="H")
df = pd.DataFrame({"High": range(len(date_range)), "Low": range(len(date_range))}, index=date_range)

time_zones = pd.to_datetime(["2022-07-31 2:00", "2022-07-31 6:00", "2022-07-31 9:00", 
                             "2022-07-31 14:00", "2022-07-31 17:00", "2022-07-31 23:55"])

fig, ax = plt.subplots(figsize=(14,8))
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_linestyle(":")
ax.spines["left"].set_linewidth(.36) 
ax.plot(df.loc["2022-07-31", "High"], color="green")
ax.plot(df.loc["2022-07-31", "Low"], color="red")

ax.set_ylabel("Price (€)", color="b")
ax.tick_params(labeltop=False, labelbottom=True)
# 获取时间戳在df索引中的位置,作为刻度位置
tick_positions = [df.index.get_loc(t) for t in time_zones]
ax.set_xticks(tick_positions, ["02:00", "06:00", "09:00", "14:00","17:00", "00:00"])

axT = ax.twiny()
# 同步顶部轴与底部轴的X范围,确保刻度位置对齐
axT.set_xlim(ax.get_xlim())
axT.tick_params(labeltop=True, labelbottom=False)
# 使用相同的刻度位置设置顶部时区标签
axT.set_xticks(tick_positions, ["Hong Kong", "Dubai", "London", "New York","Los Angeles", "Sydney"], fontsize=12, color="b")

ax.grid(True, linestyle=":")
plt.box(False)
plt.show()

核心要点

  1. 同步轴范围:通过axT.set_xlim(ax.get_xlim())强制顶部轴与底部轴的X轴范围完全一致,从根源避免刻度错位。
  2. 使用索引位置:利用df.index.get_loc()将时间戳转换为在数据索引中的位置,相比直接传入datetime,能更精准匹配上下轴的刻度位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 21:22:13