
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "gallery/ticks/date_concise_formatter.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. meta::
        :keywords: codex

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_gallery_ticks_date_concise_formatter.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_ticks_date_concise_formatter.py:


.. _date_concise_formatter:

============================================
Format date ticks using ConciseDateFormatter
============================================

Finding good tick values and formatting the ticks for an axis that
has date data is often a challenge.  `~.dates.ConciseDateFormatter` is
meant to improve the strings chosen for the ticklabels, and to minimize
the strings used in those tick labels as much as possible.

.. note::

    This formatter is a candidate to become the default date tick formatter
    in future versions of Matplotlib.  Please report any issues or
    suggestions for improvement to the GitHub repository or mailing list.

.. GENERATED FROM PYTHON SOURCE LINES 20-27

.. code-block:: Python

    import datetime

    import matplotlib.pyplot as plt
    import numpy as np

    import matplotlib.dates as mdates








.. GENERATED FROM PYTHON SOURCE LINES 28-29

First, the default formatter.

.. GENERATED FROM PYTHON SOURCE LINES 29-50

.. code-block:: Python


    base = datetime.datetime(2005, 2, 1)
    dates = [base + datetime.timedelta(hours=(2 * i)) for i in range(732)]
    N = len(dates)
    np.random.seed(19680801)
    y = np.cumsum(np.random.randn(N))

    fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
    lims = [(np.datetime64('2005-02'), np.datetime64('2005-04')),
            (np.datetime64('2005-02-03'), np.datetime64('2005-02-15')),
            (np.datetime64('2005-02-03 11:00'), np.datetime64('2005-02-04 13:20'))]
    for nn, ax in enumerate(axs):
        ax.plot(dates, y)
        ax.set_xlim(lims[nn])
        # rotate_labels...
        for label in ax.get_xticklabels():
            label.set_rotation(40)
            label.set_horizontalalignment('right')
    axs[0].set_title('Default Date Formatter')
    plt.show()




.. image-sg:: /gallery/ticks/images/sphx_glr_date_concise_formatter_001.png
   :alt: Default Date Formatter
   :srcset: /gallery/ticks/images/sphx_glr_date_concise_formatter_001.png, /gallery/ticks/images/sphx_glr_date_concise_formatter_001_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 51-55

The default date formatter is quite verbose, so we have the option of
using `~.dates.ConciseDateFormatter`, as shown below.  Note that
for this example the labels do not need to be rotated as they do for the
default formatter because the labels are as small as possible.

.. GENERATED FROM PYTHON SOURCE LINES 55-69

.. code-block:: Python


    fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
    for nn, ax in enumerate(axs):
        locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
        formatter = mdates.ConciseDateFormatter(locator)
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)

        ax.plot(dates, y)
        ax.set_xlim(lims[nn])
    axs[0].set_title('Concise Date Formatter')

    plt.show()




.. image-sg:: /gallery/ticks/images/sphx_glr_date_concise_formatter_002.png
   :alt: Concise Date Formatter
   :srcset: /gallery/ticks/images/sphx_glr_date_concise_formatter_002.png, /gallery/ticks/images/sphx_glr_date_concise_formatter_002_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 70-73

If all calls to axes that have dates are to be made using this converter,
it is probably most convenient to use the units registry where you do
imports:

.. GENERATED FROM PYTHON SOURCE LINES 73-89

.. code-block:: Python


    import matplotlib.units as munits

    converter = mdates.ConciseDateConverter()
    munits.registry[np.datetime64] = converter
    munits.registry[datetime.date] = converter
    munits.registry[datetime.datetime] = converter

    fig, axs = plt.subplots(3, 1, figsize=(6, 6), layout='constrained')
    for nn, ax in enumerate(axs):
        ax.plot(dates, y)
        ax.set_xlim(lims[nn])
    axs[0].set_title('Concise Date Formatter')

    plt.show()




.. image-sg:: /gallery/ticks/images/sphx_glr_date_concise_formatter_003.png
   :alt: Concise Date Formatter
   :srcset: /gallery/ticks/images/sphx_glr_date_concise_formatter_003.png, /gallery/ticks/images/sphx_glr_date_concise_formatter_003_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 90-113

Localization of date formats
============================

Dates formats can be localized if the default formats are not desirable by
manipulating one of three lists of strings.

