How to show date and time on x axis in matplotlib

I would like to assign a full date plot with time for the x-axis in matplotlib, but with autoscaling I could only get times or dates, but not both. The following code:

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 the x axis, I get only times without any dates, so it’s difficult to take various measurements.

I think this is some kind of option in matplotlib in matplotlib.dates.AutoDateFormatter, but I could not find anyone that could allow me to change this autoscaling.

enter image description here

+8
source share
2 answers

You can do this with matplotlib.dates.DateFormatter , which takes strftime as an argument. To get the format day-month-year hour:minute , 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

+14
source
 plt.figure() plt.plot(...) plt.gcf().autofmt_xdate() plt.show() 
0
source

All Articles