29

I am trying to plot some data against a list of datetime objects in the x axis with pyplot. However the dates appear as the standard format, which is %Y-%m-%d %H:%M:%S (way too long). I can circumvent this by creating a list of date strings with strftime and use that instead. I also know that there is some kind of date object intrinsic for pyplot which I could use instead of datetime.

Is there a way to tell pyplot in which format to plot the datetimeobjects however? Without having to transform everything to string or another kind of object?

Thank you.

2 Answers 2

38

You can use DateFormatter:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(your_dates, your_data)

# format your data to desired format. Here I chose YYYY-MM-DD but you can set it to whatever you want.
import matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate and align the tick labels so they look better
fig.autofmt_xdate()
Sign up to request clarification or add additional context in comments.

Comments

20

Apart from manually specifying the datetime format for the axes as shown in the other answer, you may use rcParams to set the format.

The standard is

# date.autoformatter.year     : %Y
# date.autoformatter.month    : %Y-%m
# date.autoformatter.day      : %Y-%m-%d
# date.autoformatter.hour     : %m-%d %H
# date.autoformatter.minute   : %d %H:%M
# date.autoformatter.second   : %H:%M:%S
# date.autoformatter.microsecond   : %M:%S.%f

You may change that in the matplotlib rc file,
or inside the code via

plt.rcParams["date.autoformatter.minute"] = "%Y-%m-%d %H:%M:%S"

4 Comments

Unlike the downvote might suggest, this method is working nicely and even saves some typing compared to other options.
I agree, this is totally sufficient to solve the issue.
What is the library used for date.autoformatter?
The other answer didn't work for me, this is the only one that has worked.

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.