Search code examples
gnuplot

How to map a string to a RGB value?


The data file is like the following:

# ID,Value, Region
A,30,North
B,26,North
C,49,South
D,55,East
...

Here I would like to map the string (e.g., Region) to a rgb value which will be used as the lc color for boxxy. It can be described as the pseudo-code:

if (region eq "North") {
   "0x1b9e77"
} else if (region eq "South") {
   "0xd95f02"
} else if (region eq "East") {
   "0x7570b3"
} else  {
   "0xe7298a"
}

How can I achieve such mapping in gnuplot? Here, in fact, it is to map $3 to a hex string in using option.


Solution

  • You can define a mapping function basing on your pseudocode:

    colormapper(x)=(x eq "North"?0x1b9e77:(x eq "South"?0xd95f02:(x eq"East"?0x7570b3:0xe7298a)))
    

    after that, you can apply it on your column.

    plot 'map.dat' u 1:2:(colormapper(stringcolumn(3))) pt 7 ps 3 lc rgb variable notitle
    

    Sample based on my data

    The key moments of the solution:

    • Using x eq "North"... because we compare strings
    • lc rgb variable let us to control the line color by a variable (without rgb you can access to the standard line colors)
    • Using stringcolumn(3) instead of $3 is very important.