Plotting dates and associated values from a dictionary with Matplotlib
<p>I have a dictionary containing instances of Python's <code>datetime.date</code> and associated numeric values (integers). Something like this but a lot larger of course:</p>

<pre><code>{datetime.date(2016, 5, 31): 27, datetime.date(2016, 9, 1): 87}
</code></pre>

<p>I am trying to use Matplotlib in order to build a line graph that would display these numeric values (<code>y</code>) against these dates (<code>x</code>), in chronological order.</p>

<p>Something like this:</p>

<p><a href="http://i.stack.imgur.com/IFHdP.png" rel="nofollow">Example line graph</a> (I can't embed images.)</p>

<p>I am new to Matplotlib and fairly new to Python as well. I tried a few solutions but they wouldn't add anything meaningful to the question.</p>

<p>Any help would be appreciated.</p>

<p>Thank you</p>

<p>Using only <code>matplotlib</code>:</p>

<pre><code>In [1]: import matplotlib.pyplot as plt

In [2]: time_dict = {datetime.date(2016, 5, 31): 27, datetime.date(2016, 8, 1): 88, datetime.date(2016, 2, 5): 42,  datetime.date(2016, 9, 1): 87}

In [3]: x,y = zip(*sorted(time_dict.items()))

In [4]: plt.plot(x,y)
Out[4]: [&lt;matplotlib.lines.Line2D at 0x7f460689ee48&gt;]
</code></pre>

<p>This is the plot:</p>

<p><a href="http://i.stack.imgur.com/ruOBD.png" rel="nofollow"><img src="http://i.stack.imgur.com/ruOBD.png" alt="enter image description here"></a></p>

<p>If you can use <code>pandas</code>, this task is also easy this way: relatively trivial:</p>

<pre><code>In [6]: import pandas as pd

In [7]: df = pd.DataFrame.from_items([(k,[v]) for k,v in time_dict.items()], orient='index', columns=['values'])

In [8]: df
Out[8]: 
            values
2016-05-31      27
2016-09-01      87
2016-02-05      42
2016-08-01      88

In [9]: df.sort_index(inplace=True)

In [10]: df
Out[10]: 
            values
2016-02-05      42
2016-05-31      27
2016-08-01      88
2016-09-01      87

In [11]: df.plot()
Out[11]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x7f4611879160&gt;
</code></pre>

<p><a href="http://i.stack.imgur.com/g070Q.png" rel="nofollow"><img src="http://i.stack.imgur.com/g070Q.png" alt="enter image description here"></a></p>

python datetime matplotlib