我想绘制一个datetime64系列的时间,其中Y轴格式为'%H:%M,只显示00:00,01:00,02:00等。如何在matplotlib中以'%H:%M'格式绘制y轴上的时间?
这个是没有自定义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()
的话题读周围做之后,我尝试以下,但没有成功。
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()
有人能告诉我吗?
导入熊猫隐式安装转换器以正确处理datetime64(通过将它们通过熊猫dt64盒装数据类型进行洗涤)。 – tacaswell
感谢@tcaswell,但在上面的示例中导入了pandas(0.17.0)。有什么建议,为什么它没有工作? – themachinist
@tcaswell不知道你的意思,我不得不添加'.tolist()'调用来使'HourLocator'工作。我注意到,绘制'.df.time' matplotlib时使用了熊猫的东西来做刻度和标签,但是我没有找到一种简单的方法来定制它们以满足需求。 – Goyo