Friday, September 14, 2012

Calling gnuplot from C/C++ on Mac OS X

Here's another way of calling gnuplot from Mac OS X.

First install gnuplot either from their website or using macports. I like the macports model because it installs all dependencies for you automatically.
  1. Install macports from: http://www.macports.org/ 
  2. Open up your terminal
  3. type: sudo port selfupdate (to update port names)
  4. type: sudo port install gnuplot
and Voila! you now have gnuplot installed on your mac. To test it type: gnuplot and you should enter the gnuplot environment. Another caveat that you have to bear in mind when using gnuplot on mac is that you have to tell gnuplot to use x11. You do this as follows:
  1. Open up your terminal
  2. type: gnuplot
  3. type: set terminal x11
Now to the fun stuff. Here's the code that I used before to call gnuplot for windows, but modified to work on Unix based systems such as Mac.

#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("gnuplot","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/C++ on Mac OS X". Weblog entry from Please Make A Note. http://pleasemakeanote.blogspot.com/2012/09/calling-gnuplot-from-cc-on-mac-os-x.html

1 comment:

  1. How do you get rid of line 42,43 and optionally 45 so you can draw a new plot without avoid contact with the shell. Gustengren

    ReplyDelete