'if' statements within a 'plot' command in gnuplot

Viewed 3184

I am writing a gnuplot (5.2) script and I would like to only plot certain functions or data files if a flag is set. An example of this that works with gnuplot is:

if(flag==0){plot sin(x)}

if(flag==1){plot sin(x), cos(x)}

so that depending on the value of 'flag' I can make slightly different plots. However, doing it the above way means repeating the plot command for every setting for the flag and this quickly becomes laborious if I have multiple settings for my flag. Is there a way to use the 'if' statement inside a plot command? For example, something like:

plot sin(x), if(flag==1){cos(x)}

so that I can do everything with only one use of 'plot'.

2 Answers

Two ideas:

The first idea uses the ternary operator:

unset key
a = 1
plot sin(x), (a == 1 ? cos(x) : NaN)

Depending on your needs, key handling gets difficult.

The second idea builds the plot command depending on some flags:

# initial plot command which plots nothing, additional functions 
# can be appended with a comma
plot_command = "plot NaN notitle"

sin_flag = 1
cos_flag = 1

if (sin_flag == 1) {
   plot_command = plot_command.", sin(x)"
}  

if (cos_flag == 1) {
   plot_command = plot_command.", cos(x)"
}  

# print the final plot command (just for a check)
print plot_command

# execute the plot command
eval plot_command

Make an empty plot window

plot "-" ps 0 notitle
0 0
e

(or sth similar) and then do your original scheme, but with "replot"

if(flagsin==1){replot sin(x)}
if(flagcos==1){replot cos(x)}
Related