In python, how to fit linear slope to a graph in a specified range of x values? -
for example, here data set:
x: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
y: 20, 21, 22, 26, 32, 41, 39, 36, 29, 23
i think i'm supposed using numpy polyfit
function, not sure. how can i, example, linear fit between x(3)
, x(6)
?
just calculating in head, should like: rise/run = (41-22)/(6-3) = 6.3333333...
i'm dealing different data sets each time read in .txt
files, appreciate if showed me general method this, apply future datasets.
i assume want least square fit, polyfit give you.
to achieve that, pass 2 lists polyfit, x values, y values , have set order of polynomial want. example, turn out be
import numpy np x = [3, 6] y = [22, 41] coeffs = np.polyfit(x, y, 1) # y values of resulting line x = np.arange(1,11) y_line = x * coeffs[0] + coeffs[1]
with regard further questions, need think output of polyfit.
the documentation numpy.polyfit
says
the solution minimizes squared error
e = \sum_{j=0}^k |p(x_j) - y_j|^2
in equations:
x[0]**n * p[0] + ... + x[0] * p[n-1] + p[n] = y[0]
x1**n * p[0] + ... + x1 * p[n-1] + p[n] = y1
...
x[k]**n * p[0] + ... + x[k] * p[n-1] + p[n] = y[k]
we using simplified case, because straight line, have polynomial of first order, is, n=1
.
that means in our case, equation y
y[k] = x[k]*p[0]+p[1]
. compare general form of line equation y = k*x+d
. see slope of line coeffs[0]
.
as plotting, see following example
import numpy np matplotlib import pyplot plt x = np.arange(1, 11) y = [20, 21, 22, 26, 32, 41, 39, 36, 29, 23] poly = np.polyfit(x, y, 1) y_line = x * poly[0] + poly[1] print poly[0] plt.scatter(x, y) plt.plot(x, y_line) plt.show()
which results in output
$ python test.py 1.21818181818
Comments
Post a Comment