gnuplot: variable values and definitions in plot command

Viewed 399

I just stumbled across the following:

According to the gnuplot manual a plot element may contain a definition.

Syntax: 

      plot {<ranges>} <plot-element> {, <plot-element>, <plot-element>}

Each plot element consists of a definition, a function, or a data source 
together with optional properties or modifiers: 

      plot-element:
           {<iteration>}
           <definition> | {sampling-range} <function> | <data source>
                        | keyentry
           {axes <axes>} {<title-spec>}
           {with <style>}

Check the following example:

  • For the first graph y=x+1 is plotted because a=1 was defined earlier. As expected.

  • For the second graph and the first plot command it should be the same but y=2*x+1 is plotted instead (twice).

  • In the third graph when a=1 is explicitely specified it is plotted as expected.

Why is gnuplot ignoring a=1 for the second graph? Have I misunderstood something?

Code:

### definitions in plot command
reset session

a = 1
b = 1
f(x) = a*x + b

set yrange[-40:40]
set multiplot layout 1,3
    plot     f(x)
    plot     f(x), a=2 f(x), a=3 f(x)
    plot a=1 f(x), a=2 f(x), a=3 f(x)
unset multiplot
### end of code

Result:

enter image description here

1 Answers

Your diagnosis is slightly off. In the second panel the first, purple plot is superimposed with the a=3 plot rather than the a=2 plot.

Why? Because gnuplot accumulates all elements of the full plot before actually drawing any of them. This involves making two passes over the command line. One pass to parse and load data from any data sources mentioned (needed for example for autoscaling), then a second pass to evaluate any functions over the range (which might have determined by autoscaling). During the first pass here, a gets set to 2 and then to 3. At the start of the second pass a is still 3 and in the absence of an initial definition to change it that is what is used when f(x) is evaluated.

Related