2016-02-02 49 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