Matplotlib date/time examples

Matplotlib can make many types of plots with a time axis. However, sometimes it takes an additional command or two to make the date/time axis work right in Matplotlib.

As seen in xarray_matplotlib.py, for imshow() datetime64 extent, you need to do something like:

import matplotlib.dates as mdates

...

# whatever your time vector is
t = np.arange('2010-05-04T12:05','2010-05-04T12:06', dtype='datetime64[s]').astype(datetime)

mt = mdates.date2num((t[0],t[-1])) # at least through Matplotlib 2.2

...

ax.imshow(im, extent=[mt[0],mt[1], y[0],y[-1]], aspect='auto')

As of Matplotlib 2.2, in most other Matplotlib plotting functions, numpy.datetime64 is a first-class citizen, but not yet for imshow().

Tags:

Categories:

Written by Michael Hirsch, Ph.D. //

Comments