[Numpy-discussion] Line of best fit!

Angus McMorland amcmorl@gmail....
Mon Dec 8 18:00:16 CST 2008

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

Line 1 creates an array with the x values I have. Line 2 creates some
random "data" I want to fit, which, in this case happens to be
normally distributed around the unity line y=x. The raw data is
plotted (assuming you have matplotlib installed as well - I suggest
you do) by line 3, with blue circles.

Line 4 calculates the coefficients giving the least-squares best fit
to a first degree polynomial (i.e. a straight line y = c0 * x + c1).
So the values of coefs are c0 and c1 in the previous equation.

Line 5 calculates the y values on the fitted polynomial, at given x
values, from the coefficients calculated in line 4, and line 6 simply
plots these fitted y values, using a dotted blue line.

I hope that helps get you started. Keep posting questions on specific
issues as they arise, and we'll see what we can do to help.

AJC McMorland
Post-doctoral research fellow
Neurobiology, University of Pittsburgh

More information about the Numpy-discussion mailing list