日期刻度标签

演示如何使用日期刻度定位器和格式化程序在matplotlib中创建日期图。有关控制主要和次要刻度的更多信息,请参阅major_minor_demo1.py

所有matplotlib日期绘图都是通过将日期实例转换为自 0001-01-01 00:00:00 UTC 加上一天后的天数(由于历史原因)来完成的。 转换,刻度定位和格式化是在幕后完成的,因此这对您来说是最透明的。 日期模块提供了几个转换器函数 matplotlib.dates.date2nummatplotlib.dates.num2date。这些可以在datetime.datetime 对象和 numpy.datetime64 对象之间进行转换。

日期刻度标签示例

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.dates as mdates
  4. import matplotlib.cbook as cbook
  5. years = mdates.YearLocator() # every year
  6. months = mdates.MonthLocator() # every month
  7. yearsFmt = mdates.DateFormatter('%Y')
  8. # Load a numpy record array from yahoo csv data with fields date, open, close,
  9. # volume, adj_close from the mpl-data/example directory. The record array
  10. # stores the date as an np.datetime64 with a day unit ('D') in the date column.
  11. with cbook.get_sample_data('goog.npz') as datafile:
  12. r = np.load(datafile)['price_data'].view(np.recarray)
  13. fig, ax = plt.subplots()
  14. ax.plot(r.date, r.adj_close)
  15. # format the ticks
  16. ax.xaxis.set_major_locator(years)
  17. ax.xaxis.set_major_formatter(yearsFmt)
  18. ax.xaxis.set_minor_locator(months)
  19. # round to nearest years...
  20. datemin = np.datetime64(r.date[0], 'Y')
  21. datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y')
  22. ax.set_xlim(datemin, datemax)
  23. # format the coords message box
  24. def price(x):
  25. return '$%1.2f' % x
  26. ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
  27. ax.format_ydata = price
  28. ax.grid(True)
  29. # rotates and right aligns the x labels, and moves the bottom of the
  30. # axes up to make room for them
  31. fig.autofmt_xdate()
  32. plt.show()

下载这个示例