0

I have a simulation result curve which is y = f(x), it has some oscillation between some distance interval. I like to smooth out the oscillation by applying some moving average along x. How to do it?

The moving averaging I know is for time averaging. What about distance averaging? Thanks

makeyourownmaker
  • 1,558
  • 2
  • 13
  • 33
roudan
  • 3,082
  • 5
  • 31
  • 72
  • 1
    you need to compute the cumulative distance for each x along f(x) into a separate array, and use those to get your rolling indices. you should provide example arrays of x and y in the question along with what you've tried already – Paul H Dec 10 '20 at 02:28
  • Possible duplicate of [Plot smooth line with PyPlot](https://stackoverflow.com/q/5283649/100129) – makeyourownmaker Jul 02 '21 at 13:44

1 Answers1

2

If you are using python then there are so many options:

Savitzky-Golay Filter:

import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import savgol_filter

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
yhat = savitzky_golay(y, 51, 3) # window size 51, polynomial order 3

plt.plot(x,y)
plt.plot(x,yhat, color='red')
plt.show()

B-spline:

from scipy.interpolate import make_interp_spline, BSpline

#create data
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = np.array([4, 9, 12, 30, 45, 88, 140, 230])

#define x as 200 equally spaced values between the min and max of original x 
xnew = np.linspace(x.min(), x.max(), 200) 

#define spline
spl = make_interp_spline(x, y, k=3)
y_smooth = spl(xnew)

#create smooth line chart 
plt.plot(xnew, y_smooth)
plt.show()

polynomial approximation:

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()
Mr. For Example
  • 4,173
  • 1
  • 9
  • 19
  • Wow, Mr. For Example, that is awesome, that is exactly what I am looking for. I really appreciate it. Thanks – roudan Dec 10 '20 at 16:00