Plotting branches with binning

Hi. I have been trying to make a binned plot, but it has not worked…

I have a tree called “data” with two branches: energy and speed, with a total of 1000 events in the tree. I want to make a plot of energy vs speed, but with a bin in the energy so that I only have 10 points. I’ve tried to do this:

file=ROOT.TFile(…)
data=file.Get(‘data’)

c1=ROOT.TCanvas(‘c1’,‘c1’,400,400)
hevts=ROOT.TH1D(‘hevts’, ‘Speed’, 10, 0, 100)
hevts.Draw()
data.Draw(‘energy:speed>>+hevts’)
c1.Draw()
c1.SaveAs(“plot.pdf”)

But it’s not working (it draws the whole 1000 points). How can I do this properly?

data.Draw(‘energy:speed>>+hevts’)

Will draws scatter plot. All the 1000 points are drawn. If you want see the binned plot you need to specify a histogram drawing option like for instance ‘COLZ’.

Thank you for the idea!
I have tried something like:

c1=ROOT.TCanvas(‘c1’,‘c1’,400,400)
hevts=ROOT.TH1D(‘hevts’, ‘Speed’, 10, 0, 100)
hevts.SetOption(“COLZ”)
hevts.Draw()
data.Draw(‘energy:speed>>+hevts’)
c1.Draw()
c1.SaveAs(“plot.pdf”)

But it’s still not working :frowning:

hevts = ROOT.TH2D('hevts', 'Energy vs. Speed', 10, 0., 100., 10, 0., 100.)
data.Draw('energy:speed >> hevts', '', 'colz') # hevts x = speed, y = energy

It worked! Thank you. However, the plot style is not so elegant; it’s formed by big squares. Do you know if I can change the format of the plot?

You create a 10 x 10 bins histogram (hence “big squares”).

Thank you again! And a last question related with this one. Once I have the energy vs speed plot, I also need to make a frequency histogram with the energy of the events (which is basically the number of events in each bin).

However, each event must be weighted by a number stored in a branch called “weight”. So, for example, if in the first bin I have only 2 events weighted with 4 and 2, respectively, the frequency for the first bin should be 6 instead of 2.

Do you know how can I do it? I guess it should be similar to the las issue, but I don’t really know…

data.Draw('energy:speed >> hevts', 'weight', 'colz')

That helped a lot! And what if I want to scale the whole histogram by a factor stored in the “scale” variable (not a root object)? This would be the final steep. I have tried this:

scale=100.
data.Draw(‘energy:speed >> hevts’, ‘scale*weight’, ‘colz’)

But it’s not working…

After the “Draw” line, add: hevts.Scale(scale)

Thanks again!