Search code examples
gnuplot

gnuplot conditional plotting with string fields


I want to plot my data columns "y":"x" only for "name" == "Q4". Here is a data sample:

name x y
Q4 1 3
Q1 2 4

I tried with this:

plot "data.log" u ("name"=="Q4"?"y":NaN):("name"=="Q4"?"x":NaN)) 

And I have the following error: Non-numeric string found where a numeric expression was expected
Any guess how to do that with string in condition? Thanks in advance for answers


Solution

  • You've been close. If you want to compare a string value of a column you have to use strcol() (check help strcol) and the string comparison eq (check help operators binary).

    By the way, it is sufficient to set only one value (either x or y to NaN) to avoid plotting that datapoint. Note, in the example below x and y are swapped compared to your example.

    Script:

    ### filtering of strings with named columns
    reset session
    
    $Data <<EOD
    name   x   y
    Q4     1   2
    Q2     3   4
    Q3     5   6
    Q4     7   8
    Q1     8  10
    Q4    11  12
    Q3    13  14
    Q4    15  16
    EOD
    
    set datafile missing NaN
    
    plot $Data u (strcol("name") eq "Q4" ? column("x") : NaN):"y" w lp pt 7 lc "red" notitle
    ### end of script
    

    Result:

    enter image description here