[Numpy-discussion] Line of best fit!

Lane Brooks lbrooks@MIT....
Tue Dec 9 05:35:11 CST 2008


James wrote:
> Hi,
>
> Thanks for all your help so far!
>
> Right i think it would be easier to just show you the chart i have so far;
>
> --------------------------
> import numpy as np
> import matplotlib.pyplot as plt
>
> plt.plot([4,8,12,16,20,24], [0.008,0.016,0.021,0.038,0.062,0.116], 'bo')
>
> plt.xlabel("F (Number of washers)")
> plt.ylabel("v^2/r ms-2")
> plt.title("Circular Motion")
> plt.axis([2,26,0,0.120])
>
> plt.show()
>
> ------------------------
>
> Very basic i know, all i wish to do is add a line of best fit based on 
> that data, in the examples there seems to be far more variables, do i 
> need to split my data up etc?
>   

Here is how I would do it:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([4,8,12,16,20,24])
y = np.array([0.008,0.016,0.021,0.038,0.062,0.116])

m = np.polyfit(x, y, 1)

yfit = np.polyval(m, x)

plt.plot(x, y, 'bo', x, yfit, 'k')

plt.xlabel("F (Number of washers)")
plt.ylabel("v2/r ms-2")
plt.title("Circular Motion")
plt.axis([2,26,0,0.120])

plt.text(5, 0.06, "Slope=%f" % m[0])
plt.text(5, 0.05, "Offset=%f" % m[1])
plt.show()



More information about the Numpy-discussion mailing list