Histogram not showing up after drawing

I’m trying to write a C++ program that takes signal MC events and fills histograms of px, py, pz and draws them. So far, I am able to get it to compile, but it puts out a blank canvas where there should be a histogram. This is probably a simple fix since I am a beginner, but I would greatly appreciate any and all help or input! Here is my code:

#include “TChain.h”
#include “TCanvas.h”

void TChainPractice(){
//creates a chain with tree “T"
TCanvas c1 = new TCanvas(“c”, “c”,600,800);
TChain chain(“h16”);
//Adds all the files needed
chain.Add("kstar
.root”);

 //create histograms                                                 
 TH1F *h16 = new TH1F("h16", "Histogram", 60, -1, 1);

 //To to get the events:                                             
 chain.SetBranchAddress("idhep==211"); //to recognize the mass of pi
 chain.SetBranchAddress("px");
 chain.SetBranchAddress("py");
 chain.SetBranchAddress("pz");

 Int_t nevent = chain.GetEntries();
 for(Int_t i =0;i<nevent;i++){
   if(abs(idhep)==211){
   chain.GetEvent(i);
   h16->fill(i);
   }
  }

 c1->Update();

 chain.Draw("px", "abs(idhep)==211");
   c1->SaveAs("px.png");

 chain.Draw("py", "abs(idhep)==211");
   c1->SaveAs("py.png");

 chain.Draw("pz", "abs(idhep)==211");
   c1->SaveAs("pz.png");

}

1 Like

try:

#include "TChain.h"
#include "TCanvas.h"

void TChainPractice() {
   //creates a chain->with tree "T" 
   TCanvas *c1 = new TCanvas("c", "c",600,800);
   TChain *chain = new TChain("h16");

   //Adds all the files needed 
   chain->Add("kstar*.root");

   //create histograms 
   TH1F *h16 = new TH1F("h16", "Histogram", 60, -1, 1);

   //To to get the events: 
   chain->SetBranchAddress("idhep==211"); //to recognize the mass of pi
   chain->SetBranchAddress("px");
   chain->SetBranchAddress("py");
   chain->SetBranchAddress("pz");

   Int_t nevent = chain->GetEntries();
   for (Int_t i =0;i<nevent;i++) {
      if(abs(idhep)==211){
         chain->GetEvent(i);
         h16->fill(i);
      }
   }


   chain->Draw("px", "abs(idhep)==211");
   c1->Update();
   c1->SaveAs("px.png");

   chain->Draw("py", "abs(idhep)==211");
   c1->Update();
   c1->SaveAs("py.png");

   chain->Draw("pz", "abs(idhep)==211");
   c1->Update();
   c1->SaveAs("pz.png");

}