Search code examples
gnuplothistogram

Centering bins in Gnuplot Histogram


In gnuplot, you can create a histogram like

binwidth=#whatever#
set boxwidth binwidth
bin(x,width)=width*floor(x/width)+binwidth/2.0
plot "gaussian.data" u (bin($1,binwidth)):(1.0/10000) smooth freq w boxes

Currently, my bins seem to be centered on the right-edge. That is, the bin corresponding to x=0 has its right edge above zero. I would like to have the bins center-oriented. That is, I would like to have the center of each bin above the corresponding x values. I have tried messing with the arguments of bin(x,width) but haven't been successful. Any suggestions?


Solution

  • bin(x,width) = width*round(x/width)
    

    should do the trick. You can simply visualize how the binning works:

    binwidth = 0.5
    round(x) = floor(x+0.5)
    bin(x,width) = width*round(x/width)
    set xrange [-2:2]
    set xlabel "x"
    set ylabel "bin position"
    set grid
    plot bin(x,binwidth)
    

    gives

    enter image description here

    Note that values in [-0.25,0.25] are mapped to the bin at position 0, values in [0.25, 0.75] are mapped to the bin at position 0.5, and so forth.