Home > Blockchain >  Plotting data and finding a line of best fit
Plotting data and finding a line of best fit

Time:04-06

It's a simple plot but the line of best fit code is something that I can't get to work. Please can someone help tell me what is wrong with it. My code:

x=[93850,92115,90400,88707]
y=[49,48,47,46]
def curve(x,m,c):
    y_=(m*x) c
    return y_
popt,pcov=curve_fit(curve,x,ydata=y,p0=[1.02,0])
plt.plot(x,curve(x,1,0))
plt.plot(x,m*x c)
plt.plot(x,y)

The error: enter image description here

CodePudding user response:

This error occurs because in your curve function, you are attempting to add a list and an int together. Your variable x is a list of ints, so the expression (m * x) returns a list, which means (m * x) c is equivalent to <a list> c.

Logically, the expression <some list> 3 doesn't really make sense, because we don't know how to relate the list and an arbitrary value. Python doesn't know what to do with it either, thus the error.

You can replicate this error in 3 lines of code to see for yourself:

foo = ['a', 'b']
bar = 5
output = foo   bar
#TypeError: can only concatenate list (not "int") to list

It seems like what you are trying to do is apply your curve function to every element of x, in which case you can use a list comprehension. An example could be:

x=[93850,92115,90400,88707]

def curve(x,m,c):
    y_=(m*x) c
    return y_

x_curve = list(curve(i) for i in x)
plt.plot(x, x_curve)

CodePudding user response:

If I've understand right you wish to achieve something like that:

# pip install matplotlib

import matplotlib.pyplot as plt

x = [93850,92115,90400,88707]
y = [49,48,47,46]


def curve(x,m,c):
    return [(i*m) c for i in x]

plt.plot(x, curve(x,1,0))
plt.plot(x, y)

plt.show() 

Returns

enter image description here

  • Related