Search code examples
gnuplot

How to use a substring of the columnhead in gnuplot?


How can I use a substring of the columnhead for the key? Following simple example:

Code:

### How to get a substring from columnhead?
reset session

$Data <<EOD
ABC.x  ABC.y  DEF.x  DEF.y  GHI.x  GHI.y
   11     21     31     41     51     61
   12     22     32     42     52     62
   13     23     33     43     53     63
   14     24     34     44     54     64
   15     25     35     45     55     65
EOD

set key top left
plot for [i=1:5:2] $Data u i:i+1 w lp title columnhead(i)
### end of code

Result:

enter image description here

I could use these two syntax variations:

... title columnhead
... title columnhead(i)

Now, however, I want to skip the .x in the legend.

None of the following works:

... title columnhead[1:3]
... title columnhead(i)[1:3]
... title substr(columnhead,1,3)
... title substr(columnhead(i),1,3)
... title sprintf("%s",columnhead)[1:3]
... title sprintf("%s",columnhead(i))[1:3]
... title (sprintf("%s",columnhead(i))."")[1:3]
... title (tmp=columnhead(i),tmp[1:3])

With most of these variations you will get the following result:

Result:

enter image description here

Question: Why is this? How to workaround?


Solution

  • Apparently, this has been solved in gnuplot 5.4.0, ... title columnhead(i)[1:3] seems to work there.

    Nevertheless, here is an attempt for a workaround for gnuplot 5.0.0 to 5.2.8. Probably, the code can also be adapted to work in older gnuplot versions.

    edit: actually, there was an earlier question which I haven't seen before I asked this question. But there is even a (strange) workaround for gnuplot 4.6.0 and comma separated columns.

    Script: (edit: simplified version, assumption column separator is whitespace)

    ### Get a substring from columnheader for gnuplot>=5.0.0
    reset session
    
    $Data <<EOD
    ABC.x  ABC.y  DEF.x  DEF.y  GHI.x  GHI.y
       11     21     31     41     51     61
       12     22     32     42     52     62
       13     23     33     43     53     63
       14     24     34     44     54     64
       15     25     35     45     55     65
    EOD
    
    # get the columnheaders into a string
    headers = ''
    set datafile separator "\n"
    stats $Data u (headers=strcol(1)) every ::0::0 nooutput
    set datafile separator            # restore default
    myTitle(i) = word(headers,i)[1:3]
    
    set key top left
    plot for [i=1:5:2] $Data u i:i+1 w lp title myTitle(i)
    ### end of code
    

    Result:

    enter image description here