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

使用axvline绘制datetime.time值触发TypeError,请求技术支持

解决matplotlib axvline绘制datetime.time类型数值的报错问题

错误原因

axvline的x参数需要坐标轴对应的数值类型(如float),直接传入datetime.time对象时,matplotlib无法自动完成类型转换,导致内部出现float与datetime.time的比较操作,触发TypeError。

解决方案

根据你的x轴数据格式,选择以下两种方法之一:

方法1:将datetime.time转换为小时数/秒数(适用于纯时间轴)

如果x轴是纯时间(无日期),可以把datetime.time转换为一天中的小时数(或总秒数),与x轴数值匹配:

import matplotlib.pyplot as plt
from datetime import time

# 示例x轴时间数据
x_times = [time(9, 0), time(10, 0), time(11, 0), time(12, 0), time(13, 0)]
y_data = [1, 3, 2, 4, 3]

# 将time对象转换为小时数(便于matplotlib识别)
x_numeric = [t.hour + t.minute/60 + t.second/3600 for t in x_times]

plt.plot(x_numeric, y_data)

# 处理要绘制的竖线时间
time_ret = time(11, 15)
vline_x = time_ret.hour + time_ret.minute/60 + time_ret.second/3600
plt.axvline(x=vline_x, color='red', linestyle='--')

# 将x轴刻度还原为时间格式显示
plt.xticks(x_numeric, [t.strftime('%H:%M') for t in x_times])
plt.show()

方法2:将datetime.time包装为datetime.datetime(适用于带日期的时间轴)

如果x轴是完整的datetime.datetime类型,把time对象结合一个固定日期转为datetime,再用matplotlib.dates.date2num转换为数值:

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

# 示例x轴日期时间数据
x_dates = [datetime(2024, 5, 20, 9, 0), datetime(2024, 5, 20, 10, 0),
           datetime(2024, 5, 20, 11, 0), datetime(2024, 5, 20, 12, 0)]
y_data = [1, 3, 2, 4]

plt.plot(x_dates, y_data)

# 把time转为datetime对象,再转换为matplotlib可识别的数值
time_ret = time(11, 15)
dt_ret = datetime(2024, 5, 20, time_ret.hour, time_ret.minute)
vline_x = mdates.date2num(dt_ret)
plt.axvline(x=vline_x, color='red', linestyle='--')

# 设置x轴显示时间格式
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:25:58