如何使用 datetime.time 绘图

mau*_*hta 5 python matplotlib

我有 HH:MM:SS 格式的时间戳列表,并希望使用 datetime.time 绘制某些值。看来 python 不喜欢我这样做的方式。有人可以帮忙吗?

import datetime
import matplotlib.pyplot as plt

# random data
x = [datetime.time(12,10,10), datetime.time(12, 11, 10)]
y = [1,5]

# plot
plt.plot(x,y)
plt.show()

*TypeError: float() argument must be a string or a number*
Run Code Online (Sandbox Code Playgroud)

use*_*197 2

嗯,一个两步故事,让情节变得非常好

在此输入图像描述

步骤 1:将数据准备成正确的格式

从 adatetime到 与日期/时间matplotlib兼容的约定float


和往常一样,魔鬼隐藏在细节之中。

matplotlib日期几乎相等,但相等:

#  mPlotDATEs.date2num.__doc__
#                  
#     *d* is either a class `datetime` instance or a sequence of datetimes.
#
#     Return value is a floating point number (or sequence of floats)
#     which gives the number of days (fraction part represents hours,
#     minutes, seconds) since 0001-01-01 00:00:00 UTC, *plus* *one*.
#     The addition of one here is a historical artifact.  Also, note
#     that the Gregorian calendar is assumed; this is not universal
#     practice.  For details, see the module docstring.
Run Code Online (Sandbox Code Playgroud)

因此,强烈建议重新使用他们的“自己的”工具:

from matplotlib import dates as mPlotDATEs   # helper functions num2date()
#                                            #              and date2num()
#                                            #              to convert to/from.
Run Code Online (Sandbox Code Playgroud)

第 2 步:管理轴标签、格式和比例(最小/最大)作为下一期

matplotlib这部分也给你带来了武器。

检查此答案中的代码以获取所有详细信息