我正在尝试用多项式曲线拟合2D数据点;参见下面的图片。蓝点是数据。蓝色虚线是拟合到这些点的2阶多项式。我想强迫拟合具有与黑线完全相同的形状,并且我要计算新拟合与黑曲线的y偏移。关于这怎么可能的任何想法?预先感谢。x = np.linspace(6.0,12.0,num=100)
a = -0.0864
b = 11.18
c = 9.04
fit_y = a*(x - b)**2 + c # black line
z = np.polyfit(data_x,data_y,2)
zfit=z[2]+z[1]*x+z[0]*x**2
fig, ax = plt.subplots()
ax.plot(data_x,data_y,'.',color='b')
ax.plot(x,fit_y,color='black') #curve of which we want the shape
ax.plot(x,zfit,color='blue',linestyle='dashed') #polynomial fit
ax.set_xlim([6.5,11.0])
ax.set_ylim([6.5,10.5])
plt.show()
编辑:这是我的问题的解决方案:
x = np.linspace(6.0,12.0,num=100)
# We want to keep a and b fixed to keep the same shape
# a = -0.0864
# b = 11.18
c = 9.04
#Only c is a variable because we only want to shift the plot on the y axis
def f(x, c):
return -0.0864*(x - 11.18)**2 + c
popt, pcov = curve_fit(f, data_x, data_y) # popt are the fitted parameters
plt.plot(data_x, data_y,'.') #blue data points
plt.plot(x,f(x, c),'black') #black line, this is the shape we want our fit to have
plt.plot(x, f(x, *popt), 'red') # new fitted line to the data (with same shape as black line)
plt.xlim([6.5,11.0])
plt.ylim([6.5,10.5])
plt.show()
print("y offset:", popt[0] - c)
y偏移:0.23492393887717355
我正在尝试用多项式曲线拟合2D数据点;参见下面的图片。蓝点是数据。蓝色虚线是适合这些点的二阶多项式。我想强迫我...
scipy.optimize.curve_fit
。如您在文档中所见,可以使用适合的参数定义自己的函数scipy.optimize.curve_fit
。拟合完成后,只需计算fit_y
中的函数,就可以计算y偏移量(相对于原点?)。下面我为您展示了一个使用根函数的示例代码(这就是您的黑色曲线的样子):