Skip to content

Commit 8c3f33e

Browse files
committed
added index date formatter example
svn path=/trunk/matplotlib/; revision=3385
1 parent fd54ced commit 8c3f33e

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

examples/date_index_formatter.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
"""
3+
When plotting daily data, a frequent request is to plot the data
4+
ignoring skips, eg no extra spaces for weekends. This is particularly
5+
common in financial time series, when you may have data for M-F and
6+
not Sat, Sun and you don't want gaps in the x axis. The approach is
7+
to simply use the integer index for the xdata and a custom tick
8+
Formatter to get the appropriate date string for a given index.
9+
"""
10+
11+
import numpy
12+
from matplotlib.mlab import csv2rec
13+
from pylab import figure, show
14+
from matplotlib.dates import Formatter
15+
16+
r = csv2rec('data/msft.csv')[-40:]
17+
18+
class MyFormatter(Formatter):
19+
def __init__(self, dates, fmt='%Y-%m-%d'):
20+
self.dates = dates
21+
self.fmt = fmt
22+
23+
def __call__(self, x, pos=0):
24+
'Return the label for time x at position pos'
25+
ind = int(round(x))
26+
if ind>=len(self.dates) or ind<0: return ''
27+
28+
return self.dates[ind].strftime(self.fmt)
29+
30+
formatter = MyFormatter(r.date)
31+
32+
fig = figure()
33+
ax = fig.add_subplot(111)
34+
ax.xaxis.set_major_formatter(formatter)
35+
ax.plot(numpy.arange(len(r)), r.close, 'o-')
36+
fig.autofmt_xdate()
37+
show()

examples/pick_event_demo2.py

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ def onpick(event):
2424
N = len(event.ind)
2525
if not N: return True
2626

27+
2728
figi = figure()
2829
for subplotnum, dataind in enumerate(event.ind):
2930
ax = figi.add_subplot(N,1,subplotnum+1)

0 commit comments

Comments
 (0)