Cubic Fit to Graph. How Do I create a better fit to my data and retrieve values from the fit?

515 views Asked by At

I have plotted some experimental data in Python and need to find a cubic fit to the data. The reason I need to do this is because the cubic fit will be used to remove background (in this case resistance in a diode) and you will be left with the evident features. Here is the code I am currently using to make the cubic fit in the first place, where Vnew and yone represent arrays of the experimental data.

answer1=raw_input ('Cubic Plot attempt?\n ')

    if answer1 in['y','Y','Yes']:


        def cubic(x,A):
            return A*x**3

        cubic_guess=array([40])               
        popt,pcov=curve_fit(cubic,Vnew,yone,cubic_guess)

        plot(Vnew,cubic(Vnew,*popt),'r-',label='Cubic Fit: curve_fit')
        #ylim(-0.05,0.05)   
        legend(loc='best')
        print 'Cubic plotted'
    else:
        print 'No Cubic Removal done'

I have knowledge of curve smoothing but only in theory. I do not know how to implement it. I would really appreciate any assistance.

Here is the graph generated so far:

1

There are 1 answers

0
Oliver W. On

To make the fitted curve "wider", you're looking for extrapolation. Although in this case, you could just make Vnew cover a larger interval, in which case you'd put this before your plot command:

Vnew = numpy.linspace(-1,1, 256)  # min and max are merely an example, based on your graph
plot(Vnew,cubic(Vnew,*popt),'r-',label='Cubic Fit: curve_fit')

"Blanking out" the feature you see, can be done with numpy's masked arrays but also just by removing those elements you don't want from both your original Vnew (which I'll call xone) and yone:

mask = (xone > 0.1) & (xone < 0.35)  # values between these voltages (?) need to be removed
xone = xone[numpy.logical_not(mask)]
yone = yone[numpy.logical_not(mask)]

Then redo the curve fitting:

popt,_ = curve_fit(cubic, xone, yone, cubic_guess)

This will have fitted only to the data that was actually there (which aren't that many points in your dataset, from the looks of it, so beware!).