How to define histogram with variable bin width in python

Hi,

I am trying to define histogram with variable bin width in python in following way:

import numpy
x=numpy.array([2,4,8,9])
import ROOT as r
h=r.TH1F(‘’,‘’,3,x)
h
<ROOT.TH1F object at 0x4f3bf30>

but the width of each bin is zero

h.GetXaxis().GetBinWidth(1)
0.0
h.GetXaxis().GetBinWidth(2)
0.0
h.GetNbinsX()
3

Could anyone please tell me the correct way to define the histogram with variable bin width in python?

Thanks in advance -:))

Saswati

See for example:

(searching on the forum is sometimes useful…) :wink:

In defense of TS, the code won’t work with a list per the other topic but should do with a numpy array.

There was a recent thread and bug report about incorrect array converters being selected: the selection is on element size, not element type as numpy arrays don’t carry a typecode as an attribute (but do as part of the buffer info). See:

https://sft.its.cern.ch/jira/browse/ROOT-9040
pyROOT TMultiGraph Segmentation Fault

1 Like

As @wlav has pointed out this is a bug about types. ROOT interprets your array as one with floats, even though it contains integers and you should have received an error. Specifying dtype when defining your array will resolve the issue until the bug is resolved.

import numpy as np
import ROOT

#Must explicit declare variable type
bin_edges = np.array([2, 4, 8, 9], dtype='float64')

h = ROOT.TH1F("","",len(bin_edges)-1, bin_edges)

for bin_num in range(len(bin_edges)-1):
    print h.GetBinWidth(bin_num)
2 Likes

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