Search code examples
pythonmatplotlibplotpolynomials

How to plot a polynomial regression


I have a polynomial matrix of degree 2 like this.

print(X)

[[  1.   5.  25.]
 [  1.   6.  36.]
 [  1.   7.  49.]
 [  1.   8.  64.]
 [  1.   9.  81.]
 [  1.  10. 100.]
 [  1.  11. 121.]
 [  1.  12. 144.]
 [  1.  13. 169.]
 [  1.  14. 196.]]

And a Matrix W with the intercept and coef values for my matrix X like this:

W = np.linalg.inv( X.T @ X ) @ X.T @ Y
print(W)
[73.55928788 -8.88859848  0.82670455]

I also have my y_P (values predicted for my whole matrix). Like this.

Y_p = W @ X.T
Y_p

array([ 49.78390909,  49.98906061,  51.84762121,  55.35959091,
        60.5249697 ,  67.34375758,  75.81595455,  85.94156061,
        97.72057576, 111.153     ])

I have this plot for the real data for X and Y.

# --- Showing the plot (2)
plt.plot(X, Y, c='orange', linestyle='dashed', 
         marker='o', markerfacecolor='#ac00e6')
plt.xlabel('Year')
plt.ylabel('Av_claims')
plt.legend('Claims')
plt.grid(True)

So I'd like to graph the line of each Y predicted by each X value over this previous plot in order to visualizate how sucessfull my model is. But I'm not sure who to do that. Could you help me? Thanks!

Data:

enter image description here

And plot

enter image description here

The blue line, is a linear regression, and now I'd like to do the same stuff with my polynomial regression.


Solution

  • You mean something like this?

    plt.plot(X, Y, c='orange', linestyle='dashed', 
             marker='o', markerfacecolor='#ac00e6')
    plt.plot(X, Y_p)
    plt.xlabel('Year')
    plt.ylabel('Av_claims')
    plt.legend('Claims')
    plt.grid(True)