Plotting histogram by looping

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 <TFile.h>
#include <TH1D.h>
#include <TCanvas.h>

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”);

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


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.