Search code examples
arraysloopsgnuplotquotes

How can I use dynamic variable names in gnuplot with "with" notation?


i want to use variables or arrays in plot command with for loop as follows

style[1]= "lines lt 4 lw 2"
style[2] = "points lt 3 pt 5 ps 2"
....

title[1]= "first title"
title[2]= "second title "
...

or

style="'lines lt 4 lw 2' 'points lt 3 pt 5 ps 2'"
title="'first title' 'second title'"

plot command

plot for [i=1:1000] 'data.txt' u 1:2 title title[i] with style[i]
plot for [i=1:1000] 'data.txt' u 1:2 title word(title,i) with word(style,i)

I was successful in the title part, but not in the with part. I realized that the problem was caused by quotes.

i=1
plot 'data.txt' u 1:2 title "first title" with "lines lt 4 lw 2"

When I use the array and word attributes, I get an error due to a quote error. I tried with sprintf but still no success.

sprintf("with %s", style'.i.')

I hope I could explain correctly. Any idea how I solve this? or how can i remove the quotes. Many thanks.


Solution

  • You can try to build a complete plot command as a string and eval it afterwards:

    max_i = 2
    array title[max_i]
    array style[max_i]
    
    style[1]= "lines lt 4 lw 2"
    style[2] = "points lt 3 pt 5 ps 2"
    
    title[1]= "first title"
    title[2]= "second title"
    
    
    cmd="plot NaN notitle"  # dummy for starting iteration
    do for [i=1:max_i] {
       # append the explicit plot command
       cmd = sprintf("%s, sin(x*%d) title \"%s\" with %s", cmd, i, title[i], style[i])
    }
    print cmd  # just for checking the final plot command
    
    eval cmd   # run plot command
    
    

    It might be slow (or even not work at all) for 1000 lines. But I would be a bit scared of having 1000 lines and titles within a single diagram, anyhow.