【问题标题】:Matplotlib plot for loop issue循环问题的 Matplotlib 图
【发布时间】:2020-09-17 07:39:35
【问题描述】:

我正在尝试使用 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()

【问题讨论】:

    标签: pandas matplotlib plot


    【解决方案1】:

    这行得通!感谢您的帮助

        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)
    

    【讨论】:

      【解决方案2】:

      你应该动态地做这样的事情:

      fig, axes = plt.subplots(7,1, figsize=(12,20))
      
      years = data.index.year
      
      for ax, (k,d) in zip(axes.ravel(), data.groupby(years)):
          d.plot(y='Close', ax=ax)
      

      【讨论】:

      • 谢谢,这生成了数据中所有列的 7 个图,而不仅仅是“关闭”。看起来它按年只是充满了额外的行。现在更深入地研究这个。
      • 我将 data.groupby(years)): 更改为 data['Close'].groupby(years)): 并且成功了!非常感谢!
      • 其实我的代码如果是 y='Close' 也可以编辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 2019-05-28
      • 2011-11-03
      • 1970-01-01
      • 2021-10-17
      • 2016-03-16
      相关资源
      最近更新 更多