首页 > 解决方案 > 如何在 Python for 循环中绘制一个月的平均线?

问题描述

我有看起来像这样的代码:

for _, d in Country_sim_count.set_index('Week').groupby('Home_Country'):
    fig, ax = plt.subplots()
    d['SIM_total'].plot()
    plt.axhline(y=d['SIM_total'].mean(), color='r', linestyle='--') #the line I would like to alter
    plt.xticks(rotation=90)
    plt.title(f"Weekly Sim Count for {d['Home_Country'].iat[0]}")
    plt.xlabel('Week')

    a = '2020-01-13' #Key dates area
    b = '2020-02-10'

    plt.axvspan(a, b, color='gray', alpha=0.2, lw=0)
    plt.legend()
    #plt.savefig(f"{d['Home_Country'].iat[0]}_plot.png")
    plt.show()

数据框包含不同的月份,但是在第 4 行上,我想绘制一条红线,显示每个国家/地区仅计算 2 月的平均值,而不是计算所有月份组合的平均值。循环中每个国家/地区的 2 月平均值会有所不同。目前我的情节是这样的:

在此处输入图像描述

红线的值是 1 月至 5 月的平均值,但我希望红线值显示整个 2 月的平均值。

有没有办法我可以做到这一点?

标签: pythonloopsmatplotlibaverage

解决方案


也许您可以尝试在括号内包含一个条件?

plt.axhline(y=d[d['SIM_total'] == 'February'].mean(), color='r', linestyle='--')

我希望它有帮助!

编辑:

在那种情况下,我认为最好不要将“周”设置为索引。

你可能不是很漂亮,你可以使用下面的代码。

feb_mean = d[d['Week'] == 'February']['SIM_total'].mean()

plt.axhline(y=feb_mean, color='r', linestyle='--')

让我知道这是否适合您!


推荐阅读