Search code examples
gnuplot

how to recall an integer in a string in gnuplot


I am just trying to recall an integer in a string as below;

x=1
y=4
$Data <<EOD
12 x
22 y
EOD
print $Data

Right now, when I output the above lines, it would print

12 x
22 y

However, I am interested to see the output when I print $Data like;

12 1
22 4

I used the $ sign behind the integers x and y but it didn't work and same is true using quotation marks. Is there anyway to get around it?


Solution

  • Without knowing your overall goal it is hard to say what the best answer is. If you will not be changing the values of x and y in between uses of $Data then one solution is to expand x and y when writing $Data rather than when reading it:

    set print $Data
    print sprintf("%d 12", x)
    print sprintf("%d 22", y)
    unset print
    
    plot $Data using 1:2 with linespoints
    

    If you truly need to extract a string "foo" from each line of $Data and retrieve the current value of a variable with that name:

    $Data << EOD
        x 12
        y 22
    EOD
    
    x = 3; y = 5
    do for [ i=1: |$Data| ] {
        print value(word($Data[i],1)), " ", word($Data[i],2)
    }
        3 12
        5 22
    

    Note that you must add an explicit space in the middle of the print statement.

    To do this inside a plot command:

    Edit: Apparently the program gets confused if the variable name read in is specifically "x" because that is also the default name of the dependent variable along the horizontal axis. You can remove this ambiguity by temporarily renamed the default name for the dependent variable (the program calls this a "dummy" name).

    set dummy not_really_x
    plot $Data using (value(strcol(1))) : (column(2)) with linespoints
    

    enter image description here