python-如何在m​​atplotlib中以’%H:%M’格式在y轴上绘制时间?

我想从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()

enter image description here

阅读有关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()

谁能告诉我?

解决方法:

为此,您需要传递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'))

enter image description here

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...