0

我正在尝试使用 Python 中的样条线填充两条曲线之间的间隙。我希望我的新线与每一端原始曲线的渐变相匹配。问题源于在 scipy.interpolate 样条例程中需要单调增加的 x 值。下面的代码是我正在处理的示例。蓝色的两条曲线(“第 1 行”和“第 2 行”)是我所拥有的,并且(类似于)我想要的样条曲线由标有“想要”的线显示。

有没有人有任何建议我该怎么做?

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

line1_x = np.array([4.0e8, 4.7e8, 5.5e8, 6.6e8, 8.0e8, 1.0e9, 1.4e9, 2.0e9, 3.6e9, 
                    9.5e9])
line1_y = np.array([5500., 5000., 4500., 4000., 3500., 3000., 2500., 2000., 1500.,
                    1000.])
                
line2_x = np.array([1.010e10, 1.060e10, 1.081e10, 1.084e10, 1.076e10, 1.064e10, 
                    1.055e10, 1.050e10, 1.051e10, 1.057e10, 1.067e10, 1.079e10, 
                    1.091e10, 1.102e10, 1.112e10])
line2_y = np.array([350., 361., 372., 385., 395., 407., 418., 430., 442., 454., 
                    466., 478., 490., 503., 515.])

desired_x = np.array([1.112e10, 1.117e10, 1.121e10, 1.116e10, 1.087e10, 1.027e10, 
                      9.869e9, 9.5e9])
desired_y = np.array([515., 536., 575., 645., 748., 891., 962., 1000.])

plt.plot(line1_x, line1_y, 'b-', label='Line 1')
plt.plot(line2_x, line2_y, 'b-', label='Line 2')
plt.plot(desired_x, desired_y, 'r--', label='Wanted')
plt.legend(loc=0)

样条图示例

4

1 回答 1

0

我一直无法弄清楚如何解决 x 增加的需求。所以我选择了一个稍微“作弊”的选项。由于我的 y 总是在增加,我可以使用标准的 scipy.interpolate 样条例程来获得所需的输出。

需要在问题中添加到我的示例中以使其工作的代码是:

x = np.concatenate((line1_x, line2_x))
y = np.concatenate((line1_y, line2_y))
order = np.argsort(y)

spline_fit = interp.UnivariateSpline(y[order], x[order])
y_points = np.linspace(515, 1000, 20)

plt.plot(spline_fit(y_points), y_points, 'k--', label='Fit')

这给出了预期的结果: 在此处输入图像描述

于 2016-05-12T14:34:28.260 回答