You are reading an old version of the documentation (v1.5.0). For the latest version see

We're updating the default styles for Matplotlib 2.0

Learn what to expect in the new updates


Previous topic

pylab_examples example code:

Next topic

pylab_examples example code:

This Page

pylab_examples example code: centered_ticklabels.pyΒΆ

(Source code, png, hires.png, pdf)

# sometimes it is nice to have ticklabels centered.  mpl currently
# associates a label with a tick, and the label can be aligned
# 'center', 'left', or 'right' using the horizontal alignment property:
#   for label in ax.xaxis.get_xticklabels():
#       label.set_horizontalalignment('right')
# but this doesn't help center the label between ticks.  One solution
# is to "face it".  Use the minor ticks to place a tick centered
# between the major 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
fh = cbook.get_sample_data('aapl.npy.gz')
    # Python3 cannot load python2 .npy files with datetime(object) arrays
    # unless the encoding is set to bytes. Hovever this option was
    # not added until numpy 1.10 so this example will only work with
    # python 2 or with numpy 1.10 and later.
    r = np.load(fh, encoding='bytes')
except TypeError:
    r = np.load(fh)
r = r[-250:]  # get the last 250 days

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



for tick in ax.xaxis.get_minor_ticks():

imid = len(r)/2

Keywords: python, matplotlib, pylab, example, codex (see Search examples)