The following is modified from matplotlib
's date_demo.py
. I've removed some of their comments and added my own to indicate changes.
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
datafile = cbook.get_sample_data('goog.npy')
try:
r = np.load(datafile, encoding='bytes').view(np.recarray)
except TypeError:
r = np.load(datafile).view(np.recarray)
fig, ax = plt.subplots()
ax.plot(r.date, r.adj_close)
# format the ticks
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
datemin = datetime.date(r.date.min().year, 1, 1)
datemax = datetime.date(r.date.max().year + 1, 1, 1)
ax.set_xlim(datemin, datemax)
# format the coords message box
def price(x):
return '$%1.2f' % x
ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.format_ydata = price
ax.grid(True)
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
# My addition:
# >>> [u'', u'', u'', u'', u'', u''] # without plt.tight_layout()
# >>> [u'2004', u'2005', u'2006', u'2007', u'2008', u'2009'] # with plt.tight_layout()
# plt.tight_layout()
print [tl.get_text() for tl in ax.xaxis.get_ticklabels()]
plt.show()
Why do I need to call plt.tight_layout()
to access the x_ticklabel
text? Is there a way to access it without having to call plt.tight_layout()
?
A similar question seems to have been asked here, but with no real resolution.