Home > Blockchain >  Changing plot axes limit in a loop
Changing plot axes limit in a loop

Time:03-17

I am working on dataframe. I am plotting temperature vs time. Usually my temperature will be within 20 and 25 ,rarely it goes out of that range. I want to plots in such a way that when temperature is within 20 and 25 , my Y axis limit should be within 20 and 25 or else it should be between 0 and 50.

My current code looks like that

listofDF = [df_i for (_, df_i) in df.groupby(pd.Grouper(key="filename", freq="1D"))] #for dividing daraframe on basis of one day

for df  in ((listofDF)):
    if len(df)!= 0:
        y = df[' Temp']                 
        x = df['time']
        plot(x,y)
        plt.ylim(20,30)

I want something like this

listofDF = [df_i for (_, df_i) in df.groupby(pd.Grouper(key="filename", freq="1D"))] #for dividing daraframe on basis of one day

for df  in ((listofDF)):
    if len(df)!= 0:
        y = df[' Temp']                 
        x = df['time']
        plot(x,y)
        if y.between(20,25):
           plt.ylim(20,25)
        else:
           plt.ylim(0,50) 

I tried this code and I got error as " The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()." . Can anyone please help me

CodePudding user response:

It throws that error because y.between returns an array with booleans including True if the value is between your boundaries. You are using the if statement to check the whole returned array, which is not directly possible. Instead, you can use all to check if ALL values in that array are true or not:

if all(y.between(20,25)):
    plt.ylim(20, 25)
  • Related