How to rebin a hisstogram in python

Hi

I am trying to rebin a histogram in python following way:

h=r.TH1F(’’,’’,8,0,8)
for i in range(9) :
… h.SetBinContent(i+1,i)

h.Draw()
Info in TCanvas::MakeDefCanvas: created default TCanvas with name c1

x=numpy.array([0,1,2,3,4,8])
h1=h.Rebin(5,’’,x)
h1.Draw()
Error in TGaxis::PaintAxis: length of axis is 0

h1.GetEntries()
9.0

h.GetEntries()
9.0

h.Integral()
28.0

h1.Integral()
0.0

What I understand Rebin() function will return the pointer of modified binsize histogram with different name, but why the integral value is zero & also why getting error while drawing? Can anyone please make it clear?

Thanks

Hi,

can you share with us a reproducer for this issue which we can run?

Cheers,
D

Hi Danilo,

Thanks, for your reply. Here I am attaching a small version of c++ & python code for rebining.

Python

import ROOT as r
import numpy

x=numpy.array([0,1,2,3,4,8])
c = r.TCanvas('c','c',600,800)
c.Divide(2,1)

h1 = r.TH1F('h1','h1',8,0,8)
for i in range(9) :
    h1.SetBinContent(i,i)
h2 = h1.Rebin(5,'h2',x)
c.cd(1)
h1.Draw()
c.cd(2)
h2.Draw()
c.Print('rebin.pdf')

C++

#include <TCanvas.h>
#include <TH1D.h>
#include <TROOT.h>
#include <TStyle.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>

void rebin() {
  double x[6]={0,1,2,3,4,8};
  TCanvas* c = new TCanvas("c","c",600,800);
  c->Divide(2,1);

  TH1F* h1 = new TH1F("h1","h1",8,0,8);
  for (int i=0; i<8; i++) h1->SetBinContent(i+1,i);
  TH1F* h2 = (TH1F*)h1->Rebin(5,"h2",x);
  c->cd(1);
  h1->Draw();
  c->cd(2);
  h2->Draw();
  c->Print("rebin.pdf");
}

where c++ is working but not python

Thanks,
Saswati

Hi Saswati,

try with the array module instead:

import ROOT as r
import array

x=array.array('d',[0,1,2,3,4,8])
c = r.TCanvas('c','c',600,800)
c.Divide(2,1)

h1 = r.TH1F('h1','h1',8,0,8)
for i in range(9) :
    h1.SetBinContent(i,i)

h2 = h1.Rebin(5,'h2',x)
c.cd(1)
h1.Draw()
c.cd(2)
h2.Draw()

Cheers,
D

Hi Danilo,

Thanks a lot! It is working now.

Thanks,
Saswati

1 Like

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