pythonnumpymatplotlibgraphbest-fit

Error when entering values for a scatter fit


The code: there's a problem with the 5th line it seems, in particular with np.polyfit,

i = text_i.get()
r = text_r.get()
i = i.split(", ")
r = r.split(", ")        

fit = np.polyfit(i,r,1)
fit_fn = np.poly1d(fit) 
plt.plot(i,r, 'yo', i, fit_fn(i), '--k')
plt.ilim(0, 5)
plt.rlim(0, 12)

Error message

    fit = np.polyfit(i,r,1)
  File "C:\Python27\lib\site-packages\numpy\lib\polynomial.py", line 546, in polyfit
    x = NX.asarray(x) + 0.0
TypeError: ufunc 'add' did not contain a loop with signature matching types 
dtype('S32') dtype('S32') dtype('S32')

Please find what's wrong with the code?


Solution

  • np.polyfit(x,y,1) needs a list or array of numerical data as input for its arguments x and y. What you type in, however, is some string. So you need to split that string and convert each of its elements to a number before passing it to polyfit. Try:

    i = np.array(list(map(float, i.split(", "))))