How to fit polynomial to data with error bars

后端 未结 3 2400
旧时难觅i
旧时难觅i 2021-02-20 16:17

I am currently using numpy.polyfit(x,y,deg) to fit a polynomial to experimental data. I would however like to fit a polynomial that uses weighting based on the errors of the poi

3条回答
  •  孤城傲影
    2021-02-20 16:43

    Here is how I did it, with lots of comments!

    Note: I did it with qth and nth order polynomial fits.

    from numpy import *
    import pylab
    
    # get data
    fn = 'cooltemp.dat'
    x, y, xerr, yerr = loadtxt(fn,unpack=True, usecols=[0,1,2,3])
    
    # create nth degree polynomial fit
    n = 1
    zn = polyfit(x,y,n) 
    pn = poly1d(zn) # construct polynomial 
    
    # create qth degree polynomial fit
    q = 5
    zq = polyfit(x,y,q) 
    pq = poly1d(zq)
    
    # plot data and fit
    xx = linspace(0, max(x), 500)
    pylab.plot(xx, pn(xx),'-g', xx, pq(xx),'-b')
    pylab.errorbar(x, y, xerr, yerr, fmt='r.')
    
    # customise graph
    pylab.legend(['degree '+str(n),'degree '+str(q),'data'])
    pylab.axis([0,max(x),0,max(y)])
    pylab.xlabel('x label (unit)')
    pylab.ylabel('y label (unit)')
    
    pylab.show()
    

提交回复
热议问题