-->

fit a function to a histogram created with frequen

2019-05-07 11:42发布

问题:

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?

回答1:

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!



回答2:

I used this a nd it worked:

gauss(x)=a/(sqrt(2*pi)sigma)*exp(-(x-mean)**2/(2*sigma**2))

fit gauss(x) 'data.txt' via a,sigma,mean

after 83 iterations GNUplot calculated me a, sigma, and mean