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

    Click :ref:`here <sphx_glr_download_gallery_ticks_and_spines_centered_ticklabels.py>` to download the full example code
.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_ticks_and_spines_centered_ticklabels.py:


==============================
Centering labels between ticks
==============================

Ticklabels are aligned relative to their associated tick. The alignment
'center', 'left', or 'right' can be controlled using the horizontal alignment
property::

    for label in ax.xaxis.get_xticklabels():
        label.set_horizontalalignment('right')

However there is no direct way to center the labels between ticks. To fake
this behavior, one can place a label on the minor ticks in between the major
ticks, and hide the major tick labels and minor ticks.

Here is an example that labels the months, centered between the ticks.



.. image:: /gallery/ticks_and_spines/images/sphx_glr_centered_ticklabels_001.png
    :class: sphx-glr-single-img





.. code-block:: python


    import numpy as np
    import matplotlib.cbook as cbook
    import matplotlib.dates as dates
    import matplotlib.ticker as ticker
    import matplotlib.pyplot as plt

    # load some financial data; apple's stock price
    with cbook.get_sample_data('aapl.npz') as fh:
        r = np.load(fh)['price_data'].view(np.recarray)
    r = r[-250:]  # get the last 250 days
    # Matplotlib works better with datetime.datetime than np.datetime64, but the
    # latter is more portable.
    date = r.date.astype('O')

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

    ax.xaxis.set_major_locator(dates.MonthLocator())
    # 16 is a slight approximation since months differ in number of days.
    ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=16))

    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))

    for tick in ax.xaxis.get_minor_ticks():
        tick.tick1line.set_markersize(0)
        tick.tick2line.set_markersize(0)
        tick.label1.set_horizontalalignment('center')

    imid = len(r) // 2
    ax.set_xlabel(str(date[imid].year))
    plt.show()


.. _sphx_glr_download_gallery_ticks_and_spines_centered_ticklabels.py:


.. only :: html

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



  .. container:: sphx-glr-download

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



  .. container:: sphx-glr-download

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


.. only:: html

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

    Keywords: matplotlib code example, codex, python plot, pyplot
    `Gallery generated by Sphinx-Gallery
    <https://sphinx-gallery.readthedocs.io>`_
