2

How gnuplot convert a string to integer

I wonder if there is an easy way to convert a string to integer. For example, I want a way as like strtointeger("2") to return an integer 2.

columns="2 3"

plot for [i in columns] "mydata.dat" using 1:strtointeger(i)

1 Answer 1

4

The variable i in [i in columns] is actually a string. So, convert it to an integer via int(i).

If you want to plot a column defined by an integer variable, use ... using (column(i))....

So, in combination:

Code:

### plot column numbers from a sequence in a string
reset session
set key top left

$Data <<EOD
11 12 13 14 15
21 22 23 24 25
31 32 33 34 35
41 42 43 44 45
51 52 53 54 55
EOD

columns="2 3 5 1 4"

plot for [i in columns] $Data using 1:(column(int(i))) w lp title sprintf("Column %s",i)
### end of code

In your case remove the datablock $Data <<EOD ... EOD and in the plot command replace $Data with "mydata.dat"

Result:

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much @theozh. And why is this a wrong way by using int(i) directly--using 1:(int(i)) rather than using (column(int(i))). I mean the function column must be used with parentheses, but parentheses used with int is a wrong use, why?
if you take (int(i)) it will be a constant with value i. Whereas (column(i)) are the values from the ith column.
According to the manuel of gnuplot, the argument of the function int is a real type. Really thanks to your answer, which let me know that string type can also be used with int!
apparently, gnuplot tries to make a number out of the argument. int(1.23), int("1.23") and even int("1.23abc") will work, whereas int(abc1.23) or int("abc1.23") will give error messages.
just for completeness: actually, using 1:int(i) would also give the same desired result like using (column(int(i))), in contrast to using 1:(int(i)), (note the additional parentheses).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.