Getting second-degree polynomial for the curve fitting by changing slightly the code I write for linear regression

Viewed 2653
import matplotlib.pyplot as plt
import numpy as np
sales=np.array([72,180,279,378,495,585,693,792,855,873,801,648,612,477,396])
indexes=np.arange(1,16)

plt.plot(indexes,sales,'ro',label='Projected Sales')

m,b=np.polyfit(indexes,sales,1)
plt.plot(indexes,m*indexes+b,color='blue',label='Best Fit - Projected Sales')

plt.legend()

Hello, the code I write works to draw the linear regression, but I need second-degree polynomial for the curve fitting. There is so many different solutions for it, but I'd like to have a code for second-degree plynomial, which is not so different the code I write for linear regression. I mean, I want to change my code for linear regression slightly and get the polynomial curve, I don't need a completely new code, please pay attention to that, thanks.

1 Answers

Numpy provides with polyval the corresponding evaluation function for polyfit:

import matplotlib.pyplot as plt
import numpy as np
sales=np.array([72,180,279,378,495,585,693,792,855,873,801,648,612,477,396])
indexes=np.arange(1,16)

plt.plot(indexes,sales,'ro',label='Projected Sales')

p = np.polyfit(indexes,sales,2)
plt.plot(indexes,np.polyval(p, indexes),color='blue',label='Best Fit - Projected Sales')

plt.legend()
plt.show()

Sample output: enter image description here

Obviously, the graphic representation is lacking finesse because you only evaluate your curve on your data points. A better approach would be:

....
p = np.polyfit(indexes,sales,2)

xfit=np.linspace(min(indexes),max(indexes), 1000)
yfit=np.polyval(p, xfit)
plt.plot(xfit,yfit,color='blue',label='Best Fit - Projected Sales')

plt.legend()
plt.show()

Sample output: enter image description here

Related