Search code examples
gnuplot

Extracting row as plot title in GNUPLOT


-Empty line here-
LED:GREEN   FREQUENCY:1 BRIGHTNESS:50
Colour  State   Time(s)
GREEN   1   0.000000
GREEN   1   0.020000
GREEN   1   0.040000
GREEN   1   0.060000
GREEN   1   0.080000
GREEN   1   0.100000
.
.
.
LED:RED FREQUENCY2:1    BRIGHTNESS2:25
Colour  State   Time(s)
RED 1   0.000000
RED 1   0.020000
RED 1   0.040000
RED 1   0.060000
RED 1   0.080000
RED 1   0.100000

I have the above .txt file as my data file and im trying to extract the rows with first column LED:GREEN/LED RED to use as my plot title for each respective graph in my multiplot.

I have the following code:

f(x,y)= (x eq "GREEN"? y :1/0);

p(x,y)= (x eq "RED"? y :1/0);

plot 'abc.txt' u 3:(f(strcol(1),$2)):"LED:GREEN" with lines linecolor "green";

plot 'abc.txt' u 3:(p(strcol(1),$2)) with lines linecolor "red";

Is there any way to extract those rows to use as plot title? ie. LED:GREEN FREQUENCY:1 BRIGHTNESS:50 and LED:RED FREQUENCY2:1 BRIGHTNESS2:25


Solution

  • Setting a graph title has to be done before the plot command. So, in order to extract a line you need to go through the data file. You could do this via an external tool, but I prefer (if possible) gnuplot-only solutions.

    If you can slightly change your data, I would recommend to insert two empty lines between your GREEN-part and RED-part. With this, you can address the blocks simply via index (block index is zero-based) (check help index).

    You can (mis)use stats to go through data and store some parts into variables. If you set datafile separator "\n", a complete line can be accessed as strcol(1) (check help strcol). Since you only need the first line (row index is zero-based) you can limit it by using every ::::0 (check help every).

    Data: SO77401935.dat

    
    LED:GREEN   FREQUENCY:1 BRIGHTNESS:50
    Colour  State   Time(s)
    GREEN   1   0.000000
    GREEN   1   0.020000
    GREEN   0   0.040000
    GREEN   1   0.060000
    GREEN   1   0.080000
    GREEN   1   0.100000
    
    
    LED:RED FREQUENCY2:1    BRIGHTNESS2:25
    Colour  State   Time(s)
    RED 1   0.000000
    RED 1   0.020000
    RED 1   0.040000
    RED 1   0.060000
    RED 0   0.080000
    RED 1   0.100000
    

    Script:

    ### get title from a row
    reset session
    
    FILE = "SO77401935.dat"
    
    set datafile separator "\n"
    stats FILE index 0 every ::::0 u (myTitle1 = strcol(1)) nooutput
    stats FILE index 1 every ::::0 u (myTitle2 = strcol(1)) nooutput
    set datafile separator whitespace
    
    set multiplot layout 1,2
    
        set title myTitle1
        plot FILE index 0 u 3:2 w lp pt 7 lc "red" lw 2
        
        set title myTitle2
        plot FILE index 1 u 3:2 w lp pt 7 lc "web-green" lw 2
    unset multiplot
    ### end of script
    

    Result:

    enter image description here