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

Matplotlib中如何隐藏x轴偏移标签并保留自定义相对刻度?

隐藏Matplotlib x轴偏移标签同时保留相对刻度

当绘制GPS时序数据时,我们常希望x轴显示相对于某一参考时间的秒数(范围[-100,100]),而非原始的大数值GPS时间。使用ticklabel_format设置偏移量后,虽然刻度显示符合需求,但x轴右下角会多出一个如+1.390585710e9的偏移标签,以下两种方法可以解决这个问题:

方法1:直接转换为相对时间

最直观的方式是提前把原始GPS时间转换成相对于参考时间的秒数,这样x轴本身就是目标数值,无需依赖ticklabel_format,自然不会出现偏移标签:

import matplotlib.pyplot as plt

xs = [1390585610, 1390585660, 1390585710, 1390585760, 1390585810]
ys = [-1, 0, 1, 0 , -1]
central_time = 1390585710  # 参考时间

# 转换为相对秒数
relative_xs = [x - central_time for x in xs]

fig, axs = plt.subplots(1)
axs.plot(relative_xs, ys)
plt.show()

方法2:隐藏偏移标签

如果不想修改原始数据,可以在使用ticklabel_format后,手动隐藏x轴的偏移文本:

import matplotlib.pyplot as plt

xs = [1390585610, 1390585660, 1390585710, 1390585760, 1390585810]
ys = [-1, 0, 1, 0 , -1]
central_time = 1390585710

fig, axs = plt.subplots(1)
axs.plot(xs, ys)
axs.ticklabel_format(axis='x', useOffset=central_time, style='plain')
# 隐藏x轴右下角的偏移标签
axs.xaxis.offsetText.set_visible(False)
plt.show()

两种方法都能实现目标:x轴显示相对参考时间的秒数,同时不显示多余的偏移标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:47:14