The ``formatter.formats`` list of formats is for the normal tick labels,
There are six levels: years, months, days, hours, minutes, seconds.
The ``formatter.offset_formats`` is how the "offset" string on the right
of the axis is formatted.  This is usually much more verbose than the tick
labels. Finally, the ``formatter.zero_formats`` are the formats of the
ticks that are "zeros".  These are tick values that are either the first of
the year, month, or day of month, or the zeroth hour, minute, or second.
These are usually the same as the format of
the ticks a level above.  For example if the axis limits mean the ticks are
mostly days, then we label 1 Mar 2005 simply with a "Mar".  If the axis
limits are mostly hours, we label Feb 4 00:00 as simply "Feb-4".

Note that these format lists can also be passed to `.ConciseDateFormatter`
as optional keyword arguments.

Here we modify the labels to be "day month year", instead of the ISO
"year month day":

.. GENERATED FROM PYTHON SOURCE LINES 113-146

.. code-block:: Python


    fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))

    for nn, ax in enumerate(axs):
        locator = mdates.AutoDateLocator()
        formatter = mdates.ConciseDateFormatter(locator)
        formatter.formats = ['%y',  # ticks are mostly years
                             '%b',       # ticks are mostly months
                             '%d',       # ticks are mostly days
                             '%H:%M',    # hrs
                             '%H:%M',    # min
                             '%S.%f', ]  # secs
        # these are mostly just the level above...
        formatter.zero_formats = [''] + formatter.formats[:-1]
        # ...except for ticks that are mostly hours, then it is nice to have
        # month-day:
        formatter.zero_formats[3] = '%d-%b'

        formatter.offset_formats = ['',
                                    '%Y',
                                    '%b %Y',
                                    '%d %b %Y',
                                    '%d %b %Y',
                                    '%d %b %Y %H:%M', ]
        ax.xaxis.set_major_locator(locator)
        ax.xaxis.set_major_formatter(formatter)

        ax.plot(dates, y)
        ax.set_xlim(lims[nn])
    axs[0].set_title('Concise Date Formatter')

    plt.show()




.. image-sg:: /gallery/ticks/images/sphx_glr_date_concise_formatter_004.png
   :alt: Concise Date Formatter
   :srcset: /gallery/ticks/images/sphx_glr_date_concise_formatter_004.png, /gallery/ticks/images/sphx_glr_date_concise_formatter_004_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 147-153

Registering a converter with localization
=========================================

`.ConciseDateFormatter` doesn't have rcParams entries, but localization can
be accomplished by passing keyword arguments to `.ConciseDateConverter` and
registering the datatypes you will use with the units registry:

.. GENERATED FROM PYTHON SOURCE LINES 153-187

.. code-block:: Python


    import datetime

    formats = ['%y',          # ticks are mostly years
               '%b',     # ticks are mostly months
               '%d',     # ticks are mostly days
               '%H:%M',  # hrs
               '%H:%M',  # min
               '%S.%f', ]  # secs
    # these can be the same, except offset by one level....
    zero_formats = [''] + formats[:-1]
    # ...except for ticks that are mostly hours, then it's nice to have month-day
    zero_formats[3] = '%d-%b'
    offset_formats = ['',
                      '%Y',
                      '%b %Y',
                      '%d %b %Y',
                      '%d %b %Y',
                      '%d %b %Y %H:%M', ]

    converter = mdates.ConciseDateConverter(
        formats=formats, zero_formats=zero_formats, offset_formats=offset_formats)

    munits.registry[np.datetime64] = converter
    munits.registry[datetime.date] = converter
    munits.registry[datetime.datetime] = converter

    fig, axs = plt.subplots(3, 1, layout='constrained', figsize=(6, 6))
    for nn, ax in enumerate(axs):
        ax.plot(dates, y)
        ax.set_xlim(lims[nn])
    axs[0].set_title('Concise Date Formatter registered non-default')

    plt.show()



.. image-sg:: /gallery/ticks/images/sphx_glr_date_concise_formatter_005.png
   :alt: Concise Date Formatter registered non-default
   :srcset: /gallery/ticks/images/sphx_glr_date_concise_formatter_005.png, /gallery/ticks/images/sphx_glr_date_concise_formatter_005_2_00x.png 2.00x
   :class: sphx-glr-single-img






.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 2.238 seconds)


.. _sphx_glr_download_gallery_ticks_date_concise_formatter.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: date_concise_formatter.ipynb <date_concise_formatter.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: date_concise_formatter.py <date_concise_formatter.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: date_concise_formatter.zip <date_concise_formatter.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
