Louisa
Louisa

Reputation: 13

Changing the formatting of a datetime.time axis in matplotlib

I am trying to change the formatting of the x-axis into %H:%M, while the xticklabel all became 00:00. The xs looks like follows:

[datetime.time(15, 8, 35), datetime.time(15, 8, 36), datetime.time(15, 8, 37)]

I tried with the following script:

import matplotlib.dates as mdate
import matplotlib.pyplot as plt

dates = ['15:08:35', '15:08:36', '15:08:37']
xs = [datetime.strptime(d, '%H:%M:%S').time() for d in dates]
ys = range(len(xs))

plt.gca().xaxis.set_major_formatter(mdate.DateFormatter('%H:%M'))
plt.gca().xaxis.set_major_locator(mdate.DayLocator())

# Plot
plt.plot(xs, ys)
plt.gcf().autofmt_xdate()
plt.show()

And the image looks like this: Please click

How could I change xticklabel into my desired formatting?

Upvotes: 1

Views: 73

Answers (1)

Markus Rosenfelder
Markus Rosenfelder

Reputation: 126

Matplotlib can handle datetime-objects easier than time objects. You can remove .time(). This code should work, I edited the dates to show changing x-values on the axis.

import matplotlib.dates as mdate
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

dates = ["15:05:35", "16:08:36", "17:09:37"]
# remove .time() from strptime
xs = [datetime.strptime(d, "%H:%M:%S") for d in dates]

ys = range(len(xs))

plt.gca().xaxis.set_major_formatter(mdate.DateFormatter("%H:%M"))
plt.gca().xaxis.set_major_locator(mdate.DayLocator())

# show all x-values on the x-axis
plt.xticks(xs)
# Plot
plt.plot(xs, ys)

plt.show()

enter image description here

Upvotes: 1

Related Questions