How to label the x-axis only with hour:min in matplotlib (using datetime)?

38 Views Asked by At

I am trying to create a plot using time in the hour:min format on the x-axis and some values on the y-axis. The data on the x-axis is built using the datetime.datetime method. However, the figure shows the x-axis in the month-day:hour format.

I would be very grateful if someone could help me solve this problem.

Here is the python code to reproduce the problem:

import datetime
import matplotlib
import matplotlib.pyplot

x_axis_time = [datetime.datetime(2024, 1, 24, h, 0) for h in range(1,24)]
#x_axis_time = [i.time() for i in x_axis_time] #converting to HH:MM format do not work
y_axis_values = [n*50 for n in range(0,23)]

matplotlib.pyplot.plot(x_axis_time, y_axis_values)
matplotlib.pyplot.gcf().autofmt_xdate()
matplotlib.pyplot.show()
2

There are 2 best solutions below

0
RuthC On BEST ANSWER

Format the dates using the DateFormatter class. The format string is the same as for datetime's strftime and strptime.

import datetime

import matplotlib.pyplot as plt
import matplotlib.dates as mdates


x_axis_time = [datetime.datetime(2024, 1, 24, h, 0) for h in range(1,24)]
y_axis_values = [n*50 for n in range(0,23)]

fig, ax = plt.subplots()

ax.plot(x_axis_time, y_axis_values)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))

fig.autofmt_xdate()
plt.show()

enter image description here

1
Angel Luis Ortega Amador On

Just format the data to show in the axis: .strftime('%H:%M')

x_axis_time = [datetime.datetime(2024, 1, 24, h, 0).strftime('%H:%M') for h in range(1,24)]