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

如何将CSV中的秒数转换为时分格式并在图表Y轴正确展示?

解决Y轴秒数转“小时:分钟”格式的问题

核心方案:保留数值型秒数,自定义刻度格式化

不需要把数据转换成datetime/timedelta类型(这类类型matplotlib绘图支持有限),而是让Y轴底层仍用秒数(数值型),只修改刻度的显示文本,这样既保证可绘图,又能显示目标格式。

用matplotlib的FuncFormatter自定义格式化函数,示例代码:

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

# 读取CSV(假设你的CSV列名为'AVG',存储秒数)
df = pd.read_csv('你的文件.csv')

# 定义格式化函数:秒数转"小时:分钟"
def sec_to_hhmm(x, pos):
    hours = int(x // 3600)
    minutes = int((x % 3600) // 60)
    return f"{hours:02d}:{minutes:02d}"

# 绘图
fig, ax = plt.subplots()
ax.bar(df.index, df['AVG'])  # 替换成你的实际X轴列名

# 设置Y轴刻度格式化器
ax.yaxis.set_major_formatter(FuncFormatter(sec_to_hhmm))

# 可选:优化Y轴刻度间隔,比如按30分钟(1800秒)分段
ax.set_yticks(range(0, int(df['AVG'].max()) + 1800, 1800))

# 可选:在柱状图顶部标注小时:分钟格式
for i, val in enumerate(df['AVG']):
    hhmm = sec_to_hhmm(val, None)
    ax.annotate(hhmm, (i, val), ha='center', va='bottom')

plt.show()

Timple工具的正确用法

如果坚持用Timple,需先把秒数转为timedelta类型,再调用Timple的格式化器:

import pandas as pd
import matplotlib.pyplot as plt
from timple import Timple

df = pd.read_csv('你的文件.csv')
# 把秒数转换为timedelta类型
df['AVG_delta'] = pd.to_timedelta(df['AVG'], unit='s')

tpl = Timple()
fig, ax = plt.subplots()
ax.bar(df.index, df['AVG_delta'])
# 指定显示格式为小时:分钟
tpl.yaxis.set_major_formatter('%H:%M')

plt.show()

常见失效原因说明

  • 直接用datetime/timestamp:这类类型表示的是时间点而非时长,不适合转换秒数时长
  • 转成字符串:文本型数据无法被matplotlib识别为数值,无法正常绘图和计算刻度
  • 仅用divmod标注:只能修改柱状图顶部文本,无法改变Y轴刻度本身的显示格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:50:27