2015-11-08 54 views
2

我想绘制时间序列数据,从第二天的晚上9点到下午6点开始。这是我失败的尝试。如何绘制时间序列,其中x轴是matplotlib中的datetime.time对象?

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
from datetime import time  

a=np.array([35,25,24,25,27,28,30,35]) 
df=pd.DataFrame(index=pd.date_range("00:00", "23:00", freq="3H").time,data={'column1':a}) 

      column1 
00:00:00  35 
03:00:00  25 
06:00:00  24 
09:00:00  25 
12:00:00  27 
15:00:00  28 
18:00:00  30 
21:00:00  35 

重新索引数据从21:00到18:00。也许有更好的方法来实现这一部分,但这是有效的。

df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]])) 

      column1 
21:00:00  35 
00:00:00  35 
03:00:00  25 
06:00:00  24 
09:00:00  25 
12:00:00  27 
15:00:00  28 
18:00:00  30 

plt.plot(df.index,df['column1']) 

x轴似乎不符合df.index。轴也从00:00开始,而不是21:00。有没有人知道一个解决方案,不涉及使用字符串标签的X轴?

回答

0

一个简单的办法做到这一点是画出数据而不expliciting x轴和改变标签。问题是,只有数据之间的时间不变,这才会起作用。我知道你说过你不想使用字符串标签,所以我不知道这个解决方案会是你想要的。

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
from datetime import time  

a=np.array([35,25,24,25,27,28,30,35]) 

df=pd.DataFrame(index=pd.date_range("00:00", "23:00",freq="3H").time,data={'column1':a}) 

df=df.reindex(np.concatenate([df.loc[time(21,00):].index,df.loc[:time(21,00)].index[:-1]])) 

# Now we create the figure and the axes 
fig,axes=plt.subplots() 
axes.plot(df['column1']) # In the x axis will appear 0,1,2,3... 
axes.set_xticklabels(df.index) # now we change the labels of the xaxis 

plt.show() 

这应该做的伎俩,并会绘制你想要的。

example of result

相关问题