TH2I equivalent of numpy histogram2d?

ROOT Version: 6.26
Platform: Linux Suse
Compiler: g+±7

I could not find a smarter way to fill a 2d integer histogram with respect to its “x”, “y” other than

for (j_pul=0; j_pul<n_pulses; j_pul++){
    int nheight = (int)(PulseHeight[j_pul]+0.5);
    int nshape    = (int)(PulseShape [j_pul]+0.5);
    if ( (nheight > 0) && (nheight < nxCh) && (nshape > 0) && (nshape < nyCh) ){
        ntmp = hpha->GetBinContent(nheight, nshape);
        hpha->SetBinContent(nheight, nshape, ntmp+1);

I am quite sure such “count” histogram can be built a smarter way but I could not find anything browsing the documentation, the forum or google.
It’s basically what numpy.histogram2d does (by default).
If you have a proper reference or example, please let me know.

I did find AddBinContent which makes the coding slightly less ugly, but it’s not what I want.

The right method to fill from array is to use TH2::FillN. This is basically the same as numpy.histogram2d.

Here is a Python example:

import numpy as np
import ROOT
x = np.random.normal(1,2,1000)
y = np.random.normal(2,1,1000)
# note we use automatic computation of bin edges for the histogram
h2 = ROOT.TH2D("h2","h2",10,1,0,10,1,0)
w = np.ones(1000)

# or equivalent in numpy 
h,xbins,ybins = np.histogram2d(x,y)


Thanks a lot, that was exactly what I meant, now it’s implemented as you say and it works perfectly.

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