在数组中的元素之间插值

时间:2018-08-06 19:33:11

标签: arrays python-3.x numpy matplotlib interpolation

我仍在尝试解决此处描述的问题:matplotlib: assign color to a radius。 我首先使用Contourplot进行了尝试,但是当我尝试在磁盘表面上绘制圆并为其分配颜色时,我认为这是一个更好的解决方案。 因此,我有一个数组:

arr = np.array([[ 114.28, 14],
            [ 128.57, 16],
            [ 142.85,19],
            [ 157.13,20],
            [ 171.41,21],
            [ 185.69,22],
            [ 199.97,24],
            [ 214.25,27],
            [ 228.53,29],
            [ 242.81,30],
            [ 257.09,31],
            [ 271.37,34],
            [ 288.65,35],
            [ 299.93,36],
            [ 300,38]])

我想将此数组扩展为具有约300个元素的数组(取决于磁盘的半径。如果半径为例如500,我想有一个包含500个元素的数组),方法是在的值之间进行插值线性数组。我需要对两列进行插值。我发现了这篇文章:Interpolate between elements in an array of floats,但由于他们谈论的是毫秒和LED指示灯,所以我听不懂代码。 提前致谢 !

1 个答案:

答案 0 :(得分:2)

IIUC,我认为您可以使用np.interp来插值。根据文档,np.interp用于:

  

一维线性插值。

听起来就像你在追求什么。

因此,您可以使用np.linspace创建一个从最小x值到最大x值的300个均匀间隔的点的数组:

new_x = np.linspace(min(arr[:,0]), max(arr[:,0]), num=300)

然后内插新的y值:

new_y = np.interp(new_x, arr[:,0], arr[:,1])

以图形方式进行说明:

# Show the original 15 points:
plt.scatter(arr[:,0], arr[:,1], label='original', zorder=10)

# Show the interpolated 300 points:
plt.scatter(new_x, new_y, label='interpolated', s=0.5)

plt.legend()

plt.show()

enter image description here

编辑根据您的注释,要在数组中的每个数据点之间精确地插值20个点,可以通过遍历数组并应用linspace来获得20个点来创建新的x轴每个连续x值之间的点。但是,这将产生280个点,因为您将在15个数据点之间创建20个点,从而产生20*(15-1)个新数据点:

new_x = np.concatenate([np.linspace(arr[i,0],arr[i+1,0], num=20)
                        for i in range(len(arr)-1)])

new_y = np.interp(new_x, arr[:,0], arr[:,1])


# Show the original 15 points:
plt.scatter(arr[:,0], arr[:,1], label='original', zorder=10)

# Show the interpolated 280 points:
plt.scatter(new_x, new_y, label='interpolated', s=0.5)

plt.legend()

plt.show()

enter image description here