Plotting dates
Sooner or later, we all have had the need to plot some information over time, be it for the bank account balance each month, the total web site accesses for each day of the year, or one of many other reasons.
Matplotlib has a plotting function ad hoc for dates, plot_date()
that considers data on X, Y, or both axes, as dates, labeling the axis accordingly.
As usual, we now present an example, and we will discuss it later:
In [1]: import matplotlib as mpl In [2]: import matplotlib.pyplot as plt In [3]: import numpy as np In [4]: import datetime as dt In [5]: dates = [dt.datetime.today() + dt.timedelta(days=i) \ ...: for i in range(10)] In [6]: values = np.random.rand(len(dates)) In [7]: plt.plot_date(mpl.dates.date2num(dates), values, linestyle='-'); In [8]: plt.show()

First, a note about linestyle
keyword argument: without it, there's no line connecting the markers that are displayed alone.
We created the dates
array using timedelta()
, a datetime
function that helps us define...