Simple tricks

Simple tricks

Using the ternary operator - plotting an inequality in 2D

One of the most useful concepts in gnuplot is that a NaN can be defined in a simple way, setting a value to 1/0. Since this value is ignored by gnuplot, this can be used to not plot something where we do not want to plot anything. I will demonstrate this by plotting the domain of an inequality in two dimensions.

Before doing that, however, I would like to point out two facts. One is that this is not the only way to plot an inequality. Another can be found in the Not so fequently asked questions, if you need only the curve separating the region of the x-y plane that fulfils the inequality from that that does not. But if the question is how we can shade the the domain, there is a much easier solution, and this solution does not involve the inversion of the inequality. We will look at the inequality

x3 - 2xy + y3 > 0

The ternary operator

While gnuplot has an if directive, in mathematical expressions it is much better to use the ternary operator, which always has the form


i.e., returns 'B', if 'A' is true, and 'C' otherwise. (Incidentally, the value 'B' can be a ternary operator itself, and in this way, multiple conditions can be imposed. More on this later.)

Now, we can define a function that has a constant value, if the inequality holds true, and has an indefinite value, if this is not the case, i.e.,

f(x,y)=(x*x*x - 2*x*y + y*y*y>0)?1:1/0

In the function above, f(x,y) = 1, if x3 - 2xy + y3>0, and f(x,y) = 1/0 (undefined), if x3 - 2xy + y3<0. Once we defined our function, we can plot it in the usual way. The complete script and the figure is given below.

f(x,y)=(x*x*x - 2*x*y + y*y*y>0)?1:1/0
unset colorbox
set isosample 300, 300
set xlabel 'x'
set ylabel 'y'
set sample 300
set pm3d map
splot [-2:2] [-2:2] f(x,y) t 'x^3 - 2xy + y^3>0'

As I pointed out above, the second argument of the ternary operator can also be a ternary operator. So, what if we wanted to plot the intersection of the domain of the following two inequalities?

x3 - 2xy + y3 > 0
x2 - 2x + y3 > 0

Generated on 15 Sep 2009 for Gnuplot tricks by  doxygen 1.6.1