JonnyZoo
JonnyZoo

Reputation: 281

Gnuplot Moving Average Window

I've tried to find solutions for the following task: - Time Graph MMDDYYYY - X-Axis - y-Value is Average of the last 30 Days. - Data is incomplete (there are days without dataline)

I've found several solutions for "moving average" using the last X samples. But thus my data didn't got a line for each day this isn't sufficient.

So I need a sliding window with fixed number of days.

Do you know how to implement this via Gnuplot?

Thanks in advance Jonny

Upvotes: 1

Views: 2083

Answers (1)

theozh
theozh

Reputation: 25724

Plotting a "last-30-days-average" in contrast to a "last-30-values-average" is not too difficult in gnuplot, but maybe not straightforward and not very efficient.

You can have a gnuplot-only and platform-independent solution if you don't mind reading your file (or datablock) many times (depending on the number of data you have). This workaround calculates the "last-N-days-average" (here: N=30) for each day in the data range in a loop via stats and STATS_mean. This is certainly not very efficient, but should return the desired result.

Script: (works for gnuplot>=5.0.0, Jan. 2015)

### get average over last N days
reset session

myFmt = "%Y-%m-%d"

# create some random test data
set print $Data
    t0 = time(0)
    y0 = rand(0)*50+50
    do for [t=0:500] {
        if (rand(0)<0.5) { print sprintf("%s %g",strftime(myFmt,t0+t*3600*24), y0=y0+rand(0)*4-2) }
    }
set print

stats $Data u (timecolumn(1,myFmt)) nooutput   # get min,max
t0 = STATS_min
t1 = STATS_max
N  = 30        # number of days average

set print $Avg
    do for [tc=t0:t1:3600*24] {
        stats $Data u (t=timecolumn(1,myFmt), tc-t>=0 && tc-t<=N*24*3600 ? $2 : NaN) nooutput
        print sprintf("%.0f %g", tc, STATS_mean)
    }
set print

set format x "%b %d\n%Y" timedate

plot $Data u (timecolumn(1,myFmt)):2 w lp pt 7 ps 0.5 lc "red" ti "Data", \
     $Avg  u 1:2 w l lc "blue" ti sprintf("Average last %d days",N)
### end of script

Result:

enter image description here

Upvotes: 0

Related Questions