Reputation: 124
I have the script below, I m trying to change my plot to show hours instead of month and year on the bottom.
import datetime
import matplotlib.pyplot as plt
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(10)]
y = ['54.2', '54.8', '54.2', '54.8', '55.3', '55.3', '55.3', '55.3', '54.8', '54.8']
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
print(x)
print(y)
plt.show()
Upvotes: 1
Views: 1033
Reputation: 1531
You can try setting set_major_formatter
format:
By changing x axis format directly. But, matplotlib will show only time in hh:00:00 format by default.
import datetime
import matplotlib.pyplot as plt
from matplotlib import dates
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(10)]
fig, ax = plt.subplots()
y = ['54.2', '54.8', '54.2', '54.8', '55.3', '55.3', '55.3', '55.3', '54.8', '54.8']
# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
## create x-axis hour format
ax.xaxis.set_major_formatter(dates.DateFormatter("%H:%M"))
plt.show()
You can change x axis label value directly using set_xticklabels
method. Just add the below code
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()
## create x-axis hour format
ax.xaxis.set_major_formatter(dates.DateFormatter("%H:%M"))
x_hours = [date_str.strftime("%H:%M:%S") for date_str in x]
ax.set_xticklabels(x_hours)
plt.show
Upvotes: 1