import numpy as np import matplotlib as matplotlib # for plotting import matplotlib.pyplot as plt # Answer to Quora question: # https://www.quora.com/How-do-I-perform-moving-average-in-Python # Create some data np.random.seed(17) n = 10 N = 500 x = np.linspace(0, n, N) y0 = -0.05*x**4 + 5*x**2 + 7*x - 6 yn = 4.5*np.random.standard_normal(N) * np.log10(y0**2 + 0.1)/2 y = y0 + yn # Create a figure canvas and plot the original, noisy data fig, ax = plt.subplots() ax.plot(x, y, label="Original") # Compute moving averages using different window sizes window_lst = [3, 6, 10, 16, 22, 35] y_avg = np.zeros((len(window_lst) , N)) for i, window in enumerate(window_lst): avg_mask = np.ones(window) / window y_avg[i, :] = np.convolve(y, avg_mask, 'same') # Plot each running average with an offset of 50 in order to be able to distinguish them ax.plot(x, y_avg[i, :] + (i+1)*50, label=window) # Add legend to plot ax.legend() plt.show() # http://mathworld.wolfram.com/NormalDistribution.html gaussian_func = lambda x, sigma: 1/np.sqrt(2*np.pi*sigma**2) * np.exp(-(x**2)/(2*sigma**2)) fig, ax = plt.subplots() # Compute moving averages using different window sizes sigma_lst = [1, 2, 3, 5, 8, 10] y_gau = np.zeros((len(sigma_lst), N)) for i, sigma in enumerate(sigma_lst): gau_x = np.linspace(-2.7*sigma, 2.7*sigma, 6*sigma) gau_mask = gaussian_func(gau_x, sigma) y_gau[i, :] = np.convolve(y, gau_mask, 'same') # Plot each running average with an offset of 50 in order to be able to distinguish them ax.plot(x, y_gau[i, :] + (i+1)*50, label=r"$\sigma = {}$, $points = {}$".format(sigma, len(gau_x))) # Add legend to plot ax.legend(loc='upper left') plt.show()