I have been trying to fit a function of the form to the data I was given:
160 0.277 0.006
170 0.2805 0.005
180 0.2825 0.007
190 0.276 0.012
200 0.2475 0.011
210 0.1645 0.009
220 0.1075 0.011
230 0.0785 0.009
240 0.0585 0.005
250 0.048 0.002
260 0.046 0.002
270 0.0485 0.001
280 0.0555 0.001
290 0.078 0.002
300 0.113 0.002
310 0.161 0.01
320 0.262 0.008
330 0.3035 0.005
340 0.326 0.004
350 0.3305 0.007
360 0.336 0.006
10 0.3275 0.005
20 0.3075 0.007
30 0.231 0.012
40 0.1625 0.005
50 0.1205 0.003
60 0.0905 0.003
70 0.0775 0.001
80 0.075 0.002
90 0.077 0.002
100 0.079 0.004
110 0.0965 0.003
120 0.124 0.002
130 0.1695 0.003
140 0.281 0.004
150 0.32 0.002
This is the code I wrote:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import special as sp
def strt(x, a, b):
"""definition of a straight line"""
return a*x+b
def trig(x, ang, I0, offset):
"""cos function to be fit"""
return offset+(I0*(sp.cosdg(x-ang)**2))
"""file handler block"""
f=open(r"C:\Users\lenovo\Desktop\trials.txt", "r")
raw=f.readlines()
data=np.loadtxt(raw)
data=np.transpose(data)
f.close()
"""fitting block"""
popt1, pcov1 = curve_fit(trig, data[0], data[1])
print(popt1)
#print(pcov1)
perr1 = np.sqrt(np.diag(pcov1))
print(perr1)
xerror=[1]*len(data[0])
"""plotting block"""
plt.figure('a')
plt.scatter(data[0], (data[1]), c='b', label="Data")
plt.plot(data[0], trig(data[0], *popt1), 'b-', label='fit: a=%5.3f, b=%5.3f c=%5.3f; sigma a=%5.3e, sigma b=%5.3e, sigma c=%5.3e' %tuple(list(popt1)+list(perr1)))
#plt.plot(data[0], trig(data[0], *popt1), 'b-', label='fit: a=%5.3f; sigma a=%5.3e' %tuple(list(popt1)+list(perr1)))
plt.xlabel('Angle (degrees)', fontsize=20)
plt.errorbar(data[0], data[1], fmt='none', xerr=xerror, yerr=data[2], ecolor='b', markersize=8, capsize=5)
#plt.xlim([-0.0075, 0.0075])
#plt.ylim([-3, 50])
plt.ylabel('Power ($\mu$W)', fontsize=20)
plt.legend(prop={"size":15}, loc='upper left')
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.show('a')
The fit looks fine but for some reason, the image has a straight line running from end to end of the curve. Which I think means that the function gives two outputs for each input. I want to know why this is happening and how can I amend it. I tried to fit just a cos function and the output image would still a have straight line running from end to end. Could someone please help? output image
I was able to solve this issue: the data should be listed in increasing order and the list above starts in the middle.