Median of histogram

Hi

is there an easy way of getting the median of a histogram instead of the mean?

Thanks

Hi,

we don’t have currently a function calculating t he mean of an histogram. It could be added in the next release.
Anyway it is easy to implement, here is function calculating it, given a TH1D

#include "TH1.h"
#include "TMath.h"
#include <vector>

double Median(const TH1D * h1) { 

   int n = h1->GetXaxis()->GetNbins();  
   std::vector<double>  x(n);
   h1->GetXaxis()->GetCenter( &x[0] );
   const double * y = h1->GetArray(); 
   // exclude underflow/overflows from bin content array y
   return TMath::Median(n, &x[0], &y[1]); 
}

Best Regards

Lorenzo

Just for the record this is how I did it in the end:

 int numBins = histo1->GetXaxis()->GetNbins();
  Double_t *x = new Double_t[numBins];
  Double_t* y = new Double_t[numBins];
  for (int i = 0; i < numBins; i++) {
    x[i] = histo1->GetBinCenter(i);
    y[i] = histo1->GetBinContent(i);
  }
  double MedianOfHisto = TMath::Median(numBins, &x[], &y[]);

Thanks for this kshaw!

The “median” is just the “0.5 quantile”:

{
  // create, fill and draw the histogram
  TF1 *f = new TF1("f", "TMath::Gaus(x, 5, 1)", 0, 10);
  TH1D *h = new TH1D("h", "h", 100, 0, 10);
  h->FillRandom("f");
  h->Draw();
  // calculate and print the "median"
  Double_t x, q;
  q = 0.5; // 0.5 for "median"
  h->ComputeIntegral(); // just a precaution
  h->GetQuantiles(1, &x, &q);
  std::cout << "median = " << x << std::endl;
}
1 Like