Search code examples
gnuplot

Gnuplot: show absolute value on y axis, percentage on y2


I want to make a plot where the data has two y-axes: one shows the absolute value, the other shows a percentage difference from one data point. So if, say, 37 is 100%, I want to show 37 on the left y axis and 100 on the right y axis. How do I do this?

The value to set at 100% is the last value in my dataset. I could live with hardcoding it.

I tried plotting the data twice, once for x1y1 and once for x1y2. The axes use independent automatic scaling and the plots did not line up. I want to avoid hardcoding the scaling.

Data:

1 35.15
2 33.3
3 33.3
4 40.7
5 37

Plot script:

plot 'data.dat' using 1:2 with lines

What I want in red


Solution

  • You can (ab)use the stats command to obtain the last value of your data file

    stats "data.dat" using (ylast=$2) nooutput
    

    and you can then link the two y axes together

    set link y2 via y*100./ylast inverse y*ylast/100.
    

    That seems to turn off the usual extensions of the y axis range beyond the largest/smallest value of the data, so you might want to increase the range manually using set offset.

    Putting all this together:

    stats "data.dat" using (ylast=$2) nooutput    
    set link y2 via y*100./ylast inverse y*ylast/100.   
    set offset 0,0,1,1
    set ytics nomirror
    set y2tics 5
    set format y2 "%g%%"    
    plot "data.dat" w lp
    

    enter image description here