插值在python中没有负值

时间:2016-10-16 16:13:38

标签: python numpy matplotlib scipy interpolation

我一直试图从这些值创建一条平滑线,但我的结果中不能有负值。到目前为止,我尝试的所有方法都给出了负值。会喜欢一些帮助。

import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))

plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)

plt.plot(xs, spl(xs), 'g', lw=3)
plt.show()

enter image description here

2 个答案:

答案 0 :(得分:6)

已知样条拟合过冲。您似乎正在寻找所谓的单调插值器之一。例如,

In [10]: from scipy.interpolate import pchip

In [11]: pch = pchip(x, y)

产生

In [12]: xx = np.linspace(x[0], x[-1], 101)

In [13]: plt.plot(x, y, 'ro', label='points')
Out[13]: [<matplotlib.lines.Line2D at 0x7fce0a7fe390>]

In [14]: plt.plot(xx, pch(xx), 'g-', label='pchip')
Out[14]: [<matplotlib.lines.Line2D at 0x7fce0a834b10>]

enter image description here

答案 1 :(得分:2)

这样做,虽然在某些部分比其他部分更好。

import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np

y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))

plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)

#new code
ny = spl(xs).clip(0,max(spl(x)))
spl2 = UnivariateSpline(xs, ny)

plt.plot(xs, spl(xs) , 'g', lw=2,label="original")
plt.plot(xs, spl2(xs), 'b', lw=2,label="stack mod")

plt.legend()
plt.show()

enter image description here