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

如何在Matplotlib中绘制timedelta并设置Y轴为HH:MM:SS格式

解决Matplotlib中Y轴显示HH:MM:SS时长格式的问题

Got it, let's fix this step by step. You're on the right track with pd.to_timedelta—here's how to get your Y-axis showing HH:MM:SS properly for your year-vs-duration chart:

完整实现代码

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

# 你的合成数据
df = pd.DataFrame({'Year':[2010, 2011, 2012], 'Time': ['2:19:15', '2:11:16', '2:20:17']})

# 1. 将时间字符串转为timedelta,再转换为总秒数(Matplotlib需要数值型数据绘图)
df['Time_seconds'] = pd.to_timedelta(df['Time']).dt.total_seconds()

# 2. 定义自定义格式化函数:把秒数转换成HH:MM:SS格式
def format_duration(seconds, pos):
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    # 用补零格式化确保时/分/秒都是两位数字
    return f"{hours:02d}:{minutes:02d}:{secs:02d}"

# 3. 绘制图表并应用格式化器
fig, ax = plt.subplots()
ax.plot(df['Year'], df['Time_seconds'], marker='o', color='#1f77b4')

# 把自定义格式化器绑定到Y轴
ax.yaxis.set_major_formatter(FuncFormatter(format_duration))

# 设置轴标签和标题
ax.set_xlabel('Year', fontsize=12)
ax.set_ylabel('Duration (HH:MM:SS)', fontsize=12)
ax.set_title('Year vs. Total Duration', fontsize=14)

# 调整布局避免标签被截断
plt.tight_layout()
plt.show()

关键步骤解释

  • 转换为总秒数:Matplotlib的绘图系统依赖数值型数据,timedelta类型无法直接作为轴数据,所以我们把时长转成总秒数作为绘图的底层数值。
  • 自定义Y轴格式化器:使用FuncFormatter可以完全控制轴标签的显示格式。我们的函数把秒数拆解为时、分、秒,并用02d格式化确保每个部分都是两位数字(比如1小时会显示为01)。
  • 适配任意时长:这个方案支持超过24小时的时长(比如30小时会显示为30:XX:XX),如果你的真实数据有更长的时长也能完美适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:02:11