File: date_index_formatter2.py

package info (click to toggle)
matplotlib 3.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,264 kB
  • sloc: python: 123,969; cpp: 57,655; ansic: 29,431; objc: 2,244; javascript: 757; makefile: 163; sh: 111
file content (45 lines) | stat: -rw-r--r-- 1,400 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
====================
Date Index Formatter
====================

When plotting daily data, a frequent request is to plot the data
ignoring skips, e.g., no extra spaces for weekends.  This is particularly
common in financial time series, when you may have data for M-F and
not Sat, Sun and you don't want gaps in the x axis.  The approach is
to simply use the integer index for the xdata and a custom tick
Formatter to get the appropriate date string for a given index.
"""

import dateutil.parser
from matplotlib import cbook, dates
import matplotlib.pyplot as plt
from matplotlib.ticker import Formatter
import numpy as np


datafile = cbook.get_sample_data('msft.csv', asfileobj=False)
print('loading %s' % datafile)
msft_data = np.genfromtxt(
    datafile, delimiter=',', names=True,
    converters={0: lambda s: dates.date2num(dateutil.parser.parse(s))})


class MyFormatter(Formatter):
    def __init__(self, dates, fmt='%Y-%m-%d'):
        self.dates = dates
        self.fmt = fmt

    def __call__(self, x, pos=0):
        """Return the label for time x at position pos."""
        ind = int(round(x))
        if ind >= len(self.dates) or ind < 0:
            return ''
        return dates.num2date(self.dates[ind]).strftime(self.fmt)


fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(MyFormatter(msft_data['Date']))
ax.plot(msft_data['Close'], 'o-')
fig.autofmt_xdate()
plt.show()