Search code examples
python-3.xmatplotlibanacondacurve-fittingerrorbar

How to get fitted curve for errorbar graph for several text files


I have written a code for getting errorbar and curve fitted line. But I am getting an error. I have tried this curve fitted line code from see the answer from this webpage but it is not working for me. Can you help me with it?

My Code:

#!/home/zahid/anaconda3/bin/python
import numpy as np
import matplotlib.pyplot as plt
import numpy
from scipy.optimize import curve_fit


x1, y1, y2,y3,y4,y5,y6 = [], [], [],[],[], [], [],[],[], [], [],[]

with open("1_peak.txt") as f:
    for line in f:
    cols = line.split()
    x1.append(float(cols[0]))
    y1.append(float(cols[2]))

with open("2_peak.txt") as f:
    for line in f:
    cols = line.split()
    x2.append(float(cols[0]))
    y2.append(float(cols[2]))
.
.
.

with open("6_peak.txt") as f:
    for line in f:
    cols = line.split()
    x6.append(float(cols[0]))
    y6.append(float(cols[2]))


for item_a, item_b, item_d, item_e, item_f, item_g, item_c in zip(y1, y2,y3,y4,y5,y6, x1):


 B = (item_a + item_b + item_d + item_e + item_f + item_g)/6
 arr = numpy.array([item_a, item_b, item_d, item_e, item_f, item_g])
 C = numpy.mean(arr, axis=0)
 D = numpy.std(arr, axis=0)

 print (item_c, C , D)

 x = np.array(item_c)
 y = np.array(C) 
 e = np.array(D)

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

 popt, pcov = curve_fit(line, x, y)
 plt.errorbar(x, y, e, linestyle='None', marker='^')
 xfine = np.linspace(0., 100., 100)  
 plt.plot(xfine, line(xfine, popt[0], popt[1]), 'r-')
 plt.xlabel('PKA_energy in keV')
 plt.ylabel('intersitial')
 plt.savefig("1.jpeg", dpi=500)

I am getting below error:

Traceback (most recent call last):
File "./value_analysis_peak_SIA_energy.py", line 70, in <module>
popt, pcov = curve_fit(line, x, y)
File "/home/zahid/anaconda3/lib/python3.6/site-packages/scipy/optimize/minpack.py", line 736, in curve_fit
res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
File "/home/zahid/anaconda3/lib/python3.6/site-packages/scipy/optimize/minpack.py", line 380, in leastsq
raise TypeError('Improper input: N=%s must not exceed M=%s' % (n, m))
TypeError: Improper input: N=2 must not exceed M=1

Solution

  • I think this is similar to what you want to do, please try it and modify as needed for your work. Here I use a quadratic curve to fit the data, the polynomial order is set at the top of the code.

    plot

    #!/home/zahid/anaconda3/bin/python
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    
    
    polynomialOrder = 2 # example quadratic
    
    x1 = []
    x2 = []
    x6 = []
    
    y1 = []
    y2 = []
    y6 = []
    
    
    # load the raw data
    with open("1_peak.txt") as f:
        for line in f:
            cols = line.split()
            x1.append(float(cols[0]))
            y1.append(float(cols[2]))
    
    with open("2_peak.txt") as f:
        for line in f:
            cols = line.split()
            x2.append(float(cols[0]))
            y2.append(float(cols[2]))
    
    with open("6_peak.txt") as f:
        for line in f:
            cols = line.split()
            x6.append(float(cols[0]))
            y6.append(float(cols[2]))
    
    
    # fit each data set to individual polynomials
    parms1 = np.polyfit(x1, y1, polynomialOrder)
    parms2 = np.polyfit(x2, y2, polynomialOrder)
    parms6 = np.polyfit(x6, y6, polynomialOrder)
    
    
    # calculate errors for each fit
    err1 = np.polyval(parms1, x1) - y1
    err2 = np.polyval(parms2, x2) - y2
    err6 = np.polyval(parms6, x6) - y6
    
    
    # graph size is set before calling plot commands
    graphWidth = 800 # pixels
    graphHeight = 600 # pixels
    plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    
    
    # plot the raw data as error-bar scatter plots
    plt.errorbar(x1, y1, err1, linestyle='None', marker='^')
    plt.errorbar(x2, y2, err2, linestyle='None', marker='^')
    plt.errorbar(x6, y6, err6, linestyle='None', marker='^')
    
    
    # plot the fitted polynomials
    xmodel1 = np.linspace(min(x1), max(x1))
    ymodel1 = np.polyval(parms1, xmodel1)
    
    xmodel2 = np.linspace(min(x2), max(x2))
    ymodel2 = np.polyval(parms2, xmodel2)
    
    xmodel6 = np.linspace(min(x6), max(x6))
    ymodel6 = np.polyval(parms6, xmodel6)
    
    plt.plot(xmodel1, ymodel1)
    plt.plot(xmodel2, ymodel2)
    plt.plot(xmodel6, ymodel6)
    
    
    # final code here
    plt.xlabel('PKA_energy in keV')
    plt.ylabel('intersitial')
    
    plt.show()
    
    
    
    '''
    popt, pcov = curve_fit(line, x, y)
    plt.errorbar(x, y, e, linestyle='None', marker='^')
    xfine = np.linspace(0., 100., 100)  
    plt.plot(xfine, line(xfine, popt[0], popt[1]), 'r-')
    plt.xlabel('PKA_energy in keV')
    plt.ylabel('intersitial')
    #plt.savefig("1.jpeg", dpi=500)
    plt.show()
    '''