0

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() 
1
  • I think you want y_d on the x axis, so: ax.plot(y_d, fit[0] * L_1 + fit[1], color='red') Commented Dec 12, 2017 at 12:41

1 Answer 1

1

You plotted that line against your Y-axis L_1, whereas what you need is the X-axis y_d. We need a numpy array for that to work, but you already have one:

fit = numpy.polyfit(y_d, L_1, deg=1)
ax.plot(B, fit[0] * B + fit[1], color='red')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.