使用SciPy将数据插入到二次拟合中

问题描述 投票:0回答:1

我有一组数据,当绘制时,大多数点聚集在x轴的左侧:

plt.plot(x, y, marker='o')
plt.title('Original')
plt.show()

ORIGINAL GRAPH

我想使用scipy来插入数据,然后尝试将二次线拟合到数据中。我避免简单地拟合没有插值的二次曲线,因为这将使得到的曲线偏向x轴的一个末端处的数据质量。我通过使用尝试了这个

f = interp1d(x, y, kind='quadratic')

# Array with points in between min(x) and max(x) for interpolation
x_interp = np.linspace(min(x), max(x), num=np.size(x))

# Plot graph with interpolation
plt.plot(x_interp, f(x_interp), marker='o')
plt.title('Interpolated')
plt.show()

并得到INTERPOLATED GRAPH

但是,我打算得到的是这样的:EXPECTED GRAPH

我究竟做错了什么?

我的x值可以找到here和y here的值。谢谢!

python scipy interpolation data-analysis
1个回答
2
投票

Solution 1

我很确定这会做你想要的。它适合您的数据的二次(二次)多项式,然后绘制函数在x值的均匀间隔的数组上,范围从原始x数据的最小值到最大值。

new_x = np.linspace(min(x), max(x), num=np.size(x))
coefs = np.polyfit(x,y,2)
new_line = np.polyval(coefs, new_x)

绘制它返回:

plt.scatter(x,y)
plt.scatter(new_x,new_line,c='g', marker='^', s=5)
plt.xlim(min(x)-0.00001,max(x)+0.00001)
plt.xticks(rotation=90)
plt.tight_layout()
plt.show()

interpolated data

if that wasn't what you meant...

但是,从您的问题来看,您似乎可能试图将所有原始y值强制均匀分布在x值上(如果这不是您的意图,请告诉我,我将删除此部分)。

这也是可能的,有很多方法可以做到这一点,但我在熊猫这里做到了:

import pandas as pd
xy_df=pd.DataFrame({'x_orig': x, 'y_orig': y})
sorted_x_y=xy_df.sort_values('x_orig')
sorted_x_y['new_x'] = np.linspace(min(x), max(x), np.size(x))

plt.figure(figsize=[5,5])
plt.scatter(sorted_x_y['new_x'], sorted_x_y['y_orig'])
plt.xlim(min(x)-0.00001,max(x)+0.00001)
plt.xticks(rotation=90)
plt.tight_layout()

这与您的原始数据看起来非常不同......这就是为什么我认为它可能不是您正在寻找的。

weird interpolation

© www.soinside.com 2019 - 2024. All rights reserved.