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.
Compile and run the code below in your own C environment.
#include <stdio.h>
#include <stdlib.h>
int main(void){
float data[5] = {1.2, 2.5, 4.0, 3.1, 5.5};
int i;
int size = 5;
FILE *gfile = popen("gnuplot", "w");
fprintf(gfile, "set terminal png\n");
fprintf(gfile, "set output 'plot_graph.png'\n");
fprintf(gfile, "plot '-'\n");
for(i=0; i<size; i++){
fprintf(gfile, "%d %f\n", i, data[i]); // coordinates x and y
}
fprintf(gfile, "e\n");
pclose(gfile);
return 0;
}
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:
Compile and run the code below in your own C environment.
#include <stdio.h>
#include <stdlib.h>
int main(void){
float data[5] = {1.2, 2.5, 4.0, 3.1, 5.5};
float data2[5] ={5.4, 0.2, 3.9, 8.2, 4.6};
int i;
int size = 5;
FILE *gfile = popen("gnuplot", "w");
fprintf(gfile, "set terminal png\n");
fprintf(gfile, "set output 'plot_multiple_curves.png'\n");
fprintf(gfile, "set title 'Comparison data and data2'\n");
fprintf(gfile, "set xlabel 'time (seconds)'\n");
fprintf(gfile, "set ylabel 'position (m)'\n");
fprintf(gfile, "plot '-' with lines title 'data', '-' with lines title 'data 2'\n");
for(i=0; i<size; i++){
fprintf(gfile, "%d %f\n", i, data[i]); // coordinates x and y
}
fprintf(gfile, "e\n");
for(i=0; i<size; i++){
fprintf(gfile, "%d %f\n", i, data2[i]); //coordinates of x and y for second curve
}
fprintf(gfile, "e\n");
pclose(gfile);
return 0;
}

