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
JavaScript
x
12
12
1
def curve_gen(x,a,b,c,d,e): #for polynomial
2
return (a*(x**4))+(b*(x**3))+(c*(x**2))+(d*x)+e
3
4
y = df['rcs'].values
5
x = df['range'].values
6
pop,_ = curve_fit(curve_gen,x,y)
7
a,b,c,d,e = pop
8
pl.scatter(y,x)
9
pl.plot(curve_gen(x,a,b,c,d,e),x,color = 'red')
10
pl.show()
11
12
in the above plot,the curve is not a smooth curve and is not starting from -40
2.power law curve fit
JavaScript
1
11
11
1
def power_law(x,a):
2
return a*np.power(x,4)
3
4
y = df['rcs'].values
5
x = df['range'].values
6
pop,_ = curve_fit(power_law,x,y)
7
a = pop
8
pl.scatter(y,x)
9
pl.plot(power_law(x,a),x,color = 'red')
10
pl.show()
11
this one giving me a wrong plot.the red line is not passing through the blue points
how to solve the above issue using curve_fit?and plot
Advertisement
Answer
You can use numpy.polyfit
and numpy.poly1d
:
JavaScript
1
13
13
1
# initial data
2
plt.plot(df['rcs'], df['range'], marker='o', ls='', label='data')
3
4
# fit
5
fit = np.polyfit(df['rcs'], df['range'], deg=4)
6
# array([1.87062937e-05, 4.24655012e-03, 3.34652273e-01, 1.20759569e+01,
7
# 1.83604091e+02])
8
9
# get X range
10
X = np.arange(df['rcs'].min(), df['rcs'].max()+1)
11
# plot mapped fit onto X
12
plt.plot(X, np.poly1d(fit)(X), label='fit')
13
output: