如何在 matplotlib 中以 '%H:%M' 格式在 y 轴上绘制时间?

how to plot time on y-axis in '%H:%M' format in matplotlib?

我想绘制 datetime64 系列的时间,其中 y 轴的格式为 '%H:%M,仅显示 00:00、01:00、02:00, 等等

这是在未自定义 y 轴格式的情况下绘图的样子。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
from matplotlib.dates import HourLocator

df = pd.DataFrame(data=dict(a=pd.date_range('1/1/2011',periods=1440000,freq='1min')))
df = df.iloc[np.arange(0,1440*100,1440)+np.random.randint(1,300,100)]

plt.plot(df.index,df['a'].dt.time)
plt.show()

在阅读有关 SO 的主题后,我尝试了以下但没有成功。

ax = plt.subplot()
ax.yaxis.set_major_locator(HourLocator())
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))
plt.plot(df.index,df['a'].dt.time)
plt.show()

ValueError: DateFormatter found a value of x=0, which is an illegal date.  This usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

谁能告诉我吗?

您可以尝试两件事: 1) 应该是 ax.xaxis..... 而不是 ax.yaxis.. 2) 使用 set_major_locator() 而不是 set_major_formatter() 作为定位器。示例如下所示。

min = 15
ax.xaxis.set_major_locator(MinuteLocator(byminute=range(0,60,min)) )
ax.xaxis.set_major_formatter( DateFormatter('%H:%M') )

为此,您需要传递 datetime 个对象(我的意思是 datetime,而不是 datetime64)。您可以将所有时间戳转换为相同的日期,然后使用 .tolist() 获取实际的 datetime 对象。

y = df['a'].apply(lambda x: x.replace(year=1967, month=6, day=25)).tolist()
ax = plt.subplot()
ax.plot(df.index, y)
ax.yaxis.set_major_locator(HourLocator())
ax.yaxis.set_major_formatter(DateFormatter('%H:%M'))