Search code examples
gnuplothistogrambinning

Stacked auto-binned histograms in gnuplot


There are ways to have gnuplot bin your data for you which revolve around

binwidth=5
bin(x,width)=width*floor(x/width)

plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes

And there are ways to plot stacked histograms from pre-binned data, using

set style data histogram
set style histogram rowstacked

plot 'test.dat' using 2:xtic(1) title 'Col1', '' using 3 title 'Col2'

Is there a way to get the best of both worlds? I can

plot 'a.dat' using (bin($1,binwidth)):(1.0) smooth freq with boxes lc 'red' ,\
     'b.dat' using (bin($1,binwidth)):(1.0) smooth freq with boxes lc 'blue' 

but if I set style fill solid the first plot is drawn over.


Solution

  • You can write the smoothed data to an external file and then plot this temporary file as histogram:

    binwidth=5
    bin(x,width)=width*floor(x/width)
    
    set table 'temp.dat'
    plot 'a.dat' using (bin($1,binwidth)):(1.0) smooth freq, \
      'b.dat' using (bin($1,binwidth)) smooth freq
    unset table
    
    set style data histogram
    set style histogram rowstacked
    
    plot 'temp.dat' using 2:xtic(1) index 0 title 'a.dat', '' using 2 index 1 title 'b.dat'
    

    The two smoothed plots of a.dat and b.dat are both saved in the file temp.dat, delimited by two blank lines. So, they can accessed for plotting using the index option.