Question

I have datapoints for every minute of a day:

import numpy as np
data = np.random.random(1440,)

# I can represent minutes as integers:

mins = np.arange(1440,dtype=np.int)

# convert to datetime

import datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])

# and plot for every 20 samples:

import matplotlib.pyplot as plt
plt.plot(times[1::20], data[1::20])

Gives me:

enter image description here

How can I change the x-axis formating to HH:MM?

I've tried useing the datetime.time() function instead of datetime.datetime() however this results in error.

Was it helpful?

Solution

You can use a custom tick formatter from the dates package to render the dates as you wish.

Extending your code example:

import numpy as np
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates

data = np.random.random(1440,)
# I can represent minutes as integers:
mins = np.arange(1440,dtype=np.int)
# convert to datetime
times=np.array([datetime.datetime(2014, 5, 13, int(p/60), p%60) for p in mins])
# and plot for every 20 samples:
plt.plot(times[1::20], data[1::20])

# generate a formatter, using the fields required
fmtr = dates.DateFormatter("%H:%M")
# need a handle to the current axes to manipulate it
ax = plt.gca()
# set this formatter to the axis
ax.xaxis.set_major_formatter(fmtr)

plt.show()

The format string is defined as per the strftime docs.

example custom date formatting

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top