Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

python linear fit

import matplotlib.pyplot as plt
import numpy as np
import itertools
from scipy import optimize


data = np.loadtxt('linear.dat', skiprows = 1, delimiter = '	')
print data
x = data[:, 0]
y = data[:, 1:]
m = y.shape[0]
n = y.shape[1]


def linear_fit(x, a, b):
    return a * x + b

y_fit = np.empty(shape=(m, n))


for i in range(n):
    fit_y_fit_a, fit_y_fit_b = optimize.curve_fit(linear_fit, x, y[:, i])[0]
    y_fit[:, i] = fit_y_fit_a * x + fit_y_fit_b

y[~np.isfinite(y)] = 0
y_mean = np.mean(y, axis = 1)

fig = plt.figure(figsize=(5, 5))
fig.clf()
plot_y_vs_x = plt.subplot(111)
markers = itertools.cycle(('o', '^', 's', 'v', 'h', '>', 'p', '<'))
for i in range(n):
    plot_y_vs_x.plot(x, y, linestyle = '', marker = markers.next(), alpha = 1, zorder = 2)
    # plot_y_vs_x.plot(x, y_fit, linestyle = ':', color = 'gray', linewidth = 0.5, zorder = 1)
    plot_y_vs_x.plot(x, y_mean, linestyle = '-', linewidth = 3.0, color = 'red', zorder = 3)
plot_y_vs_x.set_ylim([-10, 10])
plot_y_vs_x.set_ylabel('Y', labelpad = 6)
plot_y_vs_x.set_xlabel('X', labelpad = 6)
fig.savefig('plot.pdf')
plt.close()
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #python #linear #fit
ADD COMMENT
Topic
Name
6+2 =