Macro to plot multiple histograms

Hi All,
I am trying to plot multiple histograms on a single Canvas like this

void example()
{

   TFile *f= new TFile("example.root","READ");
   TCanvas *c = new TCanvas();        
   c->Divide(2,2);
   for(int i=1;i<=4;i++){
      c->cd(i);
      hist[i]->Draw();
   }
   c->Print("example.pdf");
}

what am I doing wrong? Thanks for your help.

Hi,

I think the variable hist is not defined anywhere.

Cheers,
D

Hi dpiparo,
I am calling the hist from the root file.

Hi,

I do not understand what you exactly mean. Could you post all the code?

Cheers,
D

Hi D,
I have a code that runs separately and saves histograms (hist[1],hist[2]…) into a root file (example.root). What I want to do now is write separate macro that opens example.root and plots my histograms according to the example code I posted earlier.

Hi,

I understand that.
What I am saying is that the variable hist is defined nowhere and the code, as is, cannot work. I propose you post the file being opened and the input root file. Without this step being accomplished, I am afraid I cannot help further.

Cheers,
D

Here are the files.
Thanks again,
example.root (4.7 KB)
example.C (223 Bytes)

Hello,

There is a problem with your root file. It contains:

TFile**		example.root	
 TFile*		example.root	
  KEY: TH1D	;1	
  KEY: TH1D	hist[1];1	hist[1]
  KEY: TH1D	hist[2];1	hist[2]
  KEY: TH1D	hist[3];1	hist[3]

the histograms’ names are in the form hist[?] therefore it makes harder to access them from a C++ script as something like hist[1] will be understood by the C++ interpreter as the first element of the hist array. Note also the first histogram in your file is not named at all, which will makes it even harder to access . So before going further is it possible for you to regenerate the .root file with proper named histograms ? for instance you can name them hist1 hist2 hist3 and hist4

Note that with your current file you can access your histograms using the following macro:

void example()
{

   TFile *f= new TFile("example.root","READ");
   TCanvas *c = new TCanvas();
   TH1D *h;
   c->Divide(2,2);
   for(int i=1;i<4;i++){
      c->cd(i);
      h = (TH1D *)f->Get(Form("hist[%d]",i));
      h->Draw();
   }
   c->Print("example.pdf");
}

It will access only 3 histograms out of 4 as the 1st one is not named.

1 Like

Great! It worked.
Thanks to both of you couet and dpiparo.
Cheers,

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.