Gnuplot: replot inside do for

Viewed 260

Of 3 versions of replotting only 2 work as desired:

plot sin(x)
replot sin(x)/2
replot sin(x)/3
replot sin(x)/4

After each command the respective curve is added to the plot - as expected.

plot sin(x)
replot for [i=2:4] sin(x)/i

gives the same (final) result (4 curves in the plot), but

plot sin(x)
do for [i=2:4] {replot sin(x)/i}

results in a plot with only the 1st and the 4th curve, although 4 lines are written in the key. Is this a "feature" or (how) can I get 4 curves in the do-for-version (because I have to do some additional stuff within the do-clause)?

[gnuplot 5.2 (8), Ubuntu MATE 20.04]

3 Answers

I think the syntax that expresses what you were originally trying to do is this:

do for [i=1:4] {
    # ... do some stuff ...  #
    plot for [j=1:i] sin(x)/j title sprintf("sin(x)/%d",j)
}

replot is really not what you want for this sort of thing.

So a way to use replot inside a do-for-loop is creating a macro:

plot sin(x), cos(x)
txt = ""
do for [i=2:4] {
  # some calculations involving i
  txt = txt . "replot sin(x)/" . i . ", cos(x)/" . i . " ; "
  # maybe some more stuff involving i
}
@txt

Additioal Way

There is also a way to use the eval command in loop, as follows.

plot sin(x), cos(x)
do for [i=2:4] {
  # some calculations involving i
  command = sprintf("replot sin(x)/%i, cos(x)/%i", i, i)
  eval command
  # maybe some more stuff involving i
}
Related