Skip to main content

Section 30.1 Plotting with gnuplot

gnuplot is a command-line plotting program. Rather than writing data to a file and opening gnuplot separately, we can open a pipe directly to gnuplot from within our C program using popen(), then write gnuplot commands and data to that pipe with fprintf(), exactly as if we were writing to a file:
FILE *gfile = popen("gnuplot", "w");
fprintf(gfile, "set terminal png\n");
fprintf(gfile, "set output 'my_plot.png'\n");
fprintf(gfile, "plot '-'\n");        /* '-' means: data follows inline */
/* ... write x,y pairs, one per line ... */
fprintf(gfile, "e\n");               /* 'e' ends the inline data       */
pclose(gfile);
Here is a complete, minimal example that plots a single array of data points. Click Run to see the plot appear below the code.

admin.....open in new window

We can plot multiple curves on the same figure, and add titles and axis labels, by extending the gnuplot commands we send through the pipe:

admin.....open in new window