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

Matplotlib连续小时时间轴配置:实现%H:%M格式跨天连续显示

解决Matplotlib x轴连续小时(如48:00)显示的问题

你的问题出在使用了md.DateFormatter——这个工具是用来处理日历时间的,所以它会把超过24小时的部分自动重置为新一天的时间,无法实现你想要的累计时长显示。要实现连续小时格式(比如2天显示为48:00),我们需要自定义一个格式化函数,直接基于你的dataX数值(代表天数,1天=24小时)计算累计的小时和分钟。

下面是修改后的完整代码:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

dataY = np.array([0,1,2,3,4,5,6,7,8,9])
dataX = np.array([0.1,0.5,0.8,1.2,1.3,1.6,1.9,2.1,2.2,2.5])
dataX = dataX + 1  # 保持原有的偏移处理

fig, ax = plt.subplots()

# 自定义格式化函数:将天数转换为累计小时:分钟格式
def format_total_hours(x, pos):
    total_minutes = x * 24 * 60  # 把天数转成总分钟数
    hours = int(total_minutes // 60)
    minutes = int(total_minutes % 60)
    return f"{hours:02d}:{minutes:02d}"

# 设置x轴主要格式化器为自定义函数
ax.xaxis.set_major_formatter(mticker.FuncFormatter(format_total_hours))

plt.xlim(1,4)
plt.plot(dataX, dataY)
plt.ylabel('Y-Values')
plt.xlabel('Time [hh:mm]')
plt.show()

关键细节说明:

  • 我们用matplotlib.ticker.FuncFormatter替代了日期格式化工具,它允许我们完全自定义x轴标签的生成逻辑。
  • format_total_hours函数的逻辑:
    1. 把输入的x值(天数)转换成总分钟数:x * 24 * 60
    2. 计算累计小时数:总分钟数整除60
    3. 计算剩余分钟数:总分钟数取模60
    4. 用f"{hours:02d}:{minutes:02d}"格式化为两位数字的小时:分钟样式,确保比如5小时3分钟显示为05:03
  • 这样设置后,x轴的数值(比如x=2对应48小时,x=2.5对应60小时)就会被正确格式化为48:00、60:00这类连续时长,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:51:27