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

Python读取HH:MM:SS时间作为matplotlib柱状图x轴实现方法

实现方案

核心逻辑是不要直接用HH:MM:SS格式的字符串作为x轴输入(matplotlib会把字符串当成离散分类,柱子间隔完全相等且无法处理时间先后顺序),有两种成熟实现方式,按需选就行。


方法1:转datetime对象(推荐,自动适配时间逻辑)

matplotlib原生支持Python标准库的datetime类型作为坐标输入,只需要加个刻度格式化器就能保留HH:MM:SS的显示效果,还能自动处理时间排序、间隔适配。
首先导入依赖:

from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

修正原有的csv读取逻辑,补全语法问题,同时完成时间格式转换:

timeArray = []
tempArray = []

with open('file.csv', 'r') as f:
    next(f)  # 若csv无表头行,删掉这行
    for line in f:
        line = line.strip()
        if not line:
            continue  # 跳过空行避免报错
        time_str, temp_str = line.split(',')[:2]
        # 把HH:MM:SS字符串解析为时间对象
        time_obj = datetime.strptime(time_str, "%H:%M:%S")
        timeArray.append(time_obj)
        tempArray.append(float(temp_str))

绘图时配置x轴格式即可:

plt.figure(figsize=(10, 5))
# 注意datetime轴的单位是天,秒级数据的柱子宽度设为0.0005左右(约43秒),按需调整
plt.bar(timeArray, tempArray, width=0.0005)

# 强制x轴刻度显示为HH:MM:SS格式
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S"))
# 若刻度太密重叠,可取消下一行注释,设置每N秒显示一个刻度
# plt.gca().xaxis.set_major_locator(mdates.SecondLocator(interval=10))

plt.gcf().autofmt_xdate()  # 自动倾斜x轴标签避免重叠
plt.show()

方法2:转秒级数值(轻量,适合预排序的时序数据)

如果你的csv里的时间已经是按先后顺序排好的,可以直接把时间转成从0点开始的总秒数作为数值型x轴,最后替换刻度标签为原始时间字符串即可,不用处理datetime的单位适配问题:

timeArray = []
tempArray = []
time_labels = []  # 存原始时间字符串用于刻度显示

with open('file.csv', 'r') as f:
    next(f)  # 无表头就删掉
    for line in f:
        line = line.strip()
        if not line:
            continue
        time_str, temp_str = line.split(',')[:2]
        h, m, s = map(int, time_str.split(':'))
        total_sec = h * 3600 + m * 60 + s
        timeArray.append(total_sec)
        time_labels.append(time_str)
        tempArray.append(float(temp_str))

plt.figure(figsize=(10,5))
plt.bar(timeArray, tempArray, width=3)  # 宽度单位是秒,3就是3秒宽,按需调整
# 每隔N个点显示一个刻度,避免标签重叠,这里示例每5个点显示一个
plt.xticks(timeArray[::5], time_labels[::5], rotation=45)
plt.show()

注意事项

  • 读取csv时一定要先去掉行尾的换行符、跳过空行,不然字符串转时间/浮点数会报错
  • 方法1会自动按时间先后排序x轴位置,哪怕csv里的时间是乱序的也能正确展示;方法2严格按照csv读入的顺序排列x轴,仅适合时间已经预排序的场景
  • 柱状图的width参数要根据你数据的实际时间间隔调整,避免柱子过宽重叠、过窄看不清

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:24:24