TTree::Draw()'s automatic nbins black magic

Can anyone on this forum please explain to me how TTree::Draw() intelligently picks a value for the number of bins that should occur in the histogram it creates?

I’ve already figured out how to automatically set the lower and upper bins with TH1::kCanRebin. Like so:

TH1* autobinning_hist = new TH1("autobinning_hist","A Histogram that automatically sets the xlow and xup parameters",100,0,0); //TH1(name,title,nbins,xlow,xup) autobinning_hist->SetBit(TH1::kCanRebin);

However, I’m still at a loss for emulating TTree::Draw()'s capability of automatically determining the number of bins. I’ve tried looking through several Root source code files, but I couldn’t find any piece of code that seemed to do what I want.

I’ve also searched this forum for an answer, so I apologize if this topic has been discussed but I somehow missed it in my searches.

I’ve already created a function in C++ that does a pretty good job of handling histograms that have integer bins only, but I would like a more general purpose function.

Why? I have to make histograms for lots of TTree variables and calling Draw() for each variable is slower than looping through the all the entries of the tree once and filling histograms with each loop. And since I’m not terribly familiar with the variables I have to histogram, it’d be best for me if the code could automatically set-up the parameters (nbins,xlow,xup) for me rather than me having to type them up by hand, which would amount me to me analyzing each TTree variable through the Root command line with TTree::Draw() and then copying the values displayed in htemp->Inspect(). Not very efficient.

I’ve attached two pictures of histograms to show what I’m trying to accomplish. The file 45bins.gif shows what happened to the 100bins histogram after I put it through my special function that adjusts the bins for histograms filled from TTree integer-only variables. As you can see, the function basically gets rid of the empty bins that are inbetween the filled bins.

See code in TSelectorDraw::TakeEstimate at … html#gVKzv
and look at lines like