set fit logfile "fourierfit.log"
seed = rand(time(0))
unset key
set samp 200
dat="fourierfit.dat"
set table dat
f(x,c0,c1,c2,c3,c4,c5,c6) = c0 + c1*cos(x) + c2*cos(2*x) + c3*cos(3*x) \
                               + c4*cos(4*x) + c5*cos(5*x) + c6*cos(6*x)
set xrange [0:2*pi]
plot f(x, 0.5, 1.1, 0.2, 1.3, 2.4, 0.5, 1.6) + (rand(0) - 0.5)
unset table

fit f(x,a0,a1,a2,a3,a4,a5,a6) dat via a0,a1,a2,a3,a4,a5,a6
fa(x) = x==0 ?a0 :x==1 ?a1 :x==2 ?a2 :x==3 ?a3 :\
        x==4 ?a4 :x==5 ?a5 :x==6 ?a6 :0.0 
set label 1 "周波数スペクトル" at sc 0.15,0.85 font "IPAGothic,16"
set term pngcairo enh font "Times,10" size 480,360
set out "fit_fourier.png"
set multiplot layout 2,1
set size 1,1
set origin 0,0
plot dat pt 6 ps 0.4 lc rgb "#009900",  f(x,a0,a1,a2,a3,a4,a5,a6) lt 1
set size 0.4,0.4
set origin 0.5,0.55
set xtics font ",8"
set ytics font ",8"
set xr [-1:7]
set sampl 9
unset label 1
plot '+' u 1:(fa($1)) w imp lw 5 
unset multiplot