Thursday, May 14, 2009

Calling Gnuplot from c Using Pipes... Again!

Here's another way of calling gnuplot. I like this method because it provides a standalone function that plots your results. Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void plotResults(double* xData, double* yData, int dataSize);
int main() {
int i = 0;
int nIntervals = 100;
double intervalSize = 1.0;
double stepSize = intervalSize/nIntervals;
double* xData = (double*) malloc((nIntervals+1)*sizeof(double));
double* yData = (double*) malloc((nIntervals+1)*sizeof(double));
xData[0] = 0.0;
double x0 = 0.0;
for (i = 0; i < nIntervals; i++) {
x0 = xData[i];
xData[i+1] = x0 + stepSize;
}
for (i = 0; i <= nIntervals; i++) {
x0 = xData[i];
yData[i] = sin(x0)*cos(10*x0);
}
plotResults(xData,yData,nIntervals);
return 0;
}
void plotResults(double* xData, double* yData, int dataSize) {
FILE *gnuplotPipe,*tempDataFile;
char *tempDataFileName;
double x,y;
int i;
tempDataFileName = "tempData";
gnuplotPipe = popen("c:\\gnuplot\\bin\\pgnuplot -persist","w");
if (gnuplotPipe) {
fprintf(gnuplotPipe,"plot \"%s\" with lines\n",tempDataFileName);
fflush(gnuplotPipe);
tempDataFile = fopen(tempDataFileName,"w");
for (i=0; i <= dataSize; i++) {
x = xData[i];
y = yData[i];
fprintf(tempDataFile,"%lf %lf\n",x,y);
}
fclose(tempDataFile);
printf("press enter to continue...");
getchar();
remove(tempDataFileName);
fprintf(gnuplotPipe,"exit \n");
} else {
printf("gnuplot not found...");
}
}


This code should run as is. Of course, feel free to take the plot function and use it in your own codes.

Cite as:
Saad, T. "Calling Gnuplot from c Using Pipes... Again!". Weblog entry from Please Make A Note. https://pleasemakeanote.blogspot.com/2009/05/calling-gnuplot-from-c-using-pipes.html?m=0

2 comments:

  1. please ny 1 can help me hw to call/plot graph in gnuplot in c using a DAT file. that is i am having a DAT file. nw i want graph of that DAT file using c code.please give me sm tips.

    ReplyDelete
  2. I need more help to understand many of the lines that you share, for instance , I have not idea what is double* xData = (double*) malloc((nIntervals+1)*sizeof(double));
    double* yData = (double*) malloc((nIntervals+1)*sizeof(doubl

    ReplyDelete