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

Hi. You know, gnuplot has nothing to do with GNU project. Look at gnuplot FAQ.

Not that GNU isn’t great.

Thanks A.K. Updated the post.

Using the same technique you can also interface MATLAB on a Unix system. Just replace the ‘gnuplot’ by the location of ‘matlab’ on your system.

nice post. is there a free version of C on the net. I am currently using TC Lite. By the way, my blog is about matheamtics and the integration of software in teaching math. You may want to check it out:

http://math4allages.wordpress.com

Hi. Thx for nice tips. Thera is also other way : make data file in C and then plot in gnuplot.

http://pl.wikibooks.org/wiki/Gnuplot

It’s hard to find your website in google.

I found it on 13 spot, you should build quality backlinks , it will help you to increase traffic.

I know how to help you, just search in google – k2 seo tips and tricks