2015-11-08 56 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

相關問題