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?
Did you follow the steps here, https://root.cern/primer/?#interpretation-and-compilation ?
Here is a working example.
#include <TApplication.h>
#include <TGraph.h>
void guiDemo() {
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);
// draw the graph with axis, continuous line, and put
// a * at each point
gr->Draw("AC*");
}
int main(int argc, char **argv) {
TApplication app("Root app", &argc, argv);
guiDemo();
app.Run();
return 0;
}
Compile it with
g++ -Wall -Wextra -o demo demo.cpp `root-config --cflags --libs`