C++ Gnuplot pipe input from C++ defined variables

3.2k views Asked by At

I am using C++ to pipe commands to gnuplot using the following code:

FILE *gnuplotPipe = popen("gnuplot -persist", "w");  // Open a pipe to gnuplot

if (gnuplotPipe) {   // If gnuplot is found

  fprintf(gnuplotPipe, "reset\n"); //gnuplot commands
  fprintf(gnuplotPipe, "n='500'\n");
  fprintf(gnuplotPipe, "max='1500'\n");
  fprintf(gnuplotPipe, "min='-1500\n");
  fprintf(gnuplotPipe, "width=(max-min)/n\n");
  fprintf(gnuplotPipe, "hist(x,width)=width*floor(x/width)+width/2.0\n");
  fprintf(gnuplotPipe, "set term png #output terminal and file\n");
  fprintf(gnuplotPipe, "set output 'Observable_Histogram.png'\n");
  fprintf(gnuplotPipe, "set xrange [min:max]\n");
  fprintf(gnuplotPipe, "set yrange [0:]\n");
  fprintf(gnuplotPipe, "set offset graph 0.05,0.05,0.05,0.0\n");
  fprintf(gnuplotPipe, "set xtics min,(max-min)/5,max\n");
  fprintf(gnuplotPipe, "set boxwidth width*0.9\n");
  fprintf(gnuplotPipe, "set style fill solid 0.5\n");
  fprintf(gnuplotPipe, "set tics out nomirror\n");
  fprintf(gnuplotPipe, "set xlabel 'Observable'\n");
  fprintf(gnuplotPipe, "set ylabel 'Counts'\n");
  fprintf(gnuplotPipe, "set title 'Observable'\n");
  fprintf(gnuplotPipe, "plot 'output.txt' u (hist($1,width)):(1.0) smooth freq w boxes lc rgb'green' notitle\n");

  fflush(gnuplotPipe); //flush pipe

  fprintf(gnuplotPipe,"exit \n");   // exit gnuplot
  pclose(gnuplotPipe);    //close pipe

}

This works perfectly, however I want it to be able to take input from previously defined variables in c++.
For example, instead of straight up defining n='500', min='-1500', max='1500', etc., I want to use variables that I already defined (from user input) earlier in the code, i.e. int n, int max, int min, string title, string xlabel, etc.

I have tried everything I can think of, such as:

fprintf(gnuplotPipe, "max=");
fprintf(gnuplotPipe, 'max');

or:

fprintf(gnuplotPipe, "max=" 'max' "\n");

and nothing works unfortunately.

Does anyone have any ideas on how I could get this working?

Thanks in advance!

1

There are 1 answers

0
PlushBeaver On BEST ANSWER

The thing you want to do is exactly what fprintf() is for, see the manual. Here is an example:

int maximum = 500; // taken from user input maybe
fprintf(gnuplotPipe, "max=%d\n", maximum);

You're currently using fprintf() in a way of more simple fputs().