日期索引格式化程序

在绘制每日数据时,频繁的请求是绘制忽略跳过的数据,例如,周末没有额外的空格。这在金融时间序列中尤为常见,因为您可能拥有M-F而非Sat,Sun的数据,并且您不需要x轴上的间隙。方法是简单地使用xdata的整数索引和自定义刻度Formatter来获取给定索引的适当日期字符串。

日期索引格式化程序示例

输出:

  1. loading /home/tcaswell/mc3/envs/dd37/lib/python3.7/site-packages/matplotlib/mpl-data/sample_data/msft.csv
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.cbook as cbook
  4. from matplotlib.dates import bytespdate2num, num2date
  5. from matplotlib.ticker import Formatter
  6. datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
  7. print('loading %s' % datafile)
  8. msft_data = np.genfromtxt(datafile, delimiter=',', names=True,
  9. converters={0: bytespdate2num('%d-%b-%y')})[-40:]
  10. class MyFormatter(Formatter):
  11. def __init__(self, dates, fmt='%Y-%m-%d'):
  12. self.dates = dates
  13. self.fmt = fmt
  14. def __call__(self, x, pos=0):
  15. 'Return the label for time x at position pos'
  16. ind = int(np.round(x))
  17. if ind >= len(self.dates) or ind < 0:
  18. return ''
  19. return num2date(self.dates[ind]).strftime(self.fmt)
  20. formatter = MyFormatter(msft_data['Date'])
  21. fig, ax = plt.subplots()
  22. ax.xaxis.set_major_formatter(formatter)
  23. ax.plot(np.arange(len(msft_data)), msft_data['Close'], 'o-')
  24. fig.autofmt_xdate()
  25. plt.show()

下载这个示例