I have a TH2 from which I want to draw a TH1 that shows the values of the former along a desired horizontal (or vertical) line.
A TH2 is the plot of an histogram h(x, y). If we consider all the bins along x, at a given y = c = const, I want the TH1 that plots h(x, c).
Consider the following sample:
int test () {
TH2D *h2 = new TH2D("h2a", "h2b", 10, -10, 10, 10, -10, 10);
for (Int_t i = 1; i <= h2->GetNbinsX(); i++)
for (Int_t j = 1; j <= h2->GetNbinsY(); j++)
h2->SetBinContent(i, j, i*j);
TCanvas *c1 = new TCanvas("c1", "c1");
h2->Draw("COLZ");
h2->GetYaxis()->SetRangeUser(0, 0);
TH1D *h1 = h2->ProjectionX("pX", h2->GetXaxis()->FindBin((double)-10), h2->GetXaxis()->FindBin((double)10));
TCanvas *c2 = new TCanvas("c2", "c2");
h1->Draw("HIST E0");
return 0;
}
I want to plot the section at y = 0, that is h(x, 0).
I tried with both h2->ProjectionX(...) and h2->ProfileX(...). Only the former gives something close to what I want but, for each bin along x, it seems it makes and plots the integral along y at that x.
for each bin along x, it seems it makes and plots the integral along y at that x.
Indeed a histogram projection integrates the bin contents along one axis, see e.g. this thread. You can use the firstybin and lastybin arguments to only consider a slice of the Y axis when performing the projection (see the docs).
So to get a slice along x at a given constant y you need to set firstybin and lastybin to the bin number corresponding to that y value:
// haven't tested the code but it should give you an idea
const auto yBin = h2->GetYaxis()->FindBin(c);
auto xProjection = h2->ProjectionX("pX", yBin, yBin);