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

如何将Matplotlib图表X轴标签从timedelta转为起始天数

将Matplotlib时间序列图表的X轴改为显示距起始时间的天数

当然可以,有两种简单的方法实现这个需求:

方法1:直接使用已计算的天数数组绘图

你已经计算出了day变量(它本质是距起始时间的天数数值),直接把它作为x轴数据传入plot函数即可,这样X轴会直接显示天数:

修改核心代码:

fig, ax = plt.subplots()
ax.plot(day, vals)  # 替换timedelta为day
ax.set_xlabel('距起始时间的天数')
plt.show()

方法2:自定义X轴刻度格式化器(保留timedelta数据)

如果想继续使用timedelta作为绘图的原始x数据,也可以通过自定义刻度格式化器来转换显示内容:

需要导入matplotlib.ticker.FuncFormatter,然后定义一个格式化函数,把timedelta对象转换成带小数的天数:

from matplotlib.ticker import FuncFormatter

# 定义格式化函数:将timedelta转换为精确到两位小数的天数
def format_days(x, pos):
    # 计算总天数:整数天 + 秒数转换为天数
    total_days = x.days + x.seconds / (24 * 3600)
    return f"{total_days:.2f}"

fig, ax = plt.subplots()
ax.plot(timedelta, vals)
# 应用自定义格式化器到X轴
ax.xaxis.set_major_formatter(FuncFormatter(format_days))
ax.set_xlabel('距起始时间的天数')
plt.show()

完整可运行示例代码

把两种方法整合到你的原代码中,完整版本如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter

# 生成示例数据
vals = np.random.uniform(low=5.5, high=5.6, size=(100,))
datetime = pd.date_range(start='2022-03-10',
                  end='2022-03-15',
                  periods=100)

time0 = datetime[0]
timedelta = datetime - time0
day = timedelta.astype('timedelta64[D]')

# 方法1:直接使用天数数组绘图
fig, ax1 = plt.subplots(figsize=(8, 4))
ax1.plot(day, vals)
ax1.set_xlabel('距起始时间的天数')
ax1.set_title('方法1:直接使用天数数组')
plt.tight_layout()

# 方法2:自定义刻度格式化器
def format_days(x, pos):
    total_days = x.days + x.seconds / (24 * 3600)
    return f"{total_days:.2f}"

fig, ax2 = plt.subplots(figsize=(8, 4))
ax2.plot(timedelta, vals)
ax2.xaxis.set_major_formatter(FuncFormatter(format_days))
ax2.set_xlabel('距起始时间的天数')
ax2.set_title('方法2:自定义刻度格式化器')
plt.tight_layout()

plt.show()

内容的提问来源于stack exchange,提问作者Will Davis Birch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:20:26