Wrap Gnuplot in C

Cong Wang

11:04:06 PM Oct 27

It is nice to visualize data in a C program with Gnuplot. This wrapper does exactly it. Please refer to this article for the idea.

gnuplot.h

FILE * 
init_gp(void);


void
close_gp(FILE * output);


void
write_gp(FILE * stream, char * command);

gnuplot.c

#include <stdio.h>
#include <stdlib.h>

FILE * 
init_gp(void)
{
  /* Create a pipe for gnuplot... */
  FILE * output;
  output = popen ("gnuplot", "w");

  /* Check if open correctly */
  if (!output)
    {
      fprintf (stderr, "Gnuplot failed to open!!!\n");
      exit (EXIT_FAILURE);
    }

  return output;
}


void
close_gp(FILE * output)
{
  if (pclose (output) != 0)
    {
      fprintf (stderr,
               "...Error was encountered in running Gnuplot!!!\n");
      exit (EXIT_FAILURE);
    }
}


void
write_gp(FILE * stream, char * command)
{
  fprintf (stream, "%s\n", command);
  fflush (stream);

  if (ferror (stream))
    {
      fprintf (stderr, "...Output to stream failed!!!\n");
      exit (EXIT_FAILURE);
    }

}

Example – main.c

#include <stdio.h>
#include <stdlib.h>
#include "gnuplot.h"

#define GP(CMD) write_gp(gp, CMD)

int
main (void)
{
  /* Initialize Gnuplot... */
  FILE * gp = init_gp();

  /* Seed the random number */
  srand(0);

  /* Generate 500 random numbers ranging from -100 to 100... */
  int len = 500;
  int randoms [len];
  for (int i = 0 ; i < len; ++i)
    {
      randoms[i] = rand() % 200 - 100;
    }

  /* Data-driven plotting... */
  GP("plot '-' using 1:2 with linespoints pointsize 2 linewidth 0.25 linecolor rgb 'blue',\\");
  GP("");

  for (int i = 0; i < len; ++i)
    {
      char cmd [100];
      sprintf(cmd, "%d    %d", i, randoms[i]);
      GP(cmd);
    }
  GP("e");


  /* Displaying Gnuplot window until any key press is accepted... */
  char anykey[2];
  printf("Press any key to exit...");
  fgets(anykey, 2, stdin);

  /* Terminate Gnuplot... */
  // write_gp(gp, "exit");
  GP("exit");
  close_gp(gp);

  return EXIT_SUCCESS;
}