# Getting median in a TH2 for a certain range

Hello,

I’m using a (fixed bin size) TH2F to display scatter plots. I then compute the mean in different “slices” in x, eg I get the mean for x between 0 and 10, then x between 10 and 15, then x between 15 and 16.
Is there a way to do the very same thing using median instead of mean?

Thank you,

TY

In the code below, you will find two functions;
-median2 computes/prints median and mean for each slice along Y
of a 2-d histogram
-median1 returns the median for a 1-d histogram. Internally this function
uses TMath::Median.

Rene

[code]Double_t median1(TH1 *h1) {
//compute the median for 1-d histogram h1
Int_t nbins = h1->GetXaxis()->GetNbins();
Double_t *x = new Double_t[nbins];
Double_t *y = new Double_t[nbins];
for (Int_t i=0;iGetXaxis()->GetBinCenter(i+1);
y[i] = h1->GetBinContent(i+1);
}
Double_t median = TMath::Median(nbins,x,y);
delete [] x;
delete [] y;
return median;
}

void median2(TH2 *h2) {
//compute and print the median for each slice along X of h2

Int_t nbins = h2->GetYaxis()->GetNbins();
for (Int_t i=1;iProjectionY("",i,i);
Double_t median = median1(h1);
Double_t mean = h1->GetMean();
printf(“Median of Slice %d, Median=%g, Mean = %g\n”,i,median,mean);
delete h1;
}
}

[/code]

Rene,

That’s exactly what I waqs looking for. Thanks a lot for your help!

TY

Hello Rene,

it seems like some your code was cut when you pasted it here ; may I ask you to re-post it please?

Thanks a lot,

TY

Hello Rene,

Please check your code: it does not compile, and some parts are probably lost…

Many thanks !!

• Anatoly

here is the correct file

[code]#include “TH2.h”
#include "TMath.h"
Double_t median1(TH1 *h1) {
//compute the median for 1-d histogram h1
Int_t nbins = h1->GetXaxis()->GetNbins();
Double_t *x = new Double_t[nbins];
Double_t *y = new Double_t[nbins];
for (Int_t i=0;i<nbins;i++) {
x[i] = h1->GetXaxis()->GetBinCenter(i+1);
y[i] = h1->GetBinContent(i+1);
}
Double_t median = TMath::Median(nbins,x,y);
delete [] x;
delete [] y;
return median;
}

void median2(TH2 *h2) {
//compute and print the median for each slice along X of h2

Int_t nbins = h2->GetYaxis()->GetNbins();
for (Int_t i=1;i<=nbins;i++) {
TH1 *h1 = h2->ProjectionY("",i,i);
Double_t median = median1(h1);
Double_t mean = h1->GetMean();
printf(“Median of Slice %d, Median=%g, Mean = %g\n”,i,median,mean);
delete h1;
}
}
[/code]

Rene

Thanks a lot !

To be precise, it should be “<=”:

in the second function…

• Anatoly