使用Matplotlib从字典中绘制日期和相关值 [英] Plotting dates and associated values from a dictionary with Matplotlib

查看:95
本文介绍了使用Matplotlib从字典中绘制日期和相关值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其中包含Python的 datetime.date 的实例以及相关的数值(整数)。像这样的东西,但当然要大得多:

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

我正在尝试使用Matplotlib进行构建折线图,将按时间顺序显示这些数字值( y )相对于这些日期( x )的时间。 / p>

类似这样的东西:





我是Matplotlib的新手,也是Python的新手。我尝试了一些解决方案,但它们不会给问题添加任何有意义的东西。



任何帮助将不胜感激。



谢谢

解决方案

仅使用 matplotlib

 在[1]中:将matplotlib.pyplot导入为plt 

在[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}

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

在[4]中:plt.plot(x,y)
Out [4]:[< matplotlib.lines.Line2D at 0x7f460689ee48>]

这是情节:





如果可以的话使用 pandas ,此任务也很简单:相对琐碎:

 在[6]中:导入pa ndas as pd 

在[7]中:df = pd.DataFrame.from_items([(k,[v])for k,v in time_dict.items()],orient ='index',列= ['值'])

入[8]:df
出[8]:

2016-05-31 27
2016-09-01 87
2016-02-05 42
2016-08-01 88

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

入[10]:df
出[10]:

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位于0x7f4611879160>


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:

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

解决方案

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>

这篇关于使用Matplotlib从字典中绘制日期和相关值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