6

I have a dictionary containing instances of Python's datetime.date and associated numeric values (integers). Something like this but a lot larger of course:

{datetime.date(2016, 5, 31): 27, datetime.date(2016, 9, 1): 87}

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

Something like this:

[Example line graph][1] (I can't embed images.)

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.

Any help would be appreciated.

Thank you

1 Answer 1

5

Using only matplotlib:

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]: [<matplotlib.lines.Line2D at 0x7f460689ee48>]

This is the plot:

enter image description here

If you can use pandas, this task is also easy this way: relatively trivial:

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]: <matplotlib.axes._subplots.AxesSubplot at 0x7f4611879160>

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

You could also use matplotlib's plot_date function: plt.plot_date(x,y,'-'). This helps with formatting the x axis.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.