绘制元组列表,由日期时间对象和数值组成

Plot a list of tuples, consisting of a datetime object and a numeric value

我有一本字典,其中的值是一个元组列表。该元组由一个日期时间对象和一个数值组成,例如:

{
    '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),
    ],
}

现在我想根据时间绘制值,每个键一行(在本例中为“option1”和“option2”)。使用 matplotlib,我开始循环遍历 dict.items(),嵌套循环遍历列表,然后剖析元组。但是,我想知道在 matplotlib 或任何其他可视化库中是否有更优雅的方法。我不一定需要使用 matplotlib.

zip 内置函数和参数解包就可以解决问题:

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()