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

如何在坐标轴上绘制datetime.time类型数据?

解决Matplotlib不支持datetime.time类型坐标轴的问题

针对你用datetime.time作为索引的DataFrame绘图报错的问题,这里提供三种实用方案,既能解决Matplotlib的类型兼容问题,又能保留数据的时间可操作性:

方案1:将datetime.time转为timedelta类型

Matplotlib原生支持timedelta类型,我们可以把时间对象转换为当天零点到该时间的时间差,既保留时间属性,又能正常绘图:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import timedelta

# 把索引的datetime.time转成timedelta
new_df['time_delta'] = new_df.index.map(lambda t: timedelta(hours=t.hour, minutes=t.minute, seconds=t.second))

# 绘制折线图
plt.plot(new_df['time_delta'], new_df['你的数值列名'])
plt.xlabel('时段')
plt.ylabel('聚合值')

# 设置x轴主刻度为每小时一个
plt.gca().xaxis.set_major_locator(plt.MultipleLocator(timedelta(hours=1)))
# 自动旋转刻度标签避免重叠
plt.gcf().autofmt_xdate()
plt.show()

优势:timedelta支持时间运算(比如加减时长),后续数据处理仍能直接操作时间属性。

方案2:将datetime.time绑定到固定日期转为datetime类型

把每个datetime.time和任意一个固定日期组合成datetime对象,利用Matplotlib对datetime的良好支持,再通过刻度格式化只显示时间部分:

import matplotlib.pyplot as plt
import pandas as pd
from datetime import date

# 绑定当天日期生成datetime索引
base_date = date.today()
new_df['datetime'] = new_df.index.map(lambda t: pd.Timestamp.combine(base_date, t))

# 绘图
plt.plot(new_df['datetime'], new_df['你的数值列名'])
plt.xlabel('时段')
plt.ylabel('聚合值')

# 设置x轴只显示时分格式
plt.gca().xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%H:%M'))
plt.gcf().autofmt_xdate()
plt.show()

优势:视觉上完全展示时段信息,同时datetime类型支持所有时间相关的筛选、计算操作。

方案3:将datetime.time转为当日累计分钟/秒数(数值化)

把时间转换为当日的累计分钟数(或秒数)作为数值轴,再手动设置刻度标签为时间字符串,兼顾绘图兼容性和数据可操作性:

import matplotlib.pyplot as plt
import pandas as pd

# 转换为当日累计分钟数
new_df['minutes_of_day'] = new_df.index.map(lambda t: t.hour * 60 + t.minute)

# 绘图
plt.plot(new_df['minutes_of_day'], new_df['你的数值列名'])
plt.xlabel('时段')
plt.ylabel('聚合值')

# 设置x轴刻度:每小时一个,标签显示为HH:MM
tick_positions = range(0, 1440, 60)
tick_labels = [f'{h:02d}:00' for h in range(24)]
plt.xticks(tick_positions, tick_labels)
plt.gcf().autofmt_xdate()
plt.show()

优势:数值化的时间便于做区间筛选(比如筛选9:00-10:00就是minutes_of_day在540-600之间),计算效率高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:35:00