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

在多子图中使用mdates.ConciseDateFormatter出现x轴偏移错误如何解决

多子图使用mdates.ConciseDateFormatter x轴偏移问题解决方案

问题原因

出现该异常的核心原因是多个子图共用了同一个AutoDateLocator实例。日期定位器实例会随绑定的坐标轴动态调整内部的时间范围参数,绑定第二个子图时覆盖了第一个子图对应的定位器配置,最终导致第一个子图的x轴刻度计算错误。该问题属于matplotlib日期定位器的设计特性,并非逻辑bug。

解决方案

每个子图分别创建独立的定位器和格式化器实例即可解决问题,修正后代码如下:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

dti = pd.to_datetime(["2016-08-31", "2016-09-30"])
ts0 = pd.DataFrame({"x": [0, 1]}, index=dti)
ts1 = pd.DataFrame({"x": [0, 1]}, index=dti + pd.Timedelta(365, "D"))
fig, axs = plt.subplots(2, 1, sharex=False)
ts0["x"].plot(ax=axs[0], marker="o")
ts1["x"].plot(ax=axs[1], marker="o")

# 第一个子图使用独立的定位器、格式化器
dlocator_0 = mdates.AutoDateLocator(minticks=6, maxticks=9)
axs[0].xaxis.set_major_locator(dlocator_0)
axs[0].xaxis.set_major_formatter(mdates.ConciseDateFormatter(dlocator_0))

# 第二个子图使用独立的定位器、格式化器
dlocator_1 = mdates.AutoDateLocator(minticks=6, maxticks=9)
axs[1].xaxis.set_major_locator(dlocator_1)
axs[1].xaxis.set_major_formatter(mdates.ConciseDateFormatter(dlocator_1))

plt.show()

如果子图数量较多,可以用循环批量生成实例,避免重复代码:

for ax in axs.flat:
    dlocator = mdates.AutoDateLocator(minticks=6, maxticks=9)
    ax.xaxis.set_major_locator(dlocator)
    ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(dlocator))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:36:03