Looping over histograms

Hi,

I have a TFile with a large number of number of histograms in it. I want to loop over these histograms and plot each of them on a different. I have:

for (int i =1; i<41; ++i){
TString histName(“data_s”);
histName+=i;
histName->Draw();
}

I can not get histName to Draw. What is the correct way of doing it?

Thanks,

Lisa

Dear Lisa,

I am not sure if you are missing the fact that “i” is an integer and it should be a string so you can add it, it could be. I use something similar and I would try with this.

for (int i =1; i<41; ++i){ 
	char st[17];
	sprintf(st,"%i", i);
	TString histName=data_+st; 
	histName->Draw();
}

Actually don’t understand your code? You are trying to print the histName on screen or want to plot histogram(Let’s say TH1F)?

  1. if you want to print histName,
 for (int i =1; i<41; ++i){
TString histName("data_s");
histName+=i;
cout<<"histName="<<histName<<endl;
} 
  1. if you want to plot histogram ( example, TH1F)
vector<TH1F*> hist;
TFile* f=....;<----That's where you get the TFile
 for (int i =1; i<41; ++i){
TString histName("data_s");
histName+=i;
hist.push_back(new TH1F( (TH1F*)f->Get(histName.Data()) ) );
if ( i==1 )
 hist[hist.size()-1]->Draw();
else
 hist[hist.size()-1]->Draw("same");
} 

Instead of:

for (int i =1; i<41; ++i){ char st[17]; sprintf(st,"%i", i); TString histName=data_+st; histName->Draw(); } do

TFile *myfile = TFile::Open("myfilename.root");
for (int i =1; i<41; ++i){ 
   TH1 *h = (TH1*)myfile->Get(Form(%d",i));
   if (i==1) h->Draw(); 
   else       h->Draw("same");
} 

Rene