Plotting dates and associated values from a dictionary with Matplotlib

后端 未结 1 1723
别跟我提以往
别跟我提以往 2021-01-19 09:33

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:

相关标签:
1条回答
  • 2021-01-19 09:47

    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:

    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>
    

    0 讨论(0)
提交回复
热议问题