Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and gnuplot

Tags:

c++

gnuplot

This is my first post and I'm quite a novice on C++ and compiling in general.

I'm compiling a program which requires some graphs to be drawn. The program create a .dat file and then i should open gnuplot and write plot '.dat'. That's fine.

Is there a way to make gnuplot automatically open and show me the plot I need? I should use some system() function in the code to call gnuplot but how can I make him plot what I need?

Sorry for my non-perfect English :s

Thanks for the attention anyway!

like image 479
Marco Orrù Avatar asked Jan 08 '09 14:01

Marco Orrù


2 Answers

Depending on your OS, you might be able to use popen(). This would let you spawn a gnuplot process and just just write to it like any other FILE*.

If you have datapoints to plot, you can pass them inline with the plot "-" ... option. Similarly, you may want to explore set data style points/lines/linespoints/etc options.


Without pause or persist, gnuplot will terminate upon end-of-input-stream. In your example case, that would be when the end of the file is reached.


To produce (write) an output file (graph), use:

set terminal png small
set output "filename.png"

There's lots of options to set terminal. Png is usually there. If not, perhaps gif, tiff, or jpeg?

Watch out for overwriting the file!

You may want to use set size 2,2 to make a larger graph. Some set terminal variants also allow you to specify the size.

like image 93
Mr.Ree Avatar answered Sep 17 '22 13:09

Mr.Ree


I'm learning this today too. Here is a small example I cooked up.

#include <iostream>
#include <fstream> 
using namespace std;
int main(int argc, char **argv) {
    ofstream file("data.dat");
    file << "#x y" << endl;
    for(int i=0; i<10; i++){
        file << i << ' ' << i*i << endl;
    }
    file.close();
    return 0;
}

Save that as plot.cpp and compile that with g++:

g++ plot.cpp -o plot

Run the program to create the .dat file:

./plot

Save the following gnuplot script as plot.plt:

set terminal svg enhanced size 1000 1000 fname "Times" fsize 36
set output "plot.svg"
set title "A simple plot of x^2 vs. x"
set xlabel "x"
set ylabel "y"
plot "./data.dat" using 1:2 title ""

Run the script with gnuplot to generate your .svg file:

gnuplot plot.plt

The resulting plot will be in plot.svg. If you leave out the first couple lines that specify the output, it will render in a window. Have fun!

like image 34
Andrew Wagner Avatar answered Sep 21 '22 13:09

Andrew Wagner