使用时间索引时 pandas 中的 xtick 标签格式

Geb*_*ils 5 python matplotlib pandas

我正在 pandas 中绘制时间序列,索引的类型为时间(意味着它不包含日期信息)。我想要做的是将 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)
Run Code Online (Sandbox Code Playgroud)

产生以下情节:

在此输入图像描述

我的问题是:如何格式化 xtick 标签以仅显示小时?(或者一般的任何其他格式?)

我知道使用日期时间(包括两者和时间)会让事情变得容易得多。但是,由于我要叠加几天的数据,因此我只使用时间。显然,可能有一种方法可以实现这种叠加(这样下午 1 点全天都处于相同的 x 位置),因此如果我缺少一个简单的解决方案,请告诉我。

Sto*_*ica 5

用于strftime计算标签并将它们plt.xticks与刻度位置一起传递:

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)
Run Code Online (Sandbox Code Playgroud)


Joo*_*eey 5

您可以使用Matplotlib date API自动完成所有这些操作:

from matplotlib.dates import HourLocator, DateFormatter

ax = df.plot() # don't throw away the Axes object
ax.xaxis.set_major_locator(HourLocator(interval=2)) # tick every two hours
ax.xaxis.set_major_formatter(DateFormatter('%H'))
Run Code Online (Sandbox Code Playgroud)

接受DateFormatter任何strftime字符串。使用格式化程序和定位器的优点是您不必手动处理轴限制。matplotlib.dates日期和时间以及matplotlib.ticker一般数字有许多不同的定位器和格式化程序。