Jordan Osmaston
Jordan Osmaston

Reputation: 21

How can I place a best fit line to the plotted points?

I have a simple plot containing two datasets in arrays, and am trying to use regression to calculate a best fit line through the points.

However the line I am getting is way off to the left and up of the data points.

How I can get the line to be in the right place, and are there any other tips and suggestions to my code?

from pylab import *

Is = array([-13.74,-13.86,-13.32,-18.41,-23.83])
gra = array([31.98,29.41,28.12,34.28,40.09])
plot(gra,Is,'kx')
(m,b) = polyfit(Is,gra,1)
print(b)
print(m)
z = polyval([m,b],Is)
plot(Is,z,'k--')

If anyone is curious, the data is the bandgap of a silicon transistor at various temperatures.

Upvotes: 2

Views: 605

Answers (1)

hitzg
hitzg

Reputation: 12711

You have to be careful as to which of your arrays you pass as x coordinates and which as y coordinates. Consider that you have data values y at positions x. Then you have to evaluate the polynomial wrt. x too.

from pylab import*

Is = array([-13.74,-13.86,-13.32,-18.41,-23.83])
gra = array([31.98,29.41,28.12,34.28,40.09])

# rename the variables for clarity
x = gra
y = Is

plot(x, y, 'kx')
(m,b) = polyfit(x, y, 1)
print(b)
print(m)
z = polyval([m,b], x)
plot(x, z, 'k--')
show()

Upvotes: 2

Related Questions