Histograms with different scales on the same Canvas

Dear all,
I wrote this script

void draw_particle_momentum()
{
    c = new TCanvas;
    
    f = TFile::Open("aaa..root");
    TTree *t = (TTree*)f->Get("t");
  
    t->Draw("p >> h_all(100,0,0.1)","abs(lp)==11&&layer==118&&p<0.1");
    h_all->SetStats(0);
    
    t->SetLineColor(2);
    t->Draw("p","abs(lp)==11&&layer==118&&p<0.1&&atan(sqrt(sx*sx+sy*sy))<0.5","same");
  
    f1 = TFile::Open("bbb.root");
    TTree *t1 = (TTree*)f->Get("tree");
    
    tree->SetLineColor(4);
    tree->Draw("p >> h_reco()","abs(lp)==11&&p<0.1","same");
    
    h_all->SetTitle("Momentum distribution - e^{+} and e^{-}");
    h_all->GetXaxis()->SetTitle("p (GeV)");
    
    h_ratio=new TH1F("h_ratio","h_ratio",100,0,0.1);
    h_ratio->Divide(h_reco,h_all);
    
    float rightmax=1.1*h_ratio->GetMaximum();
    float scale = gPad->GetUymax()/rightmax;
    h_ratio->SetLineColor(8);
    h_ratio->Scale(scale);
    h_ratio->Draw("same");
//draw an axis on the right side
    TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(),gPad->GetUymax(),0,rightmax,510,"+L");
    axis->SetLineColor(8);
    axis->SetLabelColor(8);
    axis->Draw();
    
}

to draw histograms with different scales in the same canvas.
But in the resulting plot the histogram h_ratio is not rescaled and the second axis is not drawned!
The strange thing is that if I try to execute the following commands after having executed the script and without closing the root session, in interactive mode, the plot is ok!

    float rightmax=1.1*h_ratio->GetMaximum();
    float scale = gPad->GetUymax()/rightmax;
    h_ratio->SetLineColor(8);
    h_ratio->Scale(scale);
    h_ratio->Draw("same");
//draw an axis on the right side
    TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),gPad->GetUxmax(),gPad->GetUymax(),0,rightmax,510,"+L");
    axis->SetLineColor(8);
    axis->SetLabelColor(8);
    axis->Draw();

Can someone explain me what’s the problem?

Thanks a lot,
Fabio

I cannot execute your macro because you did not send the two root files aaa.root and bbb.root.
But looking at the code I can tell it cannot work. To do what you want to do, you need two pads on top on each other (the top one being transparent) like in $ROOTSYS/tutorials/hist/transpad.C