在强制曲线形状的同时拟合数据点

时间:2019-12-11 15:46:14

标签: python matplotlib data-fitting

我正在尝试用多项式曲线拟合2D数据点;参见下面的图片。蓝点是数据。蓝色虚线是拟合这些点的2 nd 阶多项式。我想强制拟合具有与黑线完全相同的形状,并且我要计算新拟合与黑曲线的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()

data points and desired fit shape

编辑:这是我的问题的解决方案:

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

solution

1 个答案:

答案 0 :(得分:1)

您要使用scipy.optimize.curve_fit。如您在文档中所见,您可以使用适合的参数定义自己的函数while True: print('Welcome to Rangers Player Statistics') player_name = input('Which player would you like data on? (Kent, Defoe or Morelos) ') player_stat = input('Which statistic would you like? (goals, shots or headers) ') statistic_grab() new_stat = input('Would you like another stat? ') while new_stat == 'yes': continue elif new_stat = 'no' print('Goodbye') break else: print('Invalid Input') 。拟合完成后,您只需计算fit_y中的函数就可以计算y偏移量(相对于原点?)。在下面,我向您展示了一个使用根函数的示例代码(这是您的黑色曲线的样子):

x=0

我没有足够的声誉来发布情节,但只需运行代码即可查看自己。