How to derive equation from Numpy's polyfit?
<p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p>

<pre><code># calculate polynomial
z = np.polyfit(x, y, 5)
f = np.poly1d(z)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
</code></pre>

<p>How can I use the above to derive the actual equation for this curve?</p>

<p>If you want to show the equation, you can use <code>sympy</code> to output latex:</p>

<pre><code>from sympy import S, symbols
from matplotlib import pyplot as plt
import numpy as np

x=np.linspace(0,1,100)
y=np.sin(2 * np.pi * x)

p = np.polyfit(x, y, 5)
f = np.poly1d(p)

# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)

x = symbols("x")
poly = sum(S("{:6.2f}".format(v))*x**i for i, v in enumerate(p[::-1]))
eq_latex = sympy.printing.latex(poly)

plt.plot(x_new, y_new, label="${}$".format(eq_latex))
plt.legend(fontsize="small")
</code></pre>

<p>the result:</p>

<p><a href="http://i.stack.imgur.com/Q1h21.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q1h21.png" alt="enter image description here"></a></p>

python numpy