标签:func 指定 nbsp legend scipy pac title numpy 数据
调用scipy包中的curve_fit,可以根据指定的函数形式,对一组已知自变量和因变量的数据进行曲线拟合。
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit # 自定义函数 def func(x, a, b): return a*pow(x, b) data = pd.read_excel(r‘C:\Users\YBM\Desktop\data.xlsx‘) x = data[‘x‘] y = data[‘y‘] popt, pcov = curve_fit(x, y) a = popt[0] b = popt[1] yvals = func(x, a, b) plot1 = plt.plot(x, y, ‘s‘, label=‘original values‘) plot2 = plt.plot(x, yvals, ‘r‘, label=‘polyfit values‘) plt.xlabel(‘x‘) plt.ylabel(‘y‘) plt.legend(loc=4) # 指定legend的位置在右下角 plt.title(‘curve_fit‘)
也可以定义三个参数的函数:
import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.optimize import curve_fit def func(x, a, b, c): return a * np.exp(-b * x) + c xdata = np.linspace(0, 4, 50) y = func(xdata, 2.5, 1.3, 0.5) y_noise = 0.2 * np.random.normal(size=xdata.size) ydata = y + y_noise plt.plot(xdata, ydata, ‘b-‘, label=‘data‘) popt, pcov = curve_fit(func, xdata, ydata) a = popt[0] b = popt[1] c = popt[2] yvals = func(xdata, a, b, c) plot1 = plt.plot(xdata, ydata, ‘s‘, label=‘original values‘) plot2 = plt.plot(xdata, yvals, ‘r‘, label=‘polyfit values‘) # 或: plt.plot(xdata, func(xdata, *popt), ‘r-‘, label=‘fit‘) # 限制参数范围:0<a<3, 0<b<2, 0<c<1 popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 2., 1.])) plt.plot(xdata, func(xdata, *popt), ‘r-‘, label=‘fit‘)
标签:func 指定 nbsp legend scipy pac title numpy 数据
原文地址:https://www.cnblogs.com/excellent123/p/11374535.html