1""" 2================ 3Date tick labels 4================ 5 6Show how to make date plots in Matplotlib using date tick locators and 7formatters. See :doc:`/gallery/ticks_and_spines/major_minor_demo` for more 8information on controlling major and minor ticks. 9 10Matplotlib date plotting is done by converting date instances into 11days since an epoch (by default 1970-01-01T00:00:00). The 12:mod:`matplotlib.dates` module provides the converter functions `.date2num` 13and `.num2date`, which convert `datetime.datetime` and `numpy.datetime64` 14objects to and from Matplotlib's internal representation. These data 15types are registered with with the unit conversion mechanism described in 16:mod:`matplotlib.units`, so the conversion happens automatically for the user. 17The registration process also sets the default tick ``locator`` and 18``formatter`` for the axis to be `~.matplotlib.dates.AutoDateLocator` and 19`~.matplotlib.dates.AutoDateFormatter`. These can be changed manually with 20`.Axis.set_major_locator` and `.Axis.set_major_formatter`; see for example 21:doc:`/gallery/ticks_and_spines/date_demo_convert`. 22 23An alternative formatter is the `~.matplotlib.dates.ConciseDateFormatter` 24as described at :doc:`/gallery/ticks_and_spines/date_concise_formatter`, 25which often removes the need to rotate the tick labels. 26""" 27 28import numpy as np 29import matplotlib.pyplot as plt 30import matplotlib.dates as mdates 31import matplotlib.cbook as cbook 32 33# Load a numpy structured array from yahoo csv data with fields date, open, 34# close, volume, adj_close from the mpl-data/example directory. This array 35# stores the date as an np.datetime64 with a day unit ('D') in the 'date' 36# column. 37data = cbook.get_sample_data('goog.npz', np_load=True)['price_data'] 38 39fig, ax = plt.subplots() 40ax.plot('date', 'adj_close', data=data) 41 42# Major ticks every 6 months. 43fmt_half_year = mdates.MonthLocator(interval=6) 44ax.xaxis.set_major_locator(fmt_half_year) 45 46# Minor ticks every month. 47fmt_month = mdates.MonthLocator() 48ax.xaxis.set_minor_locator(fmt_month) 49 50# Text in the x axis will be displayed in 'YYYY-mm' format. 51ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) 52 53# Round to nearest years. 54datemin = np.datetime64(data['date'][0], 'Y') 55datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') 56ax.set_xlim(datemin, datemax) 57 58# Format the coords message box, i.e. the numbers displayed as the cursor moves 59# across the axes within the interactive GUI. 60ax.format_xdata = mdates.DateFormatter('%Y-%m') 61ax.format_ydata = lambda x: f'${x:.2f}' # Format the price. 62ax.grid(True) 63 64# Rotates and right aligns the x labels, and moves the bottom of the 65# axes up to make room for them. 66fig.autofmt_xdate() 67 68plt.show() 69