Python图表轴格式不适用于子图

时间:2017-11-09 22:12:29

标签: python pandas matplotlib time formatter

我有一个pandas数据帧,索引为datetime.time个从DatetimeIndex派生的对象,

In: df.index
Out: 
Index([00:00:00, 00:30:00, 01:00:00, 01:30:00, 02:00:00, 02:30:00, 03:00:00,
       03:30:00, 04:00:00, 04:30:00, 05:00:00, 05:30:00, 06:00:00, 06:30:00,
       07:00:00, 07:30:00, 08:00:00, 08:30:00, 09:00:00, 09:30:00, 10:00:00,
       10:30:00, 11:00:00, 11:30:00, 12:00:00, 12:30:00, 13:00:00, 13:30:00,
       14:00:00, 14:30:00, 15:00:00, 15:30:00, 16:00:00, 16:30:00, 17:00:00,
       17:30:00, 18:00:00, 18:30:00, 19:00:00, 19:30:00, 20:00:00, 20:30:00,
       21:00:00, 21:30:00, 22:00:00, 22:30:00, 23:00:00, 23:30:00],
      dtype='object')

我正在绘制df中的图表:

import matplotlib.pyplot as plt
fig,ax = plt.subplot
ax.plot(df.index, df,  marker='', linestyle='solid',linewidth=1, alpha=1)

我希望将x轴格式化为每4小时刻度一次。

使用matplotlib.dates

import matplotlib.dates as md
ax.xaxis.set_major_locator(md.HourLocator(interval=4))
ax.xaxis.set_major_formatter(md.DateFormatter('%H'))

没有效果,因为索引不是DatetimeIndex,那么我用什么来格式化轴?

1 个答案:

答案 0 :(得分:0)

正如@ImportanceofBeingErnest所建议的那样,答案是将索引中的datetime.time个对象更改回'datetime'对象以恢复DatetimeIndex

import datetime as dt   
random_date = dt.date(1901, 1, 1)
df.index = pd.DatetimeIndex([dt.datetime.combine(random_date, t) for t in df.index])