File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ When plotting time series, eg financial time series, one often wants
3+ to leave out days on which there is no data, eh weekends. The example
4+ below shows how to use an 'index formatter' to achieve the desired plot
5+ """
6+ import numpy as np
7+ import matplotlib .pyplot as plt
8+ import matplotlib .mlab as mlab
9+ import matplotlib .ticker as ticker
10+
11+ r = mlab .csv2rec ('../data/aapl.csv' )
12+ r .sort ()
13+ r = r [- 30 :] # get the last 30 days
14+
15+
16+ # first we'll do it the default way, with gaps on weekends
17+ fig = plt .figure ()
18+ ax = fig .add_subplot (111 )
19+ ax .plot (r .date , r .adj_close , 'o-' )
20+ fig .autofmt_xdate ()
21+
22+ # next we'll write a custom formatter
23+ N = len (r )
24+ ind = np .arange (N ) # the evenly spaced plot indices
25+
26+ def format_date (x , pos = None ):
27+ thisind = np .clip (int (x + 0.5 ), 0 , N - 1 )
28+ return r .date [thisind ].strftime ('%Y-%m-%d' )
29+
30+ fig = plt .figure ()
31+ ax = fig .add_subplot (111 )
32+ ax .plot (ind , r .adj_close , 'o-' )
33+ ax .xaxis .set_major_formatter (ticker .FuncFormatter (format_date ))
34+ fig .autofmt_xdate ()
35+
36+ plt .show ()
You can’t perform that action at this time.
0 commit comments