You are reading an old version of the documentation (v3.1.1). For the latest version see
Version 3.1.2
Fork me on GitHub

Related Topics

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

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.

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 ='O')

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

# 16 is a slight approximation since months differ in number of days.


for tick in ax.xaxis.get_minor_ticks():

imid = len(r) // 2

Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery