【问题标题】:For loops and time series plots对于循环和时间序列图
【发布时间】:2020-11-16 06:31:27
【问题描述】:

我是编码新手,正在尝试制作时间序列散点图。 12 年来,我每天都有每小时的臭氧浓度。我计算了一年中每个月的平均值和最大值,并试图比较月平均值和月最大值数据。我想为 4 月、5 月和 6 月制作 3 个单独的散点图(所以每个图应该有两条线,平均和最大值)。这是我到目前为止所做的:

#earlier in the code I specified only the months of Apr, May, Jun using:

df = df[df.month.isin([4, 5, 6])].copy()

#more code involving calculations, fast forward:

for month in avg_MDA8.month.unique():
    for month in max_MDA8.month.unique():
        data1 = avg_MDA8[avg_MDA8.month == month]
        data2 = max_MDA8[max_MDA8.month == month]  # filter and plot the data for a specific month
        plt.figure()  # create a new figure for each month
        plt.plot(data1.datetime, data1.r_mean, color='k',linewidth=2.0,label='average MDA8')
        plt.plot(data2.datetime, data2.r_mean, color='g',linewidth=2.0,label='max MDA8')
        plt.xlim(date(2009, 1, 1), date(2020, 12, 31))
        plt.ylim(0, 100)
        plt.title(f'Month: {month}')
        plt.ylabel('MDA8 (ppb)')
        plt.xlabel('Year')
        plt.legend(bbox_to_anchor=(1.0, 0.15))
        plt.tight_layout()

但是,输出总共给了我 9 个图:April_avg/April_max、April_avg/May_max、April_avg/June_max; May_avg/April_max 等...

我只想比较 April_avg/April_max、May_avg/May_max、June_avg/June_max。

编辑 对不起,我错了。循环没有错误地绘制代码,只是打印每个图的 3 个版本。关于如何防止它重复图表的任何建议?

【问题讨论】:

    标签: python for-loop matplotlib time-series


    【解决方案1】:

    首先,请注意您是如何在嵌套循环中重载 month 的:

    for month in avg_MDA8.month.unique():
        for month in max_MDA8.month.unique():
    

    每次您尝试在外循环中设置month 时,内循环都会立即破坏该值。您的描述说您想要获取相应的元素,并并行迭代几个月一次。这样做更简单:在avgmax 中设置的唯一月份相同,对吗?因此,无论您从哪里获得它们,都要遍历几个月。只使用一个循环:

    for month in avg_MDA8.month.unique():
        data1 = avg_MDA8[avg_MDA8.month == month]
        data2 = max_MDA8[max_MDA8.month == month] 
    

    month 现在对每个所需值只取一次。

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 2016-07-16
      • 2023-02-22
      • 2015-04-12
      • 2019-10-20
      • 2022-01-15
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      相关资源
      最近更新 更多