I am attempting to plot a regression line based on the below. This code works; however it plots the regression line to the right of the scatter plot.
My question is how do we get the regression line to plot correctly. I borrowed the plotting code from this website.
http://matthiaseisen.com/pp/patterns/p0170/
import numpy.linalg
import matplotlib.pyplot as plt
def regression_model():
L_1 = numpy.array([38.83, 37.8, 34.41, 30.95, 23.00, 31.75, 36.59, 41.15])
y_d = [1,2,3,4,5,6,7,8]
n=len(L_1)
B=numpy.array(y_d)
A=numpy.array(([[L_1[j], 1] for j in range(n)]))
X=numpy.linalg.lstsq(A,B)[0]
a=X[0]; b=X[1]
print ("Line is: y=",a,"x+",b)
r_9 = a * L_1[7] + 4.92
print ('Predicited value at period 9 is ' + str(r_9) + ' using regression')
fig, ax = plt.subplots()
fit = numpy.polyfit(y_d, L_1, deg=1)
ax.plot(L_1, fit[0] * L_1 + fit[1], color='red')
ax.scatter(y_d, L_1)
plt.show()
y_don the x axis, so:ax.plot(y_d, fit[0] * L_1 + fit[1], color='red')