Home > database >  Plotting two fitted regression lines before and after a cutoff in matplotlib
Plotting two fitted regression lines before and after a cutoff in matplotlib

Time:08-12

I want to estimate two different regression lines for before and after a cutoff. With the following code, I managed to estimate the regression lines but I do not get them in the right place. How would you put the red line as the regression line after the cutof at around 250?

#Creating subsets from before and after the cutoff
df_before = df_diff.loc[(df_diff["trade_date"] <= pd.datetime(2019,1,1))]
df_after = df_diff.loc[(df_diff["trade_date"] >= pd.datetime(2018,12,31))]

#Estimating before regression line
df_before = df_before.reset_index()
x=np.arange(df_before["trade_date"].size)
fit_before = np.polyfit(x, df_before["rate_diff"],1)
fit_before_fn =np.poly1d(fit_before)

#Estimating after regression line
df_after = df_after.reset_index()
y=np.arange(df_after["trade_date"].size)
fit_after = np.polyfit(y, df_after["rate_diff"],1)
fit_after_fn =np.poly1d(fit_after)

#Plotting the graph 
fig, ax = plt.subplots()
plt.title('')
ax.plot(df_diff["rate_diff"])
ax.plot(fit_before_fn(x), label ="before")
ax.plot(fit_after_fn(y), label="after")
ax.legend(loc = "best")

enter image description here

CodePudding user response:

Specify the x-coordinates in ax.plot(), e.g. like this

import matplotlib.pyplot as plt 
import random
fig, ax = plt.subplots(1,1)
ax.plot(x=range(50), y=random.sample(range(100),50), color="black") #  all data
ax.plot(x=range(25), y=random.sample(range(100),25), color="red") # before line
ax.plot(x=range(25, 50), y=random.sample(range(100),25), color="blue") # after line
plt.show()
  • Related