简体   繁体   中英

Fit exponential curve to data points to calculate decay rate

I have a set of data points that looks like this:

x = [0, 2, 4, 7] 
y = [100, 62, 60, 56]

and I need to fit an exponential curve that follows the following equation:

C = C0 * e^(-kdecay*t)

where C is y, C0 is the value of y at the time point 0, and t is x.

At the moment I have the code to plot the time points, but I need to add the exponential curve.

plt.plot(x,y,color='indianred', ls='none', linewidth=2)
plt.errorbar(x,y,yerr,marker='o', color='indianred', ls='none', ecolor='k')

#set y axis limits
plt.ylim((0,120))

plt.xlabel("ActD (h)", fontsize=14)
plt.ylabel("mRNA (%)", fontsize=14)

Many thanks in advance for your help.

EDIT: I was trying this

from scipy.optimize import curve_fit

def func(C, kdecay, x):
    y= C*np.exp(-kdecay*x)
    return y
popt, _ = curve_fit(func, x, y)
C, kdecay = pop

I probably miss this part, since it's not in the same shape as my function:

print('y=%.5f*x+%.5f'%(C,kdecay))

I'm really new with Python, if you could give me a clear answer instead of just suggesting a library it would be really helpful.

If you're familiar with least squares, you can convert your equation to a valid form for LS by taking a logarithm:

y(t) = a * e^(-b*t)

becomes

ln(y(t)) = ln(a) - b*t

In terms of logarithms, this is a simple linear equation for t .

Luckily, scipy can do that for you:

from scipy.optimize import curve_fit
import numpy as np

def your_function(t, a, b):
    return a * np.exp(-b*t)

x = [0, 2, 4, 7] 
y = [100, 62, 60, 56]

best_params = curve_fit(your_function, x, y)
print(best_params)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM