1

I am trying to fit my data points to exponential decay curve. So, my code is:

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt


x = np.array([54338, 54371, 54547])
y = np.array([6.37468,6.36120,6.34980])

# prepare some data
x1 = np.array([54324,54332,54496, 54620, 54752, 54861, 54913, 54914, 54915, 54913, 54974, 55026, 55117, 55117 ])
y1 = np.array([6.40873, 5.00000, 5.00000, 6.32667, 6.29763, 6.29971, 5.00000, 6.29771, 6.29687, 6.32965, 6.28848, 6.27450,6.31405,6.19976])

xall = np.array([54338, 54371, 54547,54324,54332,54496, 54620, 54752, 54861, 54913, 54914, 54915, 54913, 54974, 55026, 55117, 55117 ])
yall = np.array([6.37468,6.36120,6.34980,6.40873, 5.00000, 5.00000, 6.32667, 6.29763, 6.29971, 5.00000, 6.29771, 6.29687, 6.32965, 6.28848, 6.27450,6.31405,6.19976 ])

t0=54322.13
def h(x1,a,b,c):
    return a*np.exp(-(x1-t0)/b)+c
lendata= len(x)


popt,pcov = curve_fit(h,xall,yall)
y_fit =(h(xall, *popt))

fig = plt.figure()

plt.plot(x, y, color='#5e3c99', ls='None',marker='o')
plt.plot(x1, y1, color='#e66101',ls='None',marker='o')
plt.plot(xall, h(xall, *popt), color='#377eb8')



plt.show()

I practiced code from Scipy's documents. Everything looks okay, but I'm having the very strange line fit instead curve fit like that:

plot

I also checked this solution, but it did not help that much. What can be cause this problem?

Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
anniejcannon
  • 143
  • 9
  • 2
    FYI: `xall` is not sorted. For the plot of `xall, h(xall, *popt)` to make sense, the `x` argument must be sorted. The curve created by `plot` simply connects the points in the order given, so if the `x`-coordinates are not sorted, the curve jumps back and forth along the `x` axis. You could do something like `xs = np.sort(xall); plt.plot(xs, h(xs, *popt), color='#377eb8')` – Warren Weckesser Feb 11 '18 at 23:19
  • 3
    Visual unspection of the data to be fitted can often reveal data problems. In this case, the scatterplot shown in your image does not appear to be on a line that would be fitted by the equation you are using. – James Phillips Feb 12 '18 at 00:20
  • @WarrenWeckesser it became "L"-like shape now, not curvature again... – anniejcannon Feb 12 '18 at 06:27
  • @JamesPhillips it did not help... – anniejcannon Feb 12 '18 at 06:28
  • 2
    Are you sure you want to have the three outliers in (on `y=5.0`)? – Cleb Feb 12 '18 at 09:14
  • 2
    the problem is that you are trying to fit your data to a model that is not appropriate. The algorithm is actually doing a pretty good job but your exponential decay model is just not appropriate. – DrBwts Feb 12 '18 at 17:12

0 Answers0