TGraph with X-axis of "char" type?


ROOT Version: 6.12.02


Hi, I am using TGraph for one of my projects.

In fact, it is almost identical to multigraph.C in tutorial/graphs of root package.

{
   auto c2 = new TCanvas("c2","c2",600,400);
   TGraph *g[3];
   Double_t x[10] = {0,1,2,3,4,5,6,7,8,9};
   Double_t y[10] = {1,2,3,4,5,5,4,3,2,1};
   auto mg = new TMultiGraph();
   for (int i=0; i<3; i++) {
      g[i] = new TGraph(10, x, y);
      g[i]->SetMarkerStyle(20);
      g[i]->SetMarkerColor(i+2);
      for (int j=0; j<10; j++) y[j] = y[j]-1;
      mg->Add(g[i]);
   }
   mg->Draw("APL");
   mg->GetXaxis()->SetTitle("E_{#gamma} (GeV)");
   mg->GetYaxis()->SetTitle("Coefficients");
   // Change the axis limits
   gPad->Modified();
   mg->GetXaxis()->SetLimits(1.5,7.5);
   mg->SetMinimum(0.);
   mg->SetMaximum(10.);
}

Except one modification…

I would like to have a string (char) as x-axis label.
(But the reference for TGraph says int,float,doubles are only options for x,y)

I have been referred to hlabels1.C, which has char type as x-axis, but I want to use TGraph since it gives me easy option for error bars.

Could you help me with the problem?

Thank you!

@couet, perhaps you can help here please?

Thank you so much,
Oksana.

I think this thread answers your question: https://root-forum.cern.ch/t/filling-a-tgraph-with-strings-on-axis-label/20401/3




std::vector<Double_t> y_vals {1,2,3,4,5,6,7,8,9,10};
std::vector<std::string> x_labels {"a","b","c","d","e","f","g","h","i","j"};;
void timegraph()
{

// Fill the vectors here

TGraph* tg = new TGraph(TMath::Min(y_vals.size(), x_labels.size())); // Create the TGraph object

for (Int_t i = 0; i < TMath::Min(y_vals.size(), x_labels.size()); i++) { // Loop over all entries
    tg->SetPoint(i, i + 1., y_vals[i]); // Set The point itself
    tg->GetXaxis()->SetBinLabel(tg->GetXaxis()->FindBin(i + 1.), x_labels[i].c_str()); // Find out which bin on the x-axis the point corresponds to and set the bin label
}

   tg->SetLineColor(2);
   tg->SetLineWidth(4);
   tg->SetMarkerColor(4);
   tg->SetMarkerSize(1.5);
   tg->SetMarkerStyle(21);

tg->Draw("AP"); // Draw the TGraph

   }

I get a blank x-axis… In addition, how would I be able to add error bar for this method… It only uses SetPoint

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.