[Numpy-discussion] Line of best fit!

Scott Sinclair scott.sinclair.za@gmail....
Mon Dec 8 23:13:26 CST 2008


> 2008/12/9 Angus McMorland <amcmorl@gmail.com>:
> Hi James,
>
> 2008/12/8 James <james@fmnmedia.co.uk>:
>>
>> I have a very simple plot, and the lines join point to point, however i
>> would like to add a line of best fit now onto the chart, i am really new
>> to python etc, and didnt really understand those links!
>>
>> Can anyone help me :)
>
> It sounds like the second link, about linear regression, is a good
> place to start, and I've made a very simple example based on that:
>
> -----------------------------------------------
> import numpy as np
> import matplotlib.pyplot as plt
>
> x = np.linspace(0, 10, 11) #1
> data_y = np.random.normal(size=x.shape, loc=x, scale=2.5) #2
> plt.plot(x, data_y, 'bo') #3
>
> coefs = np.lib.polyfit(x, data_y, 1) #4
> fit_y = np.lib.polyval(coefs, x) #5
> plt.plot(x, fit_y, 'b--') #6
> ------------------------------------------------

James, you'll want to add an extra line to the above code snippet so
that Matplotlib displays the plot:

plt.show()

Cheers,
Scott


More information about the Numpy-discussion mailing list