Search code examples
scalegnuplothistogram

Data disappears when logscale is used in gnuplot


I have successfully made a nice looking histogram in gnuplot with a normal scale but when I add

set logscale y

to my code, the data disappears.

I discovered that logscale does not work with the function I am using to make the histogram (shown in the following link). https://stackoverflow.com/a/2538846/2506689

Does anyone have any suggestions on how to fix this?


Solution

  • set table to the rescue!

    Note that I typed all of this into the interactive prompt and copy/pasted my terminal contents. As such, my commands that follow are prefixed by a gnuplot> which you won't include in your script :-)

    First, I generate some data using python ...

    import numpy as np
    np.savetxt('foobar.txt',np.random.random(1000))
    

    That wasn't hard. Now time to set up gnuplot functions/constants:

    gnuplot> binwidth = 0.05
    gnuplot> bin(x,width)=width*floor(x/width)
    gnuplot> plot 'foobar.txt' using (bin($1,binwidth)):(1.0) smooth freq with boxes 
    

    Ok, it works with non-logscale data. That's good. Lets write that data into a separate file using set table

    gnuplot> set table 'foobar.table'
    gnuplot> plot 'foobar.txt' using (bin($1,binwidth)):(1.0) smooth freq with boxes
    gnuplot> unset table
    

    Now I look at the data gnuplot wrote out to see what's there.

    gnuplot> !head foobar.table
    
    # Curve 0 of 1, 21 points
    # Curve title: "'foobar.txt' using (bin($1,binwidth)):(1.0)"
    # x y xlow xhigh type
     0  40  0  0  i
     0.05  57  0.05  0.05  i
     0.1  52  0.1  0.1  i
     0.15  56  0.15  0.15  i
     0.2  49  0.2  0.2  i
     0.25  55  0.25  0.25  i
    

    Unfortunately, it looks like xlow and xhigh are always the same (possible bug?). But that's Ok, we're using a constant binwidth anyway. We'll just use that as the width.

    gnuplot> set logscale y
    gnuplot> plot 'foobar.table' u 1:2:(binwidth) w boxes
    

    I should note that I've been a little loose with my box positions. To really get it right, you probably need to shift the center of the boxes to the right by half a binwidth:

    gnuplot> plot 'foobar.table' u ($1+0.5*binwidth):2:(binwidth) w boxes