Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xtick label formatting in pandas when using time index

I am plotting a time series in pandas and the index is of type time (meaning it does not contain the date information). What I want to do is format the xtick labels to only show the hour and not minutes and seconds.

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)

Which produces the following plot:

enter image description here

My question is: how can I format the xtick labels to only show the hour? (Or any other format in general?)

I know that using datetime (including both and time) would make things a lot easier. However, since I'm overlaying data from several days I am using only the time. Obviously there might be a way to do that overlaying (so that 1pm is at the same x-position for all days) so if I'm missing an easy solution for that please let me know.

like image 888
GebitsGerbils Avatar asked Feb 08 '23 20:02

GebitsGerbils


2 Answers

Use strftime to compute the labels amd pass them to plt.xticks along with the tick 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)
like image 173
Stop harming Monica Avatar answered Feb 13 '23 03:02

Stop harming Monica


You can do all this automatically with the 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'))

The DateFormatter accepts any strftime string. The advantage of using the formatters and locators is that you don't have to manually deal with the Axes limits. There's lots of different locators and formatters in matplotlib.dates for date and time and in matplotlib.ticker for numbers in general.

like image 35
Joooeey Avatar answered Feb 13 '23 03:02

Joooeey