<jupyter_start><jupyter_text>Method 1: polyfit()<jupyter_code>m_fit, b_fit = np.poly1d(np.polyfit(x,y,1,w=1./y_err))   #weight with uncertainties
print(m_fit, b_fit)

y_fit = m_fit*x + b_fit
f = plt.figure(figsize=(7,7))
plt.errorbar(x,y,yerr=y_err,fmt='o',label='data')
plt.plot(x,y_fit,label='fit')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=2,frameon=False)<jupyter_output><empty_output><jupyter_text>Method 2: scipy + optimize<jupyter_code>#import optimize from scipy
from scipy import optimize

#define the function to fit
def f_line(x,m,b):
    return m*x + b

#perform the fit
params, params_cov = optimize.curve_fit(f_line,x,y,sigma=y_err)

m_fit = params[0]
b_fit = params[1]
print(m_fit,b_fit)
f = plt.figure(figsize=(7,7))
plt.errorbar(x,y,yerr=y_err,fmt='o',label='data')
plt.plot(x,y_fit,label='fit')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=2,frameon=False)<jupyter_output><empty_output><jupyter_text>More complicated data<jupyter_code>#redefine x and y
npoints = 50
x = np.linspace(0.,2*np.pi,npoints)

#make y a complicated function
a = 3.4
b = 2.1
c =0.27
d = -1.3
sig = 0.6

y = a*np.sin(b*x + c) + d + np.random.normal(scale=sig,size=npoints)
y_err = np.full(npoints,sig)

f = plt.figure(figsize=(7,7))
plt.errorbar(x,y,yerr=y_err,fmt='o')
plt.xlabel('x')
plt.ylabel('y')<jupyter_output><empty_output><jupyter_text>Using scipy.optimize.curve_fit()<jupyter_code>#import optimize from scipy
from scipy import optimize

#define the function to fit
def f_line(x,a,b,c,d):
    return a*np.sin(b*x + c) + d

#perform the fit - p0 values are your best guess for a,b,c,d
params, params_cov = optimize.curve_fit(f_line,x,y,sigma=y_err,p0=[1,2.,0.1,-0.1])

a_fit = params[0]
b_fit = params[1]
c_fit = params[2]
d_fit = params[3]

print(a_fit,b_fit,c_fit,d_fit)

y_fit = a_fit*np.sin(b_fit*x + c_fit) + d_fit
f = plt.figure(figsize=(7,7))
plt.errorbar(x,y,yerr=y_err,fmt='o',label='data')
plt.plot(x,y_fit,label='fit')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc=0,frameon=False)<jupyter_output><empty_output>