Search code examples
c++c++11gnuplot

What is the detailed method to use Gnu Plot in my C++ code?


I gave gone through many links that kind of answer the question but none of them provides a detailed step-by-step method to do so. I have a piece of c++ code that requires plotting using gnu plot.

I even referred to the documentation. Its not useful for me.


Solution

  • So, for Windows 10, C++11 or C++14, the process goes as follows:-

    1) Download the zip file from Sourceforge and extract it in "C:\gnuplot".

    2) Download gnuplot additional files (IDK their use !) from Google Code. Extract these files in the same folder i.e, "C:\gnuplot".

    3) Open this gnuplot folder and double click the file with .bat extension (Batch file). This is how your folder should look like: enter image description here

    4) Add the path of the binary to environment variable path enter image description here

    Now, you can continue with your code. Suppose you use Code Blocks to plot a curve using the following snippet:

    //Plot the results
        vector<float> x;
        vector<float> y1, y2;
    
        for (int i = 0; i < 1000; i++) {
            x.push_back(i * 2 * PI / 1000);
            y1.push_back(sin(i * 2 * PI / 1000));
            y2.push_back(i * 2 * PI / 1000); //Any random function...
        }
    
    FILE * gp = popen("gnuplot", "w");
        fprintf(gp, "set terminal wxt size 600,400 \n");
        fprintf(gp, "set grid \n");
        fprintf(gp, "set title '%s' \n", "f(x) = sin (x)");
        fprintf(gp, "set style line 1 lt 3 pt 7 ps 0.1 lc rgb 'green' lw 1 \n");
        fprintf(gp, "set style line 2 lt 3 pt 7 ps 0.1 lc rgb 'red' lw 1 \n");
        fprintf(gp, "plot '-' w p ls 1, '-' w p ls 2 \n");
    
        //Exact f(x) = sin(x) -> Green Graph
        for (int k = 0; k < x.size(); k++) {
            fprintf(gp, "%f %f \n", x[k], y1[k]);
        }
        fprintf(gp, "e\n");
    
        //f(x) = sin(x) -> Red Graph
        for (int k = 0; k < x.size(); k++) {
            fprintf(gp, "%f %f \n", x[k], y2[k]);
        }
        fprintf(gp, "e\n");
    
        fflush(gp);
        system("pause");
    
        pclose(gp); 
    

    On compiling it, you may see an error that says "popen not found" or "pclose not found". The solution to this is:

    • For popen, Add
    extern "C" FILE *popen(const char *command, const char *mode);
    
    

    in the global scope before the main() routine.

    • For pclose, simply, comment it out.
     //pclose(gp);
    

    Now, your program should run compile normally and the gnuplot window should spontaneously pop up along with the cmd window. It may be slow to respond sometimes and may even stop responding, but wait and enjoy the results.