1

New to Python, trying to plot linear regression of two lists. This is what I have so far:

#!/usr/bin/python

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import arange,array,ones#,random,linalg
from pylab import plot,show
from scipy import stats
from sys import argv

a = argv[1]
b = argv[2]

list1 = open(a)
list2 = open(b)

xi = list1.read().splitlines()
y = list2.read().splitlines()

slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)

print 'r value', r_value

line = slope*xi+intercept
plot(xi,line,'r-',xi,y,'o')
plt.savefig('myfig')

I get the following error:

Traceback (most recent call last):
  File "plot.py", line 21, in <module>
    slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/scipy/stats/stats.py", line 3007, in linregress                                                                                         
    xmean = np.mean(x,None)                                                                             
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/numpy/core/fromnumeric.py", line 2727, in mean                                                                                          
    out=out, keepdims=keepdims)                                                                         
  File "/export/apps/Python/2.7.2-CentOS6.0/lib/python2.7/site-packages/numpy/core/_methods.py", line 66, in _mean                                                                                              
    ret = umr_sum(arr, axis, dtype, out, keepdims)                                                      
TypeError: cannot perform reduce with flexible type 

1 Answer 1

1

My guess would be that it's not kosher to pass in a list of strings to linregress. Try converting them to floats first:

xi = [float(xk) for xk in xi]
y = [float(yk) for yk in y]
slope, intercept, r_value, p_value, std_err = stats.linregress(xi,y)

Depending on what's in xi and y, you might have to strip some empty strings first, or otherwise sanitize the input.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, it worked! I also had to clear empty strings like you mentioned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.