@@ -91,3 +91,41 @@ How do I use matplotlib with zope?
9191----------------------------------
9292
9393TODO
94+
95+
96+ .. _date-index-plots :
97+
98+ How do I skip dates where there is no data?
99+ ===========================================
100+
101+ When plotting time series, eg financial time series, one often wants
102+ to leave out days on which there is no data, eg weekends. By passing
103+ in dates on the x-xaxis, you get large horizontal gaps on periods when
104+ there is not data. The solution is to pass in some proxy x-data, eg
105+ evenly sampled indicies, and then use a custom formatter to format
106+ these as dates. The example below shows how to use an 'index formatter'
107+ to achieve the desired plot
108+
109+ import numpy as np
110+ import matplotlib.pyplot as plt
111+ import matplotlib.mlab as mlab
112+ import matplotlib.ticker as ticker
113+
114+ r = mlab.csv2rec('../data/aapl.csv')
115+ r.sort()
116+ r = r[-30:] # get the last 30 days
117+
118+ N = len(r)
119+ ind = np.arange(N) # the evenly spaced plot indices
120+
121+ def format_date(x, pos=None):
122+ thisind = np.clip(int(x+0.5), 0, N-1)
123+ return r.date[thisind].strftime('%Y-%m-%d')
124+
125+ fig = plt.figure()
126+ ax = fig.add_subplot(111)
127+ ax.plot(ind, r.adj_close, 'o-')
128+ ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
129+ fig.autofmt_xdate()
130+
131+ plt.show()
0 commit comments