Gnuplot: conditional plotting ($2 == 15 ? $2 : ‘1/0’) with lines

+1 for a great question. I (mistakenly) would have thought that what you had would work, but looking at help datafile using examples shows that I was in fact wrong. The behavior you’re seeing is as documented. Thanks for teaching me something new about gnuplot today 🙂

“preprocessing” is (apparently) what is needed here, but temporary files are not (as long as your version of gnuplot supports pipes). Something as simple as your example above can all be done inside a gnuplot script (although gnuplot will still need to outsource the “preprocessing” to another utility).

Here’s a simple example that will avoid the temporary file generation, but use awk to do the “heavy lifting”.

set datafile sep ':'  #split lines on ':'
plot "<awk -F: '{if($2 == 15 && $3 == 8){print $0}}' mydata.dat" u 1:4 w lp title 'v=15, l=8'

Notice the “< awk …”. Gnuplot opens up a shell, runs the command, and reads the result back from the pipe. No temporary files necessary. Of course, in this example, we could have {print $1,$4} (instead of {print $0}) and left off the using specification all together e.g.:

plot "<awk -F: '{if($2 == 15 && $3 == 8){print $1,$4}}' mydata.dat" w lp title 'v=15, l=8'

will also work. Any command on your system which writes to standard output will work.

plot "<echo 1 2" w p  #plot the point (1,2)

You can even use pipes:

plot "<echo 1 2 | awk '{print $1,$2+4}'" w p #Plots the point (1,6)

As with any programming language, remember not to run untrusted scripts:

HOMELESS="< rm -rf ~"
plot HOMELESS  #Uh-oh (Please don't test this!!!!!)

Isn’t gnuplot fun?

Leave a Comment