简体   繁体   English

绘制包含列表作为值的字典的所有键(python)

[英]plotting all keys of a dictionary which contains list as values (python)

In python 2.7, I have a dictionary whose size can vary. 在python 2.7中,我有一个字典,字典的大小可以变化。 For each key, Q1,Q2,Q3.... I need to plot the dictionary values, which are lists containing dates and integers. 对于每个键,Q1,Q2,Q3 ......我需要绘制字典值,这些值是包含日期和整数的列表。

{'Q1': [['20.03.2016', 25], ['21.03.2016', 35], ['22.03.2016', 22], ['23.03.2016
', 50], ['24.03.2016', 50], ['30.03.2016', 50], ['30.03.2016', 50]], 'Q3': [['20
.03.2016', 23], ['21.03.2016', 21], ['22.03.2016', 27], ['23.03.2016', 20], ['24
.03.2016', 20], ['30.03.2016', 20], ['30.03.2016', 20]], 'Q2': [['20.03.2016', 1
5], ['21.03.2016', 12], ['22.03.2016', 15], ['23.03.2016', 15], ['24.03.2016', 1
5], ['30.03.2016', 15], ['30.03.2016', 15]], 'Q5': [['20.03.2016', 320], ['21.03
.2016', 30], ['22.03.2016', 30], ['23.03.2016', 30], ['24.03.2016', 30], ['30.03
.2016', 30], ['30.03.2016', 30]], 'Q4': [['20.03.2016', 130], ['21.03.2016', 10]
, ['22.03.2016', 10], ['23.03.2016', 10], ['24.03.2016', 10], ['30.03.2016', 10]
, ['30.03.2016', 10]], 'Q7': [['23.03.2016', 5], ['24.03.2016', 5], ['30.03.2016
', 5], ['30.03.2016', 5]], 'Q9': [['30.03.2016', 17]], 'Q8': [['24.03.2016', 15]
, ['30.03.2016', 15], ['30.03.2016', 15]]}

How can I draw all the keys in one plot window containing lines for each key and labelled as per key names itself? 如何在一个包含每个键的行的绘图窗口中绘制所有键,并按键名称标记? Each line should be color coded and show all the integer vs date data points for each key. 每行应使用颜色编码,并显示每个键的所有整数与日期数据点。 So Q1 line will plot second colomn(integers) vs first colomn (dates) 因此Q1线将绘制第二列(整数)与第一列(日期)的关系图

['20.03.2016', 25], 
['21.03.2016', 35],
['22.03.2016', 22],
['23.03.2016', 50],
['24.03.2016', 50], 
['30.03.2016', 50],
['30.03.2016', 50]

Each line can be color coded and should be have label of the key in the legend. 每行都可以进行颜色编码,并且应该在图例中包含键的标签。 I am using numpy and matplotlib libraries in python. 我在python中使用numpy和matplotlib库。

We can simply iterate over the dictionary items, and then use zip() to unpack the values. 我们可以简单地遍历字典项,然后使用zip()解压缩值。 The label= keyword argument to plot() will make the legend() call create the legend automatically. plot()label=关键字参数将使legend()调用自动创建图例。

for key, data_list in data_dict.items():
    dates_str, values = zip(*data_list)  # Unpack
    dates = convert_str_to_dates(dates_str)  # Not handled in example
    plt.plot(dates, values, label=key)
plt.legend()

To be solved is how to go from a list of strings to some sort of date object that matplotlib understands. 要解决的是如何从字符串列表转到matplotlib可以理解的某种日期对象。 This should be fairly easy to find in the documentation though. 不过,在文档中应该很容易找到它。

Edit: The trick with using zip() to unpack a list-of-lists was one of those "Aha!"-moments for me :) 编辑:使用zip()解压缩列表列表的技巧对我来说就是那些“啊哈!”时刻之一:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM