Quick Tip: Piping to gnuplot from C

by Amit


Update, 21/10/09 :Thanks to A.K’s comment, Its “gnuplot” and not “GNU plot”

Couple of things first up:

  • gnuplot supports piping, So, echo "plot sin(x)" | gnuplot will plot the sin(x) function.
  • However, the plot disappears even before you could see it. For that echo "plot sin(x)" | gnuplot -persist , is useful. It persists the GNU plot main window

The usefulness of the second point is that, if you have a “pipe descriptor” describing a pipe to the open gnuplot instance , you can plot more plots on the first plot, without opening a new gnuplot instance. We shall be using this idea in our code.

C (Cee Language)

</p>
<p>#include &lt;stdio.h&gt;<br />
#define GNUPLOT &quot;gnuplot -persist&quot;</p>
<p>int main(int argc, char **argv)<br />
{<br />
        FILE *gp;<br />
        gp = popen(GNUPLOT,&quot;w&quot;); /* 'gp' is the pipe descriptor */<br />
        if (gp==NULL)<br />
           {<br />
             printf(&quot;Error opening pipe to GNU plot. Check if you have it! \n&quot;);<br />
             exit(0);<br />
           }</p>
<p>        fprintf(gp, &quot;set samples 2000\n&quot;);<br />
        fprintf(gp, &quot;plot abs(sin(x))\n&quot;);<br />
        fprintf(gp, &quot;rep abs(cos(x))\n&quot;);<br />
        fclose(gp);</p>
<p>return 0;<br />
}<br />

The above code will produce a comparative plot of absolute value of sin(x) and cos(x) on the same plot.  The popen function call is documented here. This code/idea should work on GCC and Linux and any other language and OS that supports piping.

Utility: If you have a application which is continuously generating some data, which you will finally plot, then you can plot the data for every new set of data- that gives a nice visualization about how the data is changing with the iterations of your application. This is a perfect way to demonstrate convergence to the best solutions in Evolutionary Algorithms, such as Genetic Algorithms.

Links:

  1. Piping
  2. gnuplot Homepage
Advertisement