Numpy arrays in variable binned histogram with pyroot

Hello,

I am using root-6.08.02 to make a variable binned histogram with PyROOT.
I find that this works:

from array import array
m = [400,450,500,550,600,650,700,750,800,850,900,950,1000,1150,1500]
h = ROOT.TH1D("h",";m [GeV];Events/ 50 GeV;;",len(m)-1,array('d',m))

but this doesn’t

import numpy as np
m = [400,450,500,550,600,650,700,750,800,850,900,950,1000,1150,1500]
h = ROOT.TH1D("h",";m [GeV];Events/ 50 GeV;;",len(m)-1,np.asarray(m))

I error I get is

Error in < TGaxis::PaintAxis >: length of axis is 0

when trying to draw the histogram booked using the numpy array.

Is this expected?

doesn’t give you a double array, np.asarray(m, 'd') does. I.e. this works:

import ROOT
import numpy as np
m = [400,450,500,550,600,650,700,750,800,850,900,950,1000,1150,1500]
h = ROOT.TH1D("h",";m [GeV];Events/ 50 GeV;;",len(m)-1,np.asarray(m, 'd'))
h.Draw()

Axel.

Thanks for your reply.

I traced the problem back to an unrelated issue with TPad::DrawFrame and not to the histo I was trying to fill. In other words,
h = ROOT.TH1D(“h”,";m [GeV];Events/ 50 GeV;;",len(m)-1,np.asarray(m))
works without specifying ‘d’.

I had used TGraph and TGraphAsymErrors with the same kind of initialization and those worked as well.

Very surprising. I had to specify the 'd'; without the 'd' I got the same error message as you did.

Axel.

Not sure if this has got to do with the versions: I’m using python 2.7.10 with numpy 1.9.2
This https://docs.scipy.org/doc/numpy-1.9.2/reference/generated/numpy.asarray.html#numpy.asarray
says that the data type is optional.

“Optional” doesn’t mean “magically does what you expect” :slight_smile:

Axel.

I agree. It’s good to be pedantic in this case!