Moving Average for Gnuplot

Fix Number of Averages

This causes that the first 500 samples are not printed.
avg_cnt=500

array A[avg_cnt]
samples(x) = $0 > (avg_cnt-1) ? avg_cnt : int($0+1)
mod(x) = int(x) % avg_cnt
avg_n(x) = (A[mod($0)+1]=x, ($0 < avg_cnt/4 ? NaN : (sum [i=1:samples($0)] A[i]) / samples($0)))

plot \
     input_file using 2:(($3-$7)+($6-$10)+$11-$12) with lines title "memory consumption", \
     input_file using 2:(avg_n(($3-$7)+($6-$10)+$11-$12)) with lines title "memory consumption (".avg_cnt.")", \

Moving average implementation with variable number of averages

n = 100
do for [i=1:n] {
    eval(sprintf("back_n%d=0", i))
}
shift = "("
do for [i=n:2:-1] {
    shift = sprintf("%sback_n%d = back_n%d, ", shift, i, i-1)
}
shift = shift."back_n1 = x)"
sum = "(back_n1"
do for [i=2:n] {
    sum = sprintf("%s+back_n%d", sum, i)
}
sum = sum.")"
samples(x) = \$0 > (n-1) ? n : (\$0+1)
avg_n(x)   = (shift_n(x), @sum/samples(\$0))
shift_n(x) = @shift


plot "test.data" using 1:2 w l notitle, \
     "test.data" using 1:(avg_n($2)) w l lc rgb "red" lw 3 title "avg\\_".n
Source: https://stackoverflow.com/a/42868056/494725