Tuesday 21 May 2013

gnuplot rolling average

Plot rolling average in gnuplot

After reading this example which provided a fixed 5-sample rolling average a put together this which will provide a variable size rolling average and which can be re-used for multiple traces.

The sprintf whose pattern is conditional on (int($0)==0) will reset avg_data when a new plot is started. I suppose this depends on the plot starting at the first row - perhaps a better technique could be found.

min(a,b) = a >= b ? b : a
samples(n) = min(int($0), n)
avg_data = ""

sum_n(data, n) = ( n <= 0 ? 0 : word(data, words(data) - n) + sum_n(data, n - 1))

avg(x, n) = ( avg_data = sprintf("%s %f", (int($0)==0)?"":avg_data, x), sum_n(avg_data, samples(n))/samples(n))

Then, a plot can be made like this which would plot a rolling average of the previous 5 values:

plot [0:*] "file.dat" using 0:(avg(column(3), 5))