|
3 | 3 | Date tick labels |
4 | 4 | ================ |
5 | 5 |
|
6 | | -Show how to make date plots in Matplotlib using date tick locators and |
7 | | -formatters. See :doc:`/gallery/ticks_and_spines/major_minor_demo` for more |
8 | | -information on controlling major and minor ticks. |
9 | | -
|
10 | 6 | Matplotlib date plotting is done by converting date instances into |
11 | 7 | days since an epoch (by default 1970-01-01T00:00:00). The |
12 | 8 | :mod:`matplotlib.dates` module provides the converter functions `.date2num` |
13 | | -and `.num2date`, which convert `datetime.datetime` and `numpy.datetime64` |
| 9 | +and `.num2date` that convert `datetime.datetime` and `numpy.datetime64` |
14 | 10 | objects to and from Matplotlib's internal representation. These data |
15 | | -types are registered with with the unit conversion mechanism described in |
| 11 | +types are registered with the unit conversion mechanism described in |
16 | 12 | :mod:`matplotlib.units`, so the conversion happens automatically for the user. |
17 | 13 | The registration process also sets the default tick ``locator`` and |
18 | 14 | ``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`. |
| 15 | +`~.matplotlib.dates.AutoDateFormatter`. |
22 | 16 |
|
23 | | -An alternative formatter is the `~.matplotlib.dates.ConciseDateFormatter` |
24 | | -as described at :doc:`/gallery/ticks_and_spines/date_concise_formatter`, |
25 | | -which often removes the need to rotate the tick labels. |
| 17 | +An alternative formatter is the `~.dates.ConciseDateFormatter`, |
| 18 | +used in the second ``Axes`` below (see |
| 19 | +:doc:`/gallery/ticks_and_spines/date_concise_formatter`), which often |
| 20 | +removes the need to rotate the tick labels. The last ``Axes`` |
| 21 | +formats the dates manually, using `~.dates.DateFormatter` to |
| 22 | +format the dates using the format strings documented at |
| 23 | +`datetime.date.strftime`. |
26 | 24 | """ |
27 | 25 |
|
28 | | -import numpy as np |
29 | 26 | import matplotlib.pyplot as plt |
30 | 27 | import matplotlib.dates as mdates |
31 | 28 | import matplotlib.cbook as cbook |
|
36 | 33 | # column. |
37 | 34 | data = cbook.get_sample_data('goog.npz', np_load=True)['price_data'] |
38 | 35 |
|
39 | | -fig, ax = plt.subplots() |
40 | | -ax.plot('date', 'adj_close', data=data) |
| 36 | +fig, axs = plt.subplots(3, 1, figsize=(6.4, 7), constrained_layout=True) |
| 37 | +# common to all three: |
| 38 | +for ax in axs: |
| 39 | + ax.plot('date', 'adj_close', data=data) |
| 40 | + # Major ticks every half year, minor ticks every month, |
| 41 | + ax.xaxis.set_major_locator(mdates.MonthLocator(bymonth=(1, 7))) |
| 42 | + ax.xaxis.set_minor_locator(mdates.MonthLocator()) |
| 43 | + ax.grid(True) |
| 44 | + ax.set_ylabel(r'Price [\$]') |
41 | 45 |
|
42 | | -# Major ticks every 6 months. |
43 | | -fmt_half_year = mdates.MonthLocator(interval=6) |
44 | | -ax.xaxis.set_major_locator(fmt_half_year) |
| 46 | +# different formats: |
| 47 | +ax = axs[0] |
| 48 | +ax.set_title('DefaultFormatter', loc='left', y=0.85, x=0.02, fontsize='medium') |
45 | 49 |
|
46 | | -# Minor ticks every month. |
47 | | -fmt_month = mdates.MonthLocator() |
48 | | -ax.xaxis.set_minor_locator(fmt_month) |
| 50 | +ax = axs[1] |
| 51 | +ax.set_title('ConciseFormatter', loc='left', y=0.85, x=0.02, fontsize='medium') |
| 52 | +ax.xaxis.set_major_formatter( |
| 53 | + mdates.ConciseDateFormatter(ax.xaxis.get_major_locator())) |
49 | 54 |
|
| 55 | +ax = axs[2] |
| 56 | +ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02, |
| 57 | + fontsize='medium') |
50 | 58 | # Text in the x axis will be displayed in 'YYYY-mm' format. |
51 | | -ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) |
52 | | - |
53 | | -# Round to nearest years. |
54 | | -datemin = np.datetime64(data['date'][0], 'Y') |
55 | | -datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') |
56 | | -ax.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. |
60 | | -ax.format_xdata = mdates.DateFormatter('%Y-%m') |
61 | | -ax.format_ydata = lambda x: f'${x:.2f}' # Format the price. |
62 | | -ax.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. |
66 | | -fig.autofmt_xdate() |
| 59 | +ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b')) |
| 60 | +# Rotates and right-aligns the x labels so they don't crowd each other. |
| 61 | +for label in ax.get_xticklabels(which='major'): |
| 62 | + label.set(rotation=30, horizontalalignment='right') |
67 | 63 |
|
68 | 64 | plt.show() |
0 commit comments