首页 > 解决方案 > 循环问题的 Matplotlib 图

问题描述

我正在尝试使用 for 循环在 matplotlib 中绘制时间序列数据。目标是动态绘制价值“n”年的每日收盘价数据。如果我加载 7 年的数据,我会得到 7 个独特的图。我创建了一个数据集 yearly_date_ranges 的开始和结束日期的摘要(日期是索引)。我用它来填充开始和结束日期。到目前为止,我编写的代码生成了所有每日数据的 7 个图,而不是 7 个独特的图,每年一个。任何帮助表示赞赏。提前致谢!

    yearly_date_ranges
              start        end
    Date                      
    2014 2014-04-01 2014-12-31
    2015 2015-01-01 2015-12-31
    2016 2016-01-01 2016-12-31
    2017 2017-01-01 2017-12-31
    2018 2018-01-01 2018-12-31
    2019 2019-01-01 2019-12-31
    2020 2020-01-01 2020-05-28

    import pandas as pd
    import matplotlib.pyplot as plt
    %matplotlib inline

    fig = plt.figure(figsize=(12,20))
    for i in range(len(yearly_date_ranges)):
        ax = fig.add_subplot(len(yearly_date_ranges),1,i + 1)       
        for row in yearly_date_ranges.itertuples(index=False):
            start = row.start
            end = row.end
            subset = data[start:end]        
            ax.plot(subset['Close'])

    plt.show()

标签: pandasmatplotlibplot

解决方案


这行得通!感谢您的帮助

    fig, axes = plt.subplots(7,1, figsize=(12,20))

    years = data.index.year

    for ax, (k,d) in zip(axes.ravel(), data['Close'].groupby(years)):
        d.plot(x='Close', ax=ax)

推荐阅读