2016-10-16 3 views
2

Ich habe versucht, eine glatte Linie aus diesen Werten zu erstellen, aber ich kann keine negativen Werte in meinem Ergebnis haben. Bisher geben alle Methoden, die ich versucht habe, negative Werte. Würde etwas Hilfe lieben.Interpolieren ohne negative Werte in Python

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

Antwort

6

Keilpassung zu überschreiten, ist bekannt. Sie scheinen nach einem der sogenannten monotonischen Interpolatoren zu suchen. Zum Beispiel

In [10]: from scipy.interpolate import pchip 

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

produziert

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

+0

Groß ! Genau das, was ich brauchte – user4421975

2

Das tut es, wenn auch in einigen Abschnitten besser als andere.

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

+0

Noch unter 0 geht: '(SPL2 (xs) <0) .any()' 'kehrt true' ... – wildwilhelm