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

如何在Matplotlib中正确设置与格式化timedelta坐标轴?

Matplotlib中Timedelta坐标轴的规范配置方案

完整实现代码

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

# 生成示例Timedelta数据
time_points = pd.date_range(start="2024-01-01", end="2024-01-10", freq="H")
delta = time_points - time_points[0]  # 计算相对于起始点的Timedelta
values = np.sin(np.linspace(0, 4*np.pi, len(delta))) + np.random.randn(len(delta))*0.1

# 创建图表
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(delta, values)

# --------------------------
# 核心:配置Timedelta坐标轴刻度
# --------------------------
# 主刻度:每1天(转换为秒:24*3600)
ax.xaxis.set_major_locator(ticker.MultipleLocator(base=24 * 3600))
# 自定义主刻度标签格式
def format_major(x, pos):
    days = int(x // (24 * 3600))
    return f"第{days+1}天"
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_major))

# 次刻度:每6小时(可改为3600秒即1小时)
ax.xaxis.set_minor_locator(ticker.MultipleLocator(base=6 * 3600))
# 自定义次刻度标签格式(可选)
def format_minor(x, pos):
    hours = int(x // 3600) % 24
    return f"{hours:02d}h"
ax.xaxis.set_minor_formatter(ticker.FuncFormatter(format_minor))

# 优化刻度显示
ax.tick_params(axis='x', which='minor', labelsize=8, labelcolor='#666666')
ax.grid(True, which='both', linestyle='--', alpha=0.7)

# 图表标注
ax.set_ylabel('数值')
ax.set_title('Timedelta坐标轴示例(主刻度:天,次刻度:小时)')
plt.tight_layout()
plt.show()

关键逻辑说明

  1. Timedelta的底层处理:Matplotlib会自动将timedelta64(numpy)或Timedelta(pandas)对象转换为总秒数数值,因此刻度间隔需要以秒为单位计算:

    • 1天 = 24 * 3600 秒
    • 1小时 = 3600 秒
  2. 刻度定位器:

    • 用MultipleLocator精确指定主/次刻度的间隔,确保刻度严格按天/小时划分,避免默认的无意义间隔。
    • 主刻度设为1天间隔,次刻度可根据需求调整为1小时、6小时等。
  3. 标签格式化:

    • 通过FuncFormatter自定义标签内容,比如主刻度显示天数序号,次刻度显示当日小时数,提升可读性。
    • 次刻度标签可调整字号和颜色,避免与主刻度重叠。

纯Numpy环境适配

如果不用pandas,直接生成numpy的timedelta64数组,处理逻辑完全一致:

# 生成纯numpy的Timedelta数组
delta = np.array([np.timedelta64(i, 'h') for i in range(0, 24*10)])
values = np.sin(np.linspace(0, 4*np.pi, len(delta))) + np.random.randn(len(delta))*0.1

# 后续坐标轴配置与上方代码完全相同

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:25:18