Kahibaro Login Register
Previous
First Graph »

First Graph

Creating Graphs

Creating graphs is done with the class TGraph. Similar to TH1F, the constructor is highly overloaded. Hence, there are many options that can be selected for creating a graph. However, the easiest way for a graph is given as

void graph()
{
  double x[4] = {1, 2, 3, 4};
  double y[4] = {1, 4, 9, 16};

  TCanvas *c1 = new TCanvas());
  TGraph *gr = new TGraph(4, x, y);
  gr->Draw();
}

This code creates two arrays with values for the $x$ and $y$ axes and then passes them to the graph. The result looks as follows:

A simple graph
A simple graph

As one can see, the standard title for a graph is simply Graph.

Changing Name and Title

Unlike histograms, the name and title are typically not defined in the constructor. For changing the name of the graph, the member function SetName(TString) can be used. The title can be changed using the function SetTitle(TString). This results in the following code that has to be added:

gr->SetName("gr");
gr->SetTitle("First Graph;X;Y");

Again, we can define the titles of the $x$ and $y$ axes with semicolons in the title. Now we get the following result:

A graph with name and titles.
A graph with name and titles.

Lines and Markers

We can also change the marker and line styles of the graph to improve the visbility. For this purpose, several member functions were implemented. For example, we can add the following code to the example above:

gr->SetMarkerColor(4);
gr->SetMarkerStyle(21);
gr->SetMarkerSize(0.5);
gr->SetLineColor(4);
gr->SetLineWidth(2);

This leads then to the following result:

Changing styles and colors of markers and lines.
Changing styles and colors of markers and lines.

The color of the line and markers was chosen as blue. The marker style is a filled circle and the marker size is is 4, whereas the line thickness was defined as 2.

Previous