zakjma
zakjma

Reputation: 2110

Gnuplot - save output

I use linux,C++. I want to save output from gnuplot. How can I do it using c++? I tried below code. It generates a png file.But it hasn't plot point. I want to do two task

How can I do them?

FILE *pipe = popen("gnuplot -persist", "w");

// set axis ranges
fprintf(pipe,"set xrange [0:11]\n");
fprintf(pipe,"set yrange [0:]\n");

fprintf(pipe, "set terminal png\n");
fprintf(pipe, "set output 'b.png'\n");
int b = 5;int a;
// to make 10 points
std::vector<int> x (10, 0.0); // x values
std::vector<int> y (10, 0.0); // y values
for (a=0;a<5;a++) // 10 plots
{
    x[a] = a;
    y[a] = 2*a;// some function of a
    fprintf(pipe,"plot '-'\n");
    // 1 additional data point per plot
    for (int ii = 0; ii <= a; ii++) {
        fprintf(pipe, "%d %d\n", x[ii], y[ii]); // plot `a` points
    }

    fprintf(pipe,"e\n");    // finally, e
    fflush(pipe);   // flush the pipe to update the plot
    usleep(1000000);// wait a second before updating again
}

Upvotes: 2

Views: 4024

Answers (1)

sweber
sweber

Reputation: 2986

It seems that your problem is not the C-Code itself (or controlling gnuplot that way), as it works perfectly. You can generate the image and if you omit the set terminal and set output commands, you (at least I) get a gnuplot window on the sceen.

However, it is not fully clear what you want to plot. From your code, it seems that you want to update the plot each time you generated a new xy pair. In this case, note the different behavior of different terminals for several subsequent plot commands:

  • PNG: The file is closed after the first plot (as you said, it shows just one point!)
  • PDF (pdfcairo): Multi page PDF with one plot on each page
  • GIF with option animate: animated GIF with one plot per frame.
  • Window (x11, wxt, ...): Each plot command is processed one after one, only the last remains visible (you may have seen the others flickering on the screen before)

If this is what you want, you can first plot everything to the screen (as said, without set terminal and set output) and at the end, dump the last plot into a file:

plot sin(x) title 'a curve'          # opens a window on screen and shows curve

set term 'pngcairo'
set output 'b.png'
replot                # redo the last plot command
unset output          # clean closing of file

But if you want to plot several data sets into one plot, you need a single plot command:

plot '-' title 'first plot', '-' title 'second plot'
input data ('e' ends) > 1 2
input data ('e' ends) > 2 3
input data ('e' ends) > 5 6
input data ('e' ends) > e
input data ('e' ends) > 7 8
input data ('e' ends) > 9 10        
input data ('e' ends) > 11 12
input data ('e' ends) > e


set terminal pngcairo
set output 'b.png'
replot
unset output

Upvotes: 1

Related Questions