Issue
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()
Solution
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()
Answered By - RuthC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.