0

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 Answers 2

2

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)]
Sign up to request clarification or add additional context in comments.

1 Comment

It works. The disadvantage now is that it populates the x-axis with every single time-data. But it will be another question. Thanks a lot.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.