8000 DOC: more improve date example · matplotlib/matplotlib@865b09d · GitHub
[go: up one dir, main page]

Skip to content

Commit 865b09d

Browse files
jklymaktimhoffmQuLogic
committed
DOC: more improve date example
Co-authored-by: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Co-authored-by: Elliott Sales de Andrade <quantum.analyst@gmail.com>
1 parent 9bfd631 commit 865b09d

File tree

1 file changed

+33
-37
lines changed
  • examples/text_labels_and_annotations

1 file changed

+33
-37
lines changed

examples/text_labels_and_annotations/date.py

Lines changed: 33 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,26 @@
33
Date tick labels
44
================
55
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-
106
Matplotlib date plotting is done by converting date instances into
117
days since an epoch (by default 1970-01-01T00:00:00). The
128
: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`
1410
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
1612
:mod:`matplotlib.units`, so the conversion happens automatically for the user.
1713
The registration process also sets the default tick ``locator`` and
1814
``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`.
2216
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`.
2624
"""
2725

28-
import numpy as np
2926
import matplotlib.pyplot as plt
3027
import matplotlib.dates as mdates
3128
import matplotlib.cbook as cbook
@@ -36,33 +33,32 @@
3633
# column.
3734
data = cbook.get_sample_data('goog.npz', np_load=True)['price_data']
3835

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 [\$]')
4145

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')
4549

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()))
4954

55+
ax = axs[2]
56+
ax.set_title('Manual DateFormatter', loc='left', y=0.85, x=0.02,
57+
fontsize='medium')
5058
# 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')
6763

6864
plt.show()

0 commit comments

Comments
 (0)
0