Skip to content
Advertisement

How to fit a power law to the dataframe and plot it?

I have two columns(rcs,range) in a dataframe.

rcs range
-40 12.9
-35 14.9
-30 22.9
-25 35.44
-20 43.48
-15 62.4
-10 92.4
-5 132.99
0 182.6
5 252.99

I want to plot a curve with equation rcs = range^4

I tried the following 1.as a polynomial curve fitting

def curve_gen(x,a,b,c,d,e):  #for polynomial
    return (a*(x**4))+(b*(x**3))+(c*(x**2))+(d*x)+e

y = df['rcs'].values
x = df['range'].values
pop,_ = curve_fit(curve_gen,x,y)
a,b,c,d,e = pop
pl.scatter(y,x)
pl.plot(curve_gen(x,a,b,c,d,e),x,color = 'red')
pl.show()

enter image description here in the above plot,the curve is not a smooth curve and is not starting from -40

2.power law curve fit

def power_law(x,a):  
    return a*np.power(x,4)

y = df['rcs'].values
x = df['range'].values
pop,_ = curve_fit(power_law,x,y)
a = pop
pl.scatter(y,x)
pl.plot(power_law(x,a),x,color = 'red')
pl.show()

this one giving me a wrong plot.the red line is not passing through the blue points enter image description here

how to solve the above issue using curve_fit?and plot

Advertisement

Answer

You can use numpy.polyfit and numpy.poly1d:

# initial data
plt.plot(df['rcs'], df['range'], marker='o', ls='', label='data')

# fit
fit = np.polyfit(df['rcs'], df['range'], deg=4)
# array([1.87062937e-05, 4.24655012e-03, 3.34652273e-01, 1.20759569e+01,
#        1.83604091e+02])

# get X range
X = np.arange(df['rcs'].min(), df['rcs'].max()+1)
# plot mapped fit onto X
plt.plot(X, np.poly1d(fit)(X), label='fit')

output:

polynomial fit

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement