Filling a TGraph with strings on axis label

Although as couet said this is not intended by root it is still possible because the TGraph class uses an internal TH1 for drawing so all possibilities of a TH1 are more or less available for TGraphs. Assuming your vecors are of the std::vector type I’ve written you a short macro that does what you want. I names the vecors simply y_vals and x_labels. The problem is that you still have to set a numeric x-value, because otherwise root does not know where on the x-axis a specific string has to be drawn. In my example I just enumerate the points from 1 to Number of Points, which I assume is what you intended:

std::vector<Double_t> y_vals;
std::vector<std::string> x_labels;

// 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->Draw("AP"); // Draw the TGraph

Hope this helps you. I tested it and it worked like I expected it to.

1 Like