python等⾼线图平滑_⽤Matplotlib平滑等⾼线图中的数据平滑数据的⼀个简单⽅法是使⽤moving average算法。移动平均的⼀种简单形式是计算某⼀位置相邻测量值的平均值。例如,在⼀维测量序列a[1:N]中,a[N]处的移动平均值可以计算为a[N]=(a[N-1]+a[N]+a[N+1])/3。如果你检查了所有的测量,你就完成了。在这个简单的例⼦中,我们的平均窗⼝的⼤⼩是3。也可以使⽤不同⼤⼩的窗⼝,具体取决于所需的平滑程度。
为了在更⼴泛的应⽤程序中使计算更简单、更快,还可以使⽤基于convolution的算法。使⽤卷积的优点是,只需更改窗⼝,就可以选择不同类型的平均值,如加权平均值。
让我们做⼀些代码来说明。以下摘录需要安装Numpy、Matplotlib和Scipy。Click here⽤于完整运⾏的⽰例代码from __future__ import division
import numpy
import pylab
from scipy.signal import convolve2d
matplotlib中subplotdef moving_average_2d(data, window):
"""Moving average on two-dimensional data.
"""
# Makes sure that the window function is normalized.
window /= window.sum()
# Makes sure data array is a numpy array or masked array.
if type(data).__name__ not in ['ndarray', 'MaskedArray']:
data = numpy.asarray(data)
# The output array has the same dimensions as the input data
# (mode='same') and symmetrical boundary conditions are assumed
# (boundary='symm').
return convolve2d(data, window, mode='same', boundary='symm')
下⾯的代码⽣成⼀些任意且有噪声的数据,然后使⽤四个不同⼤⼩的框窗⼝计算移动平均值。M, N = 20, 2000 # The shape of the data array
m, n = 3, 10 # The shape of the window array
y, x = id[1:M+1, 0:N]
# The signal and lots of noise
signal = -10 * s(x / 500 + y / 10) / y
noise = al(size=(M, N))
z = signal + noise
# Calculating a couple of smoothed data.
win = s((m, n))
z1 = moving_average_2d(z, win)
win = s((2*m, 2*n))
z2 = moving_average_2d(z, win)
win = s((2*m, 4*n))
z3 = moving_average_2d(z, win)
win = s((2*m, 10*n))
z4 = moving_average_2d(z, win)
然后,为了看到不同的结果,这⾥是⼀些绘图的代码。# Initializing the plot
pylab.close('all')
pylab.ion()
fig = pylab.figure()
bbox = dict(edgecolor='w', facecolor='w', alpha=0.9)
crange = numpy.arange(-15, 16, 1.) # color scale data range
# The plots
ax = pylab.subplot(2, 2, 1)
<(0.05, 0.95, 'n=10, m=3', ha='left', va='top', ansAxes, bbox=bbox)
bx = pylab.subplot(2, 2, 2, sharex=ax, sharey=ax)
<(0.05, 0.95, 'n=20, m=6', ha='left', va='top', ansAxes, bbox=bbox)
bx = pylab.subplot(2, 2, 3, sharex=ax, sharey=ax)
<(0.05, 0.95, 'n=40, m=6', ha='left', va='top', ansAxes, bbox=bbox)
bx = pylab.subplot(2, 2, 4, sharex=ax, sharey=ax)
<(0.05, 0.95, 'n=100, m=6', ha='left', va='top', ansAxes, bbox=bbox)
ax.set_xlim([x.min(), x.max()])
ax.set_ylim([y.min(), y.max()])
fig.savefig('movingavg_sample.png')
# That's all folks!
下⾯是不同⼤⼩窗⼝的打印结果:
这⾥给出的⽰例代码使⽤⼆维的简单框(或矩形)窗⼝。有⼏种不同类型的窗⼝可⽤,您可能需要检查Wikipedia以获取更多⽰例。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。