3
votes

I'm a complete noob to gnuplot and linux in general. I need to plot scientific graphs for my project for which I will be using C++. After looking for various plotting options available, I've decided to use gnuplot for plotting due to its features and quality of graphs. So I downloaded gnuplot as a program and could plot the graphs using .dat files, however I need to plot the graphs within C++ without explicitly launching gnuplot. Is it possible to plot dynamic graphs using gnuplot? I would also like to plot the solution as is it computed for every time step!

I came to know that gnuplot-iostream interface makes this possible. However I did not understand how to install this library for C++ at all. I do not understand Git, or anything posted on the website to be able to configure that library. Can anybody point me to the tutorial/how to document for the same? I have Ubuntu 12.04 and also Windows 8.1.

Is it possible to configure this library with an IDE (I'm using code::blocks), if yes how that can be done?

2

2 Answers

7
votes

First of all gnuplot-iostream relies on the Boost library, it is a very common library, but it doesn't come together with the C++ compiler, so make sure it is properly installed.

Obviously it also needs gnuplot: if it is properly installed you should be able to launch it from the terminal.

Then paste this minimal example in a file main.cpp:

#include <vector>
#include <utility>
#include "gnuplot-iostream.h"

int main() {
  std::vector<std::pair<double,double>> data;
  data.emplace_back(-2,-0.8);
  data.emplace_back(-1,-0.4);
  data.emplace_back(0,-0);
  data.emplace_back(1,0.4);
  data.emplace_back(1,0.8);

  Gnuplot gp;
  gp << "plot [-5:5] sin(x) tit 'sin(x)', '-' tit 'data'\n";
  gp.send1d(data);
  return 0;
}

Save the header gnuplot-iostream.h in the same folder and compile with:

g++ -std=c++11 main.cpp -o main -lboost_iostreams -lboost_system -lboost_filesystem

When running ./main you should get a plot of the sine function and of the few dots.

1
votes

recently I was using Gnuplot to visualize data from an iterative solver. To run Gnuplot in "pseudo" real-time I did the following steps:

  • establish a pipeline from C++ to Gnuplot:

    FILE *GnuPipe = popen("...\bin\pgnuplot -persist","w");

  • start the solver (or data source) and write to a file e.g. 'data.txt'

  • start a script which tells Gnuplot to replot the data.txt as long as flag is NOT set. In this case I created a text file 'flag.txt' and wrote in a=0, which serves as flag. The script for Gnuplot could look like:

    load 'flag.txt'
    plot 'data.txt' u 1:2 with lines
    pause 0.1
    if (a==0) reread
    
  • if the solver converges, or if there is no further data to plot, set a=1 in the 'flag.txt'
  • Gnuplot is loading the 'flag.txt' and sees that the flag is set and stops rereading.