2016-02-02 104 views
1

當我在繪製大熊貓時間序列和指數的類型時(這意味着它不包含最新信息),熊貓格式。我想要做的是將xtick標籤格式化爲只顯示小時而不顯示分鐘和秒。XTICK標籤使用時間指數

import datetime 
import random 
import pandas as pd 
from matplotlib import pylab as plt 
%matplotlib inline 

#generate a list of random datetime.times 
random_time = lambda: (datetime.datetime.strptime("00:00:00", '%H:%M:%S') + datetime.timedelta(minutes=random.randrange(1440))).time() 
times = [random_time() for x in range(20)] 

#create data frame 
df = pd.DataFrame({'times': times, 'counts': [random.randrange(10) for x in range(len(times))]}) 
df.set_index('times', inplace=True) 

df.plot() 
#I want tick labels at sensible places, only two here as illustration 
custom_tick_locs = [datetime.time(hour=8), datetime.time(hour=16)] 
plt.xticks(custom_tick_locs) 

將會產生以下情節:

enter image description here

我的問題是:我怎麼可以格式化XTICK標籤只顯示小時? (或一般任何其他格式?)

我知道,使用日期時間(包括時間)會使事情更容易。但是,由於我重疊了幾天的數據,因此我只使用時間。顯然,有可能是一個辦法做到這一點覆蓋(這樣是下午1點,在所有天同x位置),所以如果我失去了一個簡單的解決方案,用於請讓我知道。

回答

2

使用strftime計算標籤AMD把它們傳遞給plt.xticks與記號LOCS一起:

custom_tick_locs = [datetime.time(hour=8), datetime.time(hour=16)] 
custom_tick_labels = map(lambda x: x.strftime('%H'), custom_tick_locs) 
plt.xticks(custom_tick_locs, custom_tick_labels) 
+0

感謝,這正是我要找的,因爲它允許在格式化了很大的靈活性! – GebitsGerbils