Linear regression with matplotlib / numpy

I am trying to create a linear regression on a scatter chart that I created, however my data is in list format and all the examples that I can find when using polyfit require the use of arange . arange does not accept lists. I searched high and low on how to convert a list to an array, and nothing seems clear. Did I miss something?

Further, what is the best way to use my list of integers as contributions to polyfit ?

here is an example of polyphyte that I follow:

 from pylab import * x = arange(data) y = arange(data) m,b = polyfit(x, y, 1) plot(x, y, 'yo', x, m*x+b, '--k') show() 
+75
python numpy matplotlib linear-regression curve-fitting
May 27 '11 at 5:32 a.m.
source share
3 answers

arange generates lists (well, numpy arrays); type help(np.arange) for details. You do not need to call it in existing lists.

 >>> x = [1,2,3,4] >>> y = [3,5,7,9] >>> >>> m,b = np.polyfit(x, y, 1) >>> m 2.0000000000000009 >>> b 0.99999999999999833 

I should add that I prefer to use poly1d here instead of writing "m * x + b" and higher order equivalents, so my version of your code will look something like this:

 import numpy as np import matplotlib.pyplot as plt x = [1,2,3,4] y = [3,5,7,10] # 10, not 9, so the fit isn't perfect fit = np.polyfit(x,y,1) fit_fn = np.poly1d(fit) # fit_fn is now a function which takes in x and returns an estimate for y plt.plot(x,y, 'yo', x, fit_fn(x), '--k') plt.xlim(0, 5) plt.ylim(0, 12) 
+160
May 27 '11 at 5:47 a.m.
source share

This code:

 from scipy.stats import linregress linregress(x,y) #x and y are arrays or lists. 

produces a list with the following:

tilt: float
regression line slope
interception: float
regression line interception
r value: float
correlation coefficient
p value: float
two-way p-value for a hypothesis test, the null hypothesis of which is that the slope is zero stderr: float
Standard error of estimation

Source

+35
Dec 08 '14 at 17:37
source share

Another quick and dirty answer is that you can simply convert your list to an array using:

 import numpy as np arr = np.asarray(listname) 
+1
Sep 15 '14 at 20:26
source share



All Articles