|
3 | 3 | Date tick labels
|
4 | 4 | ================
|
5 | 5 |
|
6 |
| -Show how to make date plots in matplotlib using date tick locators and |
7 |
| -formatters. See major_minor_demo1.py for more information on |
8 |
| -controlling major and minor ticks |
| 6 | +Show how to make date plots in Matplotlib using date tick locators and |
| 7 | +formatters. See :doc:`/gallery/ticks_and_spines/major_minor_demo` for more |
| 8 | +information on controlling major and minor ticks. |
9 | 9 |
|
10 | 10 | All matplotlib date plotting is done by converting date instances into days
|
11 | 11 | since 0001-01-01 00:00:00 UTC plus one day (for historical reasons). The
|
|
23 | 23 |
|
24 | 24 | years = mdates.YearLocator() # every year
|
25 | 25 | months = mdates.MonthLocator() # every month
|
26 |
| -yearsFmt = mdates.DateFormatter('%Y') |
| 26 | +years_fmt = mdates.DateFormatter('%Y') |
27 | 27 |
|
28 |
| -# Load a numpy record array from yahoo csv data with fields date, open, close, |
29 |
| -# volume, adj_close from the mpl-data/example directory. The record array |
30 |
| -# stores the date as an np.datetime64 with a day unit ('D') in the date column. |
| 28 | +# Load a numpy structured array from yahoo csv data with fields date, open, |
| 29 | +# close, volume, adj_close from the mpl-data/example directory. This array |
| 30 | +# stores the date as an np.datetime64 with a day unit ('D') in the 'date' |
| 31 | +# column. |
31 | 32 | with cbook.get_sample_data('goog.npz') as datafile:
|
32 |
| - r = np.load(datafile)['price_data'].view(np.recarray) |
| 33 | + data = np.load(datafile)['price_data'] |
33 | 34 |
|
34 | 35 | fig, ax = plt.subplots()
|
35 |
| -ax.plot(r.date, r.adj_close) |
| 36 | +ax.plot('date', 'adj_close', data=data) |
36 | 37 |
|
37 | 38 | # format the ticks
|
38 | 39 | ax.xaxis.set_major_locator(years)
|
39 |
| -ax.xaxis.set_major_formatter(yearsFmt) |
| 40 | +ax.xaxis.set_major_formatter(years_fmt) |
40 | 41 | ax.xaxis.set_minor_locator(months)
|
41 | 42 |
|
42 |
| -# round to nearest years... |
43 |
| -datemin = np.datetime64(r.date[0], 'Y') |
44 |
| -datemax = np.datetime64(r.date[-1], 'Y') + np.timedelta64(1, 'Y') |
| 43 | +# round to nearest years. |
| 44 | +datemin = np.datetime64(data['date'][0], 'Y') |
| 45 | +datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') |
45 | 46 | ax.set_xlim(datemin, datemax)
|
46 | 47 |
|
47 |
| - |
48 | 48 | # format the coords message box
|
49 |
| -def price(x): |
50 |
| - return '$%1.2f' % x |
51 | 49 | ax.format_xdata = mdates.DateFormatter('%Y-%m-%d')
|
52 |
| -ax.format_ydata = price |
| 50 | +ax.format_ydata = lambda x: '$%1.2f' % x # format the price. |
53 | 51 | ax.grid(True)
|
54 | 52 |
|
55 | 53 | # rotates and right aligns the x labels, and moves the bottom of the
|
|
0 commit comments