# [Tutor] Polyfit works like this

Eike Welk eike.welk at gmx.net
Wed Dec 2 09:49:53 CET 2009

```On Tuesday 01 December 2009, questions anon wrote:
> I would now like to add a line of best fit. I think the command is
> polyfit()??
> But I can't seem to get it to work

These are the steps to make polyval work. I typed it into
an 'ipython -pylab' session; I hope I included all relevant lines and
I removed some of the output:

#this is the input data
In [13]:d_x = [0, 0.1, 0.3, 0.5, 0.7, 1, 1.2, 1.5, 1.8, 2]
In [14]:d_y = [0.1, 0.11, 0.15, 0.3, 0.5, 0.8, 1, 1.2, 1.1, 1.2]

#show input data
In [15]:plot(d_x,d_y, label='data')

#make 2nd degree polynom, and plot smoothly with 50 points
In [17]:pol2 = polyfit(d_x, d_y, 2)
In [18]:p_x = linspace(0, 2, 50)
In [19]:p2_y = polyval(pol2, p_x)
In [20]:plot(p_x,p2_y, label='pol 2nd')

#also create line and plot it too (would not need 50 points)
In [21]:pol1 = polyfit(d_x, d_y, 1)
In [22]:p1_y = polyval(pol1, p_x)
In [24]:plot(p_x,p1_y, label='line')

#create legend so you can recognize the curves
In [25]:legend()

Eike.
```