Plotting date-formatted time series data
Let's look at how to plot time series data using date formatting. This is useful in visualizing stock data over time.
How to do it…
- Create a new Python file, and import the following packages:
import numpy import matplotlib.pyplot as plt from matplotlib.mlab import csv2rec import matplotlib.cbook as cbook from matplotlib.ticker import Formatter
- Define a function to format the dates. The
__init__
function sets the class variables:# Define a class for formatting class DataFormatter(Formatter): def __init__(self, dates, date_format='%Y-%m-%d'): self.dates = dates self.date_format = date_format
- Extract the value at any given time and return it in the following format:
# Extact the value at time t at position 'position' def __call__(self, t, position=0): index = int(round(t)) if index >= len(self.dates) or index < 0: return '' return self.dates[index...