I can't find a possiblity to tell curve_fit to only use x values within a specific range. I found the "bounds" parameter, but this only seems to apply to the parameters of my function.
When one has data, where you want to fit, for example, a linear curve (but only in a specific area of your data) you have to create a new list. Especially as pyplot.plot takes two separate lists for x and y values, while for manuall sorting out you need them as pairs of (x,y).
The easiest solution is indeed to create a new list, which is a filtered version of the original list. It is of course best to work with numpy arrays instead of python lists.
So assume to have two arrays x
and y
, of which you only want to fit those values where x is larger than some number a
to a function f
. You can filter and curve_fit
them as
x2 = x[x>a]
y2 = y[x>a]
popt2, _ = scipy.optimize.curve_fit(f, x2, y2 )
A complete example:
import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt
import scipy.optimize
x = np.linspace(-1,3)
y = x**2 + np.random.normal(size=len(x))
f = lambda x, a,b : a* x +b
popt, _ = scipy.optimize.curve_fit(f, x,y, p0=(1,0))
x2 = x[x>0.7]
y2 = y[x>0.7]
popt2, _ = scipy.optimize.curve_fit(f, x2,y2, p0=(1,0))
plt.plot(x,y, marker="o", ls="", ms=4, label="all data")
plt.plot(x, f(x, *popt), color="moccasin", label="fit all data")
plt.plot(x2, f(x2, *popt2), label="fit filtered data")
plt.legend()
plt.show()
Finally just to mention it, you can also connect several conditions using logical operators, like x[(x>0.7) & (x<2.5)]
.
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.