How to show date and time on x axis
Asked Answered
I

3

18

I would like to assign for x axis in matplotlib plot full date with time but with autoscale I could get only times or dates but not both.

import matplotlib.pyplot as plt
import pandas as pd

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))
plt.show()

And on x axis I get only times without any dates so it's hard to distinct measurements.

I think that it's some option in matplotlib in matplotlib.dates.AutoDateFormatter but I couldn't find any one that could allow me to change that autoscale.

enter image description here

Invalid answered 6/10, 2015 at 14:20 Comment(0)
B
34

You can do this with a matplotlib.dates.DateFormatter, which takes a strftime format string as its argument. To get a day-month-year hour:minute format, you can use %d-%m-%y %H:%M:

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

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))

xfmt = mdates.DateFormatter('%d-%m-%y %H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

enter image description here

Bloodstream answered 6/10, 2015 at 15:0 Comment(3)
If you define two y-axis for your plot, you may need to call xaxis.set_major_formatter(xfmt) on the other axis object.Camphorate
how can we increase the number of dates (the frequency of showing the dates) on the x-axis?Ectoblast
@Ectoblast you would want to change the Locator. For example, in this case we could use ax.xaxis.set_major_locator(mdates.HourLocator(interval=6)) to have a tick every 6 hours. See the docs here for a list of different available locators.Bloodstream
T
1
plt.figure() 
plt.plot(...)
plt.gcf().autofmt_xdate() plt.show()
Thunderstone answered 9/7, 2019 at 4:43 Comment(1)
Adding context to a code answer is considered useful.Towline
F
0

This is how to plot date and time column when it is not your index column.
fig, ax = plt.subplots() ax.plot('docdate', 'count', data=newdf) fig.autofmt_xdate() plt.show()

Flavio answered 8/2, 2021 at 14:25 Comment(2)
adding a verbal explanation is often helpfulGallstone
This is just a very simplified version of accepted answer with no real addition.Enlighten

© 2022 - 2024 — McMap. All rights reserved.