0

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.

hhquark
  • 379
  • 3
  • 10
  • First calling `plt.show()` and then getting the ticklabels seems to be working, so no need to call `plt.tight_layout()`. So it seems like the ticklabels are created during the actual creation of the figure. Maybe explicitly setting the x axis ticklabels based on the data, solves the problem, without the need to plot first. – rinkert Jul 07 '17 at 23:24
  • This is what you are looking for: https://stackoverflow.com/questions/41122923/getting-tick-labels-in-matplotlib#41124884 – Y. Luo Jul 08 '17 at 05:29
  • I added an answer to [the question](https://stackoverflow.com/questions/41496377/matplotlib-with-qt5agg-backend-returns-empty-ticklabels/44984451#44984451) you call similar. In most cases you do not want to manipulate the ticklabels themselves. So if you can tell us the reason to get the ticklabels, there is probably a better solution than drawing the canvas first. – ImportanceOfBeingErnest Jul 08 '17 at 09:09
  • Call `fig.canvas.draw()` before `ax.xaxis.get_ticklabels()` and it should work. – Jean-Sébastien Jul 10 '17 at 14:58
  • It seems I need to draw the figure before I have access to the ticklabels. Thanks all! @ImportanceOfBeingErnest I have a weird date-format that I was trying to use and my approach required knowing all the dates (I don't show the day unless it changes; e.g. ["2017-07-10\n00:00:00", "\n12:00:00", "2017-07-11\n00:00:00", "\n12:00:00"]). I can make another post with that specific question. – hhquark Jul 10 '17 at 16:03
  • @hhquark Yes, asking as specifically as possible about the *actual* problem is always best. It ensures that you get a useful answer and don't run into things like the [xyproblem](http://xyproblem.info). Given that this question is now already 2 days old and has been marked as duplicate, opening a new question would be the way to go. – ImportanceOfBeingErnest Jul 10 '17 at 18:54

0 Answers0