'Using the ROOT framework to plot a mathematical function in C++

I'm trying to plot a function graph using the "ROOT" data analysis framework with C++. I've tried to use this code (found in a user guide on the web):

   Int_t n = 20;
   Double_t x[n], y[n];
   for (Int_t i=0;i<n;i++) {
      x[i] = i*0.1;
      y[i] = 10*sin(x[i]+0.2);
   }

   // create graph
   TGraph *gr  = new TGraph(n,x,y);
   TCanvas *c1 = new TCanvas("c1","Graph Draw Options",
                             200,10,600,400);

   // draw the graph with axis, continuous line, and put
   // a * at each point
   gr->Draw("AC*");

The expected behavior is to get a picture with the 2D plot of the function (see picture in the user guide). But unfortunately, no graph shows up.

When I use the ROOT prompt, I can show a canvas if I just do:

root [3] g = new TGraph()
root [4] g->Draw()

But, again, if I write and compile this from C++ (using g++) it doesn't open any canvas nor show any graph. It sometimes shows the message: Info in <TCanvas::MakeDefCanvas>: created default TCanvas with name c1 but nothing happens again - no graph or canvas shows up.

How can I use ROOT in a C++ program in order to produce a graphical plot of a function?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source