2017-10-08 212 views
1

我有个数据点的两个列表:平滑曲线在Python

list_x = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] 
list_y = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 

当我绘制出来,图形看起来就像这样:基于这些

import matplotlib.pyplot as plt 
plt.plot(list_x, list_y) 
plt.show() 

enter image description here

数据点,有没有办法使图形看起来像下面的图形并得到它的图形方程?

enter image description here

========================================= ==================

我已经尝试使用here的解决方案,它会产生一个不平滑的图形。

from scipy.interpolate import spline 
import numpy as np 

list_x_new = np.linspace(min(list_x), max(list_x), 1000) 
list_y_smooth = spline(list_x, list_y, list_x_new) 

plt.plot(list_x_new, list_y_smooth) 
plt.show() 

enter image description here

+0

的可能的复制[绘制与PyPlot平滑线(https://stackoverflow.com/questions/5283649/plot-smooth-line-with-pyplot) –

回答

2

,从戴维斯鲱鱼相呼应的建议,一个简单的办法是用多项式近似数据

import numpy as np 
import matplotlib.pyplot as plt 

plt.figure() 
poly = np.polyfit(list_x,list_y,5) 
poly_y = np.poly1d(poly)(list_x) 
plt.plot(list_x,poly_y) 
plt.plot(list_x,list_y) 
plt.show() 

Polynomial approximation

你会在那是情节的右端注意振荡不存在于原始数据中,该原始数据是多项式近似的伪像。

戴维斯上面提出的样条插值是另一个不错的选择。改变平滑度参数s,您可以在平滑度和距离与原始数据之间实现不同平衡。

from scipy.interpolate import splrep, splev 

plt.figure() 
bspl = splrep(list_x,list_y,s=5) 
bspl_y = splev(list_x,bspl) 
plt.plot(list_x,list_y) 
plt.plot(list_x,bspl_y) 
plt.show() 

B-spline approximation

1

因为你的数据是近似(,它已经量化),你想要一个approximating spline,而不是插值样条。