You are reading an old version of the documentation (v2.2.5). For the latest version see
Version 2.2.5
Fork me on GitHub

Related Topics

Date tick labelsΒΆ

Show how to make date plots in matplotlib using date tick locators and formatters. See for more information on controlling major and minor ticks

All matplotlib date plotting is done by converting date instances into days since 0001-01-01 00:00:00 UTC plus one day (for historical reasons). The conversion, tick locating and formatting is done behind the scenes so this is most transparent to you. The dates module provides several converter functions matplotlib.dates.date2num and matplotlib.dates.num2date. These can convert between datetime.datetime objects and numpy.datetime64 objects.

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook

years = mdates.YearLocator()   # every year
months = mdates.MonthLocator()  # every month
yearsFmt = mdates.DateFormatter('%Y')

# Load a numpy record array from yahoo csv data with fields date, open, close,
# volume, adj_close from the mpl-data/example directory. The record array
# stores the date as an np.datetime64 with a day unit ('D') in the date column.
with cbook.get_sample_data('goog.npz') as datafile:
    r = np.load(datafile)['price_data'].view(np.recarray)

fig, ax = plt.subplots()
ax.plot(, r.adj_close)

# format the ticks

# round to nearest years...
datemin = np.datetime64([0], 'Y')
datemax = np.datetime64([-1], 'Y') + np.timedelta64(1, 'Y')
ax.set_xlim(datemin, datemax)

# format the coords message box
def price(x):
    return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price

# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery