Is there an easier way to create multiple canvases using functions and loops?

I am trying to follow this worksheet from Hance and recreate the invariant mass plot below from his root file. I have attached my code and the root file can be downloaded from the website.HEP_practiceV6.C (33.3 KB) (upload://aoNaWV7GMmHT31s6iq6103497KE.C) (20.4 KB)

I am creating around 20 canvas here by repeating code? Is there some easier way to do this with functions and loops?

ROOT Version: 6.22
Platform: Ubutnu 18.04
Compiler: Not Provided


That’s more of a c++ issue than root, but with a loop you can for example create an array of canvases (e.g. TCanvas *c[20];) declared outside the loop and then inside the loop create each one as needed, also giving them names that depend on the loop iteration number.

1 Like

To complement @dastudillo’s reply, you can make this:

 	TCanvas *c1 = new TCanvas("c1","pTLep Histrogram" ,200,10,900,700);
		c1->SetFillColor(10);
		c1->SetGrid();
		c1->GetFrame()->SetFillColor(10);
		c1->GetFrame()->SetBorderSize(12);
		c1->Range(0,0,1,1);

		gStyle->SetOptStat(1);
			
			c1->cd();
			histpTLep->SetXTitle("pTLep");
			histpTLep->SetYTitle("Counts");
			histpTLep->SetStats(1);
			histpTLep->Draw();
			if(SaveAsRootFile){
				TFile outfile1(rootOutputFileName1, "RECREATE");
				c1->Write(rootOutputFileName1);
				outfile1.Close();
			}
			
			
	TCanvas *c2 = new TCanvas("c2","etaLep Histrogram" ,200,10,900,700);
		c2->SetFillColor(10);
		c2->SetGrid();
		c2->GetFrame()->SetFillColor(10);
		c2->GetFrame()->SetBorderSize(12);
		c2->Range(0,0,1,1);

		gStyle->SetOptStat(1);
			
			c2->cd();
			histetaLep->SetXTitle("etaLep");
			histetaLep->SetYTitle("Counts");
			histetaLep->SetStats(1);
			histetaLep->Draw();
			if(SaveAsRootFile){
				TFile outfile2(rootOutputFileName2, "RECREATE");
				c2->Write(rootOutputFileName2);
				outfile2.Close();
			}

into (something like) this:


std::vector<TCanvas*> canvases(2);
std::vector<std::string> titles = {"pTLep Histogram", "etaLep Histogram"};
std::vector<TH1D*> histos = {histpTLep, histetaLep};
for (int i = 0; i < 2; ++i) {
   TCanvas *c = new TCanvas(("c" + std::to_string(i)).c_string(), titles[i].c_str(), 200, 10, 900, 700);
   canvases[i] = c;
	c->SetFillColor(10);
	c->SetGrid();
	c->GetFrame()->SetFillColor(10);
	c->GetFrame()->SetBorderSize(12);
	c->Range(0,0,1,1);
	gStyle->SetOptStat(1);
	c->cd();
	histos[i]->SetXTitle(titles[i].c_str());
	histos[i]->SetYTitle("Counts");
	histos[i]->SetStats(1);
	histos[i]->Draw();
	if(SaveAsRootFile){
		TFile outfile1(rootOutputFileName1, "RECREATE");
		c->Write(rootOutputFileName1);
		outfile1.Close();
	}
}

Cheers,
Enrico

I guess

should read

TCanvas *c = new TCanvas(("c" + std::to_string(i)).c_str(), titles[i].c_str(), 200, 10, 900, 700);

, with c_str() instead of c_string()

2 Likes