2016-02-26 161 views
1

我想绘制一个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() 

enter image description here

的话题读周围做之后,我尝试以下,但没有成功。

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

对于工作,你需要传递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

+0

导入熊猫隐式安装转换器以正确处理datetime64(通过将它们通过熊猫dt64盒装数据类型进行洗涤)。 – tacaswell

+0

感谢@tcaswell,但在上面的示例中导入了pandas(0.17.0)。有什么建议,为什么它没有工作? – themachinist

+0

@tcaswell不知道你的意思,我不得不添加'.tolist()'调用来使'HourLocator'工作。我注意到,绘制'.df.time' matplotlib时使用了熊猫的东西来做刻度和标签,但是我没有找到一种简单的方法来定制它们以满足需求。 – Goyo

0

您可以尝试两件事情: 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')) 
+1

感谢,但这些线不出现工作。另外,当时间在Y轴上,为什么它应该是ax.axis? – themachinist

相关问题