Reputation: 15320
I have a dictionary where the value is a list of tuples. The tuple consists of a datetime object and a numeric value, e.g.:
{
'option1': [
(datetime.datetime(2021, 8, 6, 6, 11, 29), 2480.82),
(datetime.datetime(2021, 8, 6, 6, 21, 36), 2499.14),
(datetime.datetime(2021, 8, 6, 6, 31, 40), 2488.59),
(datetime.datetime(2021, 8, 6, 6, 41, 44), 2486.51),
],
'option2': [
(datetime.datetime(2021, 8, 6, 6, 11, 30), 560.56),
(datetime.datetime(2021, 8, 6, 6, 21, 36), 1100.19),
(datetime.datetime(2021, 8, 6, 6, 31, 40), 795.54),
(datetime.datetime(2021, 8, 6, 6, 41, 44), 873.97),
],
}
Now I would like to plot values against time, one line for every key (in this case "option1" and "option2"). With matplotlib
, I started looping over the dict.items()
, nested looping over the list, and then dissecting the tuple. However, I wonder if there is a more elegant way, either in matplotlib
or any other visualization library. I do not neccessarily need to use matplotlib
.
Upvotes: 1
Views: 381
Reputation: 4181
zip
built-in function together with argument unpacking would do the trick:
import datetime
import matplotlib.pyplot as plt
data = {
'option1': [
(datetime.datetime(2021, 8, 6, 6, 11, 29), 2480.82),
(datetime.datetime(2021, 8, 6, 6, 21, 36), 2499.14),
(datetime.datetime(2021, 8, 6, 6, 31, 40), 2488.59),
(datetime.datetime(2021, 8, 6, 6, 41, 44), 2486.51),
],
'option2': [
(datetime.datetime(2021, 8, 6, 6, 11, 30), 560.56),
(datetime.datetime(2021, 8, 6, 6, 21, 36), 1100.19),
(datetime.datetime(2021, 8, 6, 6, 31, 40), 795.54),
(datetime.datetime(2021, 8, 6, 6, 41, 44), 873.97),
],
}
for option, tuples in data.items():
x, y = zip(*tuples)
plt.plot(x, y, label=option)
plt.legend()
plt.show()
Upvotes: 1