In [2]:
import numpy as np
import matplotlib.pyplot as plt

Linear fit


In [13]:
# generate data
n_points = 10
x = np.array(range(n_points))
y = np.array(range(n_points))
#lets make it more real
y[1] = 2
y[4] = 5
y[7] = 6

# perform the polynomial fit
z = np.polyfit(x, y, 1)
# use poly1d, an one-dimensional polynomial convenience class, to encapsulate “natural” operations on polynomials 
p = np.poly1d(z)

# add the fit line
xp = np.linspace(0, 10, 10)

#plot
_ = plt.plot(x, y, '.', xp, p(xp), '-')
plt.ylim(0,15)
plt.show()

print "The polynomial of the fit is: ", p


The polynomial of the fit is:   
0.9212 x + 0.4545

In [12]:
p


Out[12]:
poly1d([ 0.92121212,  0.45454545])

Polynomial fit of higher degree


In [14]:
# generate the data
x = np.array([0.0, 1.0, 2.0, 3.0,  4.0,  5.0])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])

# perform the fit 
z = np.polyfit(x, y, 3)
p = np.poly1d(z)

# plot
xp = np.linspace(-2, 6, 100)
_ = plt.plot(x, y, '.', xp, p(xp), '-')
plt.ylim(-2,2)
plt.show()

print "The polynomial of the fit is: ", p


The polynomial of the fit is:           3          2
0.08704 x - 0.8135 x + 1.693 x - 0.03968

In [ ]: