Hi,
I have a root file with few histograms in it. I have to make a TGraph - on xAaxis to have data form one histogram, and yAxis - from other histogram. Is it possible? And can you give me some hints how to do it?
Thanks!
may be something like that:
{
// Open the Root file containing your histograms
auto file = new TFile("YourRootFile.root");
// Assuming you have two histograms named "histogramX" and "histogramY"
TH1F *histogramX = (TH1F*)file->Get("histogramX"); // Retrieve the first histogram
TH1F *histogramY = (TH1F*)file->Get("histogramY"); // Retrieve the second histogram
int numBinsX = histogramX->GetNbinsX();
TGraph *graph = new TGraph();
for (int i = 1; i <= numBinsX; ++i)
{
double x = histogramX->GetBinCenter(i); // Use bin center as x-value
double y = histogramY->GetBinContent(i); // Use bin content as y-value
graph->AddPoint(x, y); // Add the point in the TGraph
}
// Draw the TGraph
graph->Draw("A*L"); // APL option is used to draw points with lines
}
@couet Well, the code is correct now, but I think it is worse than the “original” version, especially for a “new user”. You now start with an empty graph, but then the “AddPoint” will often need to reallocate the arrays, which always takes additional time. In the “original” version, you nicely allocated the correct arrays just once at the beginning and only then filled them (so that “inexperienced users” could also learn how to avoid the “costly” memory reallocations).
I was more thinking about code simplicity. But yes the old one has the advantages you describe. here it is:
{
// Open the Root file containing your histograms
auto file = new TFile("YourRootFile.root");
// Assuming you have two histograms named "histogramX" and "histogramY"
TH1F *histogramX = (TH1F*)file->Get("histogramX"); // Retrieve the first histogram
TH1F *histogramY = (TH1F*)file->Get("histogramY"); // Retrieve the second histogram
int numBinsX = histogramX->GetNbinsX();
TGraph *graph = new TGraph(numBinsX);
for (int i = 1; i <= numBinsX; ++i)
{
double x = histogramX->GetBinCenter(i); // Use bin center as x-value
double y = histogramY->GetBinContent(i); // Use bin content as y-value
graph->SetPoint(i-1,x, y); // Set the point in the TGraph
}
// Draw the TGraph
graph->Draw("A*L"); // APL option is used to draw points with lines
}
Thank you very much. I check the code, but in this case I get data from two histos in Xaxis. I want to have data from one histos on X, other on Y. If I have two histograms : Mass and Temperature for example, I want to make graph Mass vs Temperature.
That’s what is done:
double x = histogramX->GetBinCenter(i); // Use bin center as x-value
double y = histogramY->GetBinContent(i); // Use bin content as y-value
It looks like working. Thank you!
And that’s what you expected?