fit a function to a histogram created with frequency in gnuplot

DanielTuzes picture DanielTuzes · Jan 13, 2013 · Viewed 8.9k times · Source

Intro

In gnuplot there's a solution to create histogram from file named hist.dat what likes

1
2
2
2
3

by using commands

binwidth=1
set boxwidth binwidth
bin(x,width)=width*floor(x/width) + binwidth/2.0
plot [0:5][0:*] "hist.dat" u (bin($1,binwidth)):(1.0) smooth freq with boxes

that generates a histogram like this one from other SO page.

Question

How can I fit my function to this histogram? I defined a Gaussian function and initialized its values by

f(x) = a*exp(-((x-m)/s)**2)
a=3; m=2.5; s=1

and in the output the function follow the histogram well.

Unfortunatelly I cannot fit to this histogram using command

fit f(x) "hist.dat" u (bin($1,binwidth)):(1.0) smooth freq via a,m,s  
                                                      ^
         Need via and either parameter list or file

So how can I fit my function without creating a new file containing the binned values?

Answer

amaciarey picture amaciarey · Mar 14, 2013

I'm facing a similar problem and I found a kind of not very ellegant solution.

binwidth=1
set boxwidth binwidth
bin(x,width)=width*floor(x/width) + binwidth/2.0
set table 'hist.temp'
plot [0:5][0:*] "hist.dat" u (bin($1,binwidth)):(1.0) smooth freq with boxes
unset table

And then you can do the fit of the file as you prefer. I know that probably there are some better way of doing this, but for me it is a fast and working solution. I hope this will be helpful for you.

Cheers!