get_ticklabels()返回日期格式化x-ticklabels的空Text对象,除非首先调用tight_layout()

时间:2017-07-07 21:48:00

标签: python matplotlib

以下内容已从matplotlib date_demo.py进行了修改。我删除了他们的一些评论并添加了我自己的评论以表明更改。

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

为什么我需要致电plt.tight_layout()来访问x_ticklabel文字?有没有办法访问它而无需致电plt.tight_layout()

类似的问题似乎被问到here,但没有真正的解决方案。

0 个答案:

没有答案