Draw two histograms in same canvas from two different root files

I’m new to ROOT and trying to draw two histogram on the same canvas from root file. I tried to use “same” method for vs.6.14/6 but it didn’t work. My senior who used the same method for vs.5.38.xx got the result with the following command linesfirst.root (52.9 KB)
second.root (41.4 KB)

TFile *f1 = TFile::Open("first.root")
TCanvas *c1 = (TCanvas*)f1->Get("h1");
h1->Draw("hist l");
h1->SetLineWidth(3);
h1->SetLineColor(2);

TFile *f2 = TFile::Open("second.root")
TCanvas *c2 = (TCanvas*)f2->Get("h1");
h1->SetLineWidth(2);
h1->SetLineColor(4);
h1->Draw("hist l same");

I’m attaching the root files.
I’ll be very grateful if someone can do me favor.
Thanks.

{
  TFile *f1 = TFile::Open("first.root");
  f1->ls();
  TH1D *h1f; f1->GetObject("h1", h1f);
  h1f->SetLineColor(2);
  TFile *f2 = TFile::Open("second.root");
  f2->ls();
  TH1D *h1s; f2->GetObject("h1", h1s);
  h1s->SetLineColor(4);
  h1f->Draw("hist l");
  h1s->Draw("hist l same");
}

Hi,
I attached below a modified version of your code. (Remember to put you code between two ``` in this way will appear highlited).

there are 3 main point

  • I added two ; after the opening of the files.
  • When you use Get() to get the histogram recast as a TH1D and not a TCanvas, otherwise you cannot the TH1D methods.
  • the Draw is made using the TH1D pointer and not the name of the histogram in the file.
void macro()
{
    
    TFile *f1 = TFile::Open("first.root");
    TH1D *h1= (TH1D*)f1->Get("h1");
    h1->Draw("hist l");
    h1->SetLineWidth(3);
    h1->SetLineColor(2);
    
    TFile *f2 = TFile::Open("second.root");
    TH1D *h2 = (TH1D*)f2->Get("h1");
    h2->SetLineWidth(2);
    h2->SetLineColor(4);
    h2->Draw("hist l same");
    
}

Thanks for helping. It worked.

Thanks. It helped me.