Cd() is not moving to the proper drawing pad

Hello Experts,

I am having a confusing problem when trying to plot. I want to split a canvas vertically into three different pads and plot a specific range of a TGraphErrors object in each one of the vertical pads. The following is the relevant portion of my code:

        TCanvas* testCanvas = new TCanvas();
        testCanvas->Divide(1,3);

        testCanvas->cd(1);
        TGraphErrors* graph_pad1 = new TGraphErrors(numberOfRuns, runIndexArr, hitosMeans, xAxisErr, histoMeanUncert);
        graph_pad1->SetMarkerStyle(22);
        graph_pad1->SetMarkerColor(4);
        graph_pad1->SetName(graphName);
        graph_pad1->SetTitle(histoTitle);
        graph_pad1->Draw("AP");
        graph_pad1->GetXaxis()->SetRangeUser(0,6);
        gPad->Modified();
        gPad->Update();

        testCanvas->cd(2);
        TGraphErrors* graph_pad2 = ((TGraphErrors*)(graph_pad1->DrawClone("AP")));
        graph_pad2->GetXaxis()->SetRangeUser(7,12);
        gPad->Modified();
        gPad->Update();

        testCanvas->cd(3);
        TGraphErrors* graph_pad3 = ((TGraphErrors*)(graph_pad1->DrawClone("AP")));
        graph_pad3->GetXaxis()->SetRangeUser(13,16);
        gPad->Modified();
        gPad->Update();

However, the output ends up being the first two pads plotted on top of each other where only the first pad should go, the third pad is plotted in the spot where the second pad should go, and the spot for the third pad is left empty. Please have a look at the following output:

Can you please help me understand what I am doing wrong?

Instead of:
testCanvas->cd(...);
try:
gROOT->SetSelectedPad(testCanvas->cd(...));

2 Likes

Thank you very much for your quick reply! This definitely solved the problem! Do you know why my initial approach using only cd() and not nesting it in gROOt did not work?

It works if you do it this way:

{
   auto testCanvas = new TCanvas();
   testCanvas->Divide(1,3);

   testCanvas->cd(1);
   auto graph1 = new TGraph();
   graph1->AddPoint(1,1);
   graph1->AddPoint(2,3);
   graph1->AddPoint(3,1);
   graph1->SetMarkerStyle(22);
   graph1->SetMarkerColor(kBlue);
   graph1->Draw("APL");

   testCanvas->cd(2);
   auto graph2 = (TGraph*)graph1->Clone();
   graph2->Draw("APL");
   graph2->SetMarkerColor(kRed);

   testCanvas->cd(3);
   auto graph3 = (TGraph*)graph1->Clone();
   graph3->Draw("APL");
   graph3->SetMarkerColor(kGreen);
}

1 Like

Thank you very much! I will make sure to keep this in mind for the future. :slight_smile:

1 Like