# Finding x,y coordinates to max value in 2D histogram

Hello, I am searching for a command to find coordinates to the a max value of a 2D histogram.

``h_gaus = ROOT.TH2D("h_gaus", "", 8, 0, 8, 8, 0, 8)``

I am filling this histogram with Gaussian distribution.
So now I want a way to find the the x and y values which correspond to the maximum value/bin in the histogram.
Dose anyone know?

Thanks for the reply. But I don’t quiet get how to do it. As I have understood it TH1::GetMaximumBin should do what I want, but I cant quite make sense on what it returns. Here is an example:

``````h_gaus = ROOT.TH2D("h_gaus", "", 48, 0, 48, 48, 0, 48)

TwoDGaus=ROOT.TF2("TwoDGaus","[0]*TMath::Gaus(x,[1],[2])*TMath::Gaus(y,[3],[4])",0,10,0,10)
TwoDGaus.SetParameter(0,5)
TwoDGaus.SetParameter(1,15)
TwoDGaus.SetParameter(2,2)
TwoDGaus.SetParameter(3,25)
TwoDGaus.SetParameter(4,2)

h_gaus.FillRandom('TwoDGaus',10000)

h_gaus.Draw("COLZ")

print h_gaus.GetMaximumBin()``````

GetMaximumBin returns “1266” which dose not all corresponds to parameter [1] (15) or parameter [3] (25). How do I get it to return (~15, ~25)? Which should be the coordinates for the location of the maximum.

Hi,

I think you need
root.cern.ch/doc/master/classTH … 291489b758

Cheers,
Danilo

Thanks for response, So I am a bit of a beginner here. GetBinXYZ is suppose to get GetMaximumBin as input and then store the result in x,y,z?
Like this:

How dose it work if I just have two dimensions? I am unable to get this to work in PyROOT.

Hi,

yes. There is no speciality if the histo has 2 dimensions only.

Cheers,
Danilo

Here is how to use the two method Danilo and I mentioned. I made a .C macro with your script (I am easier with C++…). The macro is:

``````{
TH2D *h_gaus = new TH2D("h_gaus", "", 48, 0, 48, 48, 0, 48);

TF2 *TwoDGaus = new TF2("TwoDGaus","[0]*TMath::Gaus(x,[1],[2])*TMath::Gaus(y,[3],[4])",0,10,0,10);
TwoDGaus->SetParameter(0,5);
TwoDGaus->SetParameter(1,15);
TwoDGaus->SetParameter(2,2);
TwoDGaus->SetParameter(3,25);
TwoDGaus->SetParameter(4,2);

h_gaus->FillRandom("TwoDGaus",10000);

Int_t MaxBin = h_gaus->GetMaximumBin();
Int_t x,y,z;
h_gaus->GetBinXYZ(MaxBin, x, y, z);

printf("The bin having the maximum value is (%d,%d)\n",x,y);

h_gaus->Draw("COLZ");
}``````

it gives:

``````root [0] .x radio.C
The bin having the maximum value is (15,26)
root [1] ``````

Alright that explains it, thanks for the example. Now I know how it is suppose to work in C++. Just need to figure out how it should work in Python.

The same … simply add in your code the 2 calls retrieving bins info.

Ok finishing touch. By pre-define my variables with ROOT.Long for storing the coordinates I am able to use the GetBinXYZ.

``````maxbin=h_gaus.GetMaximumBin()
xx, yy, zz = ROOT.Long(0), ROOT.Long(0), ROOT.Long(0)
h_gaus.GetBinXYZ(maxbin, xx, yy, zz)
print xx,yy,zz``````

This prints 16 , 25 , 0

Bye