python - 为什么时间是00 :00 when trying to plot them using matplotlib?

标签 python matplotlib

我有一个 datetime 列表,我正在尝试绘制一个数字,其中时间在 y 轴上,日期在 x 轴上。以下是我到目前为止所得到的:

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

datetimes_str = ['2020-08-03T03:46:18.000Z', '2020-08-01T01:14:31.000Z',
                 '2020-07-27T22:45:11.000Z', '2020-07-21T20:00:42.000Z',
                 '2020-07-20T00:37:17.000Z', '2020-07-16T00:40:47.000Z']

datetimes = [dt.datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ") for d in datetimes_str]

# The above list contains datetimes:
# 2020-08-03 03:46:18
# 2020-08-01 01:14:31
# 2020-07-27 22:45:11
# 2020-07-21 20:00:42
# 2020-07-20 00:37:17
# 2020-07-16 00:40:47

fig, ax = plt.subplots()

ax.plot(datetimes, datetimes)

ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.xaxis.set_major_formatter(DateFormatter('%Y/%m/%d'))

fig.autofmt_xdate()

plt.show()

上面的代码导致-

enter image description here

如您所见,日期是正确的,但所有时间都是 00:00。有什么问题吗?!

还有一些奇怪的事情:在列表 datetimes 中,当所有日期都相等且时间不同时,一切正常!

最佳答案

这是因为 DateFormatter 从日期的序数值中删除了 float :

~/.local/bin/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in _from_ordinalf(x, tz)
    281         tz = _get_rc_timezone()
    282 
--> 283     ix, remainder = divmod(x, 1)
    284     ix = int(ix)
    285     if ix < 1:

您必须使用 ax.set_yticks 或最好使用 ax.set_yticklabels 创建自己的刻度/刻度标签

关于python - 为什么时间是00 :00 when trying to plot them using matplotlib?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63356082/

相关文章:

python - Cartopy 投影随不同数据/意外行为而变化

python - 有没有办法在 Windows 10 中安装后更改 python 最大路径长度设置?

python 瓶: how to pass parameters into function handler

python - 如何将EC2 ip地址动态添加到Django ALLOWED_HOSTS

python - 如果固定装置在 pytest 中失败,则跳过测试套件

python - 导入 matplotlib 和 matplotlib.pyplot 有什么区别?

python - 使用 Python(PyQt、PyGTK、wxPython、IronPython 等)创建 GUI 的最佳库

python - 绘制连接两个 swarmplots 的各个数据点的彩色线

Python - 带子图的 blit 仅绘制最后一个子图

python - 如何检测是否为matplotlib轴生成了双轴