Reputation: 1838
I have a textfile with x and y coordinates that I with this program want to calculate a curve with, however, the outcome is a straight line repeating itself The data is imported separately as x and y coordinates. Here is the code that would handle this data
def plotDots(t,x_acc,y_acc):
while x_acc and y_acc:
t.pu()
t.goto(x_acc[0],y_acc[0])
t.pd()
t.stamp()
x_acc, y_acc=x_acc[1:], y_acc[1:]
def plotRegression(x,x_acc,y_acc):
ave_x=sum(x_acc)/len(x_acc) #Calculating curve
ave_y=sum(y_acc)/len(y_acc)
n=len(x_acc)
m=((x_acc[0]*y_acc[0])-(n*ave_x*ave_y))/(x_acc[0]**2-(n-x_acc[0]**2))
y=ave_y+m*(x-ave_x)
return y
def main():
t=turtle.Turtle()
wn=turtle.Screen()
turtle.setworldcoordinates(-1000,-1000,1000,1000)
doc=open("labdata.txt")
line=doc.readline()
y_acc=[]
x_acc=[]
while line:
values=line.split()
x_acc=x_acc +[float(values[0])]
y_acc=y_acc +[float(values[1])]
line=doc.readline()
plotDots(t,x_acc,y_acc)
for x in x_acc:
t.goto(x, plotRegression(x,x_acc,y_acc))
doc.close()
wn.exitonclick()
main()
Upvotes: 0
Views: 6437
Reputation:
The way I read your script, you're fitting a linear line to the data. You are then drawing that fit, the linear line, since plotRegression
will return the value fitted value y
that belongs to your input x
(in `t.goto(...).
So it's wonder you see a straight line; you should see that.
Simple use
for x, y in zip(x_acc, y_acc):
t.goto(x, y)
to draw your curve.
calcRegression
that returns a
and b
, your fitted parameters, and then a evalRegression
that takes input x
(either a float or an array of floats) and returns y
.plotRegression
if it actually doesn't plot anything.
If it's just part of practice, no problem, but don't use it for real-world problems, since people have solved this before (and overall, more carefully and more detailed).
Upvotes: 1