This is my code. Please let me know if there is a way to make the histogram without changing the code significantly. Additionally, let me know the easier way as well. Thank you.
{
TFile *f = new TFile("Data.root", "RECREATE");
TNtuple *t = new TNtuple("current_data", "Data from HV", "Unix:Current");
t->ReadFile("NP02_HVCurrent_10-09-2019_11-09-2019");
t->Write();
TH1F *h = new TH1F("Current_Hist", "Current Vs. Events", 100, -5, 5);
h->Fill("Current");
h->Draw();
}
Your code is not so far off. Like @PaulMcKenzie wrote there's no need to do dynamic allocations (though they are common in root usage code and prevent things from going out of scope while they are implicitly still needed ...)
The creation of the TFile
and t->Write()
seem superfluous for just creating and plotting the histogram.
For simply drawing a branch of a TTree
(from which TNtuple
inherits) there is often no need to do the boilerplate of creating the histogram. TTree::Draw
is very versitile, there are various options:
{
TNtuple t("current_data", "Data from HV", "Unix:Current");
t.ReadFile("NP02_HVCurrent_10-09-2019_11-09-2019");
// just draw
t.Draw("Current");
// draw with custom binning
t.Draw("Current>>(100,-5,5)");
// use a manually created histogram
TH1F h("Current_Hist", "Current Vs. Events", 100, -5, 5);
t.Draw("current>>Current_Hist");
}
Any of the Draw
should also plot to the current canvas or create one if needed.
(For complex things that TTree::Draw
cannot do, I'd recommend calling MakeClass
on the t
, which runs code generation. In the generated implementation file there should be a loop over all elements implemented already and you can add the histogram creation outside the loop and inside the loop h.Fill(Current)
. NB: Fill
does not take a string, it takes a float which needs to be the variable that holds the current tree element's value).