简体   繁体   中英

How to plot average line for a month in a Python for loop?

I have code which looks something like this:

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

The dataframe contains various months however on Line 4 I wanted to plot a red line which would show the average calculated for only February per country, instead of calculating the mean for all the months combined. The feb average will be different for each country in the loop. Currently my plot looks like this:

在此处输入图像描述

The value for the red line is the average combined from Jan-May however I'm hoping to have the red line value show the average value for Feb throughout.

Is there a way I could do this?

Maybe you could try including a condition inside the brackets?

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

I hope it helps!

EDIT:

In that case I think it would be better not to set 'Week' as the index.

Thou it may not very pretty, you could use something like the code below.

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

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

Let me know if this works for you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM