Sha Sha - 29 days ago 9
Python Question

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

In python 2.7, I have a dictionary whose size can vary. For each key, Q1,Q2,Q3.... I need to plot the dictionary values, which are lists containing dates and integers.

{'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)

['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.

Answer

We can simply iterate over the dictionary items, and then use zip() to unpack the values. The label= keyword argument to plot() will make the legend() call create the legend automatically.

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. 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 :)