问题描述
我有一个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()
上面的代码导致-
您看到日期是正确的,但所有时间均为00:00
。怎么了?!
还有一个奇怪的事情:在列表datetimes
中,当所有日期都相等且时间不同时,一切正常!
解决方法
这是因为DateFormatter
从日期的序数值中删除了浮点数:
~/.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
创建自己的刻度/刻度标签
您可以在列表理解中划分时间:
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]
times = sorted([d[11:16] for d in datetimes_str])
fig,ax = plt.subplots()
ax.plot(datetimes,times)
ax.xaxis.set_major_formatter(DateFormatter('%Y/%m/%d'))
fig.autofmt_xdate()
plt.show()
制作:
,之所以会发生这种情况,是因为x和y轴唯一不同的是表示dateTime的格式,而不是dateTime本身的值,这就是为什么您总是会得到一条对角线的原因。
由于y轴的值变化太大以致无法精确表示小时,因此仅显示了00:00。
要更改此设置,您需要通过删除日期信息并仅保留时间来更改y轴的值。这是应该可以解决问题的代码段:
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter,DayLocator,HourLocator
datetimes_str = ['2020-08-03T03:46:18.000Z',"%Y-%m-%dT%H:%M:%S.%fZ") for d in datetimes_str]
times = [d.replace(day=1,month=1,year=2000) for d in datetimes]
# 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.yaxis.set_major_formatter(DateFormatter('%H:%M'))
ax.xaxis.set_major_formatter(DateFormatter('%Y/%m/%d'))
ax.plot(datetimes,times)
fig.autofmt_xdate()
plt.show()