Draw the section of a TH2 taken at the desired position

Hi!

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.

May I get some help please?

This one works, althought I’m bit puzzled…

int test () {
	TH2D *h2 = new TH2D("h2a", "h2b", 10, -10, 10, 10, -10, 10);
	const int N = 100000;
	
	for (Int_t i = 1; i <= h2->GetNbinsX(); i++)
		for (Int_t j = 1; j <= h2->GetNbinsY(); j++)
			h2->SetBinContent(i, j, j);
	
	TCanvas *c1 = new TCanvas("c1", "c1", 0, 60, 640, 480);
	h2->Draw("COLZ");

	const double chosenY = 0.0;

	TH1D *h1 = h2->ProjectionX("pX", h2->GetXaxis()->FindFixBin((double)chosenY), h2->GetXaxis()->FindFixBin((double)chosenY));
	
	TCanvas *c2 = new TCanvas("c2", "c2", 0, 600, 640, 480);
	h1->Draw("HIST E0");
	
	return 0;
}

This command

h2->GetXaxis()->FindFixBin((double)chosenY)

should select the bin along x at “chosenY”. Weird.

I was expecting to find some command like

TH1D * h1 = h2->ProjectionX("name", minXbin, maxXbin, yBin);

Hi @Ziel_van_brand,
and sorry for the late reply!

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);

I hope this helps!
Enrico

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