# Plotting histogram by looping

**URL:** <https://root-forum.cern.ch/t/plotting-histogram-by-looping/53145>\
**Category:** Newbie\
**Created:** [January 17, 2023, 6:17pm UTC](https://root-forum.cern.ch/t/plotting-histogram-by-looping/53145 "2023-01-17T18:17:38Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bikash](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/b/ee59a6/32.png) [@Bikash](https://root-forum.cern.ch/u/Bikash)\
**Post date:** [January 17, 2023, 6:17pm UTC](https://root-forum.cern.ch/t/plotting-histogram-by-looping/53145/1 "2023-01-17T18:17:38Z")

</div>

Hello. I have a root file within which there is a folder which contains different histogram. I want to loop those and plot different histogram for all of them. The folder name is Energy spectra and within that there are histograms named Energy ch 1;1 , Energy ch 2;1, Energy ch 3;1, and so on.

I wrote the following code and it did not work

#include  
#include \<TFile.h\>  
#include \<TH1D.h\>  
#include \<TCanvas.h\>  
#include

using namespace std;

void tut17() {  
//Open an existing ROOT File using the READ command. READ is used so as to not modify the data saved in the ROOT file.  
TFile\* fileOut = TFile::Open(“C:/root\_v5.34.36/macros/run00037\_000.root”, “READ”);  
//TFile \*fileOut = TFile::Open(“ROOT DIRECTORY + /DAQRoot.root”,“READ”);

```auto
if (!fileOut) {
	cout << "File not found." << endl;
	return 0;
}

TDirectory* folder = (TDirectory*)fileOut->Get("Energy spectra"); // get the folder from the file

for (int i = 1; i < 33; i++)
{
	//std::cout << file_name << std::endl;
	TH1F* histo[i] = (TH1F*)folder->Get(Form("Energy ch %d",i)); // get the histogram from the folder
	//double counts = histo->Integral(200, 1000);

	TCanvas* canvas = new TCanvas("canvas", "Histogram", 800, 600); // create a canvas for the plot

	histo[i]->Draw("same");// draw the histogram
	//cout << counts << endl;
	//cout << histo[i]->Integral(200, 1000) << endl;

	//canvas->SaveAs("histo.pdf"); // save the plot as a pdf
}

```

}

---

<div class="post-metadata">

**Author:** ![couet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/couet/32/12037_2.png) [@couet](https://root-forum.cern.ch/u/couet)\
**Post date:** [January 17, 2023, 8:13pm UTC](https://root-forum.cern.ch/t/plotting-histogram-by-looping/53145/2 "2023-01-17T20:13:04Z")

</div>

A few remarks with the code you’ve provided:

- The path should be in quotation marks, but the path you provided uses different characters (“ ”).
- Instead of `TH1F* histo[i]`, it should be `TH1F* histo = (TH1F*)folder->Get(Form("Energy ch %d",i));`
- The `for` loop should run from 1 to 33 (inclusive) but you are currently only running from 1 to 32 (exclusive).
- You should not option “same” to draw the histograms.
- You should consider to use `canvas->SaveAs(Form("histo_%d.pdf",i));` instead of `"histo.pdf"` to save each histogram plots in a different files.
