Least Action

Nontrivializing triviality..and vice versa.

Archive for June 2012

Gnuplot with C/C++

leave a comment »

Sometimes, it is convenient to call gnuplot from within your own C/C++ code rather than having the code create a data file, and manually execute gnuplot every time to re-plot using the contents of the file. This is easy if you use Linux: just use a pipe. For instance:


#include <iostream>
#include <stdio.h>
#include <cstdlib>

using namespace std;

int main(){
// Code for gnuplot pipe
FILE *pipe = popen("gnuplot -persist", "w");
fprintf(pipe, "\n");

// Your code goes here

// Don't forget to close the pipe
fclose(pipe);
return 0;
}

Note that we have had to use C routines to call gnuplot. But there’s a problem with this code: gnuplot will generate the plot only when the pipe is closed. So if you have multiple plot statements, or if you want to refresh the same plot (as for instance, in an animation scenario) you will find that the above approach will result in the plots getting asynchronously updated right at the end.

So how does one ensure that after every plot command, a plot is actually generated (or an existing one refreshed) Immediately? The key is to flush the buffer using fflush. Simply insert


fflush(pipe);

below every plot call to gnuplot. If you have an animation, then in order to make the transitions smoother, you might want to include a delay subroutine. A simple one can be built using the clock routines in time.h. For an example, click here.

Thanks to Vidushi Sharma for bringing these issues to my attention.

Advertisements

Written by Vivek

June 22, 2012 at 14:13