21
21
import matplotlib .lines as ml
22
22
from matplotlib .ticker import Formatter
23
23
24
- # Load a numpy record array from yahoo csv data with fields date, open, high,
24
+ # Load a structured numpy array from yahoo csv data with fields date, open, high,
25
25
# low, close, volume, adj_close from the mpl-data/sample_data directory. The
26
26
# record array stores the date as an np.datetime64 with a day unit ('D') in
27
- # the date column (``r. date``).
28
- r = cbook .get_sample_data ('goog.npz' )['price_data' ]. view ( np . recarray )
27
+ # the date column (``r[' date'] ``).
28
+ r = cbook .get_sample_data ('goog.npz' )['price_data' ]
29
29
r = r [:9 ] # get the first 9 days
30
30
31
31
fig , (ax1 , ax2 ) = plt .subplots (nrows = 2 , figsize = (6 , 6 ), layout = 'constrained' )
32
32
fig .get_layout_engine ().set (hspace = 0.15 )
33
33
34
34
# First we'll do it the default way, with gaps on weekends
35
- ax1 .plot (r . date , r . adj_close , 'o-' )
35
+ ax1 .plot (r [ " date" ] , r [ " adj_close" ] , 'o-' )
36
36
37
37
# Highlight gaps in daily data
38
- gaps = np .flatnonzero (np .diff (r . date ) > np .timedelta64 (1 , 'D' ))
38
+ gaps = np .flatnonzero (np .diff (r [ " date" ] ) > np .timedelta64 (1 , 'D' ))
39
39
for gap in r [['date' , 'adj_close' ]][np .stack ((gaps , gaps + 1 )).T ]:
40
- ax1 .plot (gap . date , gap . adj_close , 'w--' , lw = 2 )
40
+ ax1 .plot (gap [ ' date' ] , gap [ ' adj_close' ] , 'w--' , lw = 2 )
41
41
ax1 .legend (handles = [ml .Line2D ([], [], ls = '--' , label = 'Gaps in daily data' )])
42
42
43
43
ax1 .set_title ("Plot y at x Coordinates" )
51
51
def format_date (x , _ ):
52
52
try :
53
53
# convert datetime64 to datetime, and use datetime's strftime:
54
- return r . date [round (x )].item ().strftime ('%a' )
54
+ return r [ " date" ] [round (x )].item ().strftime ('%a' )
55
55
except IndexError :
56
56
pass
57
57
58
58
# Create an index plot (x defaults to range(len(y)) if omitted)
59
- ax2 .plot (r . adj_close , 'o-' )
59
+ ax2 .plot (r [ " adj_close" ] , 'o-' )
60
60
61
61
ax2 .set_title ("Plot y at Index Coordinates Using Custom Formatter" )
62
62
ax2 .xaxis .set_major_formatter (format_date ) # internally creates FuncFormatter
@@ -79,6 +79,6 @@ def __call__(self, x, pos=0):
79
79
pass
80
80
81
81
82
- ax2 .xaxis .set_major_formatter (MyFormatter (r . date , '%a' ))
82
+ ax2 .xaxis .set_major_formatter (MyFormatter (r [ " date" ] , '%a' ))
83
83
84
84
plt .show ()
0 commit comments