我正在尝试使用axvline函数来绘制datetime.time值,并看到此错误。请帮助。
代码如下:
import datetime as dt
from datetime import datetime
import matplotlib.pyplot as plt
i='wpt'
x = [datetime.time(12,10), datetime.time(12, 15)]
fig, axs = plt.subplots(3, sharex = True, figsize = (12,9), constrained_layout = True)
axs[i].axvline(x[0], color = 'lightskyblue', ls = '--', lw = 1)
当我运行代码时,得到以下错误:
TypeError: '>' not supported between instances of 'float' and 'datetime.time'
我在网上查了一下,没有发现使用datetime.time
的axvline的解决方案
1条答案
按热度按时间u3r8eeie1#
matplotlib需要一个数字x坐标,而不是一个日期时间对象。您需要将时间转换为数字,例如使用matplotlib.dates.date2num函数:
这会将时间转换为一个浮点数,表示自0001年1月1日以来的天数。Matplotlib会使用它的日期绘制机制来适当地格式化坐标轴。注意,我在这里使用了datetime.合并,通过添加今天的日期将时间转换为完整的datetime对象。