Drawing Vertical Line in TGraph

Hi, I am trying to draw veritcal line in my TGraph. My code compiles without error but the line is out of scope (picture attached for reference where you can see red line on bottom part). Can someone please help with the issue? Thank you.

void code() {
       const Int_t nPoints = 5;
       Double_t x[nPoints] = {1, 2, 3, 4, 5};
       Double_t y[nPoints] = {2.0, 3.5, 1.5, 4.0, 2.5};

       TGraph *graph = new TGraph(nPoints, x, y);

       TCanvas *canvas = new TCanvas("canvas", "Graph Example", 800, 600);

       graph->SetTitle("Example Graph");
       graph->GetXaxis()->SetTitle("X-axis");
       graph->GetYaxis()->SetTitle("Y-axis");

       graph->Draw("APL"); // A: Axis, P: Points, L: Line
        
        TLine *verticalLine = new TLine(2, canvas->GetUymin(), 2, canvas->GetUymax());
        verticalLine->SetLineColor(kRed);
        verticalLine->SetLineWidth(2);

        verticalLine->Draw("same");
       canvas->Draw();
       }

Try

  TLine *verticalLine = new TLine(2, graph->GetYaxis()->GetXmin(), 2, graph->GetYaxis()->GetXmax());
1 Like

It worked! But why GetXmin() and GetXmax() instead of GetYmin() and GetYmax()? Thank you

Both GetXaxis() and GetYaxis() return a TAxis object, which by itself is neither x nor y, but the methods to get the maximum and minimum from a TAxis happen to be called GetXmax() and GetXmin().

simplified code:

void code() {
   const Int_t nPoints = 5;
   Double_t x[nPoints] = {1, 2, 3, 4, 5};
   Double_t y[nPoints] = {2.0, 3.5, 1.5, 4.0, 2.5};

   auto canvas = new TCanvas("canvas", "Graph Example", 800, 600);

   auto graph = new TGraph(nPoints, x, y);
   graph->SetTitle("Example Graph");
   graph->GetXaxis()->SetTitle("X-axis");
   graph->GetYaxis()->SetTitle("Y-axis");

   graph->Draw("AL");

   TLine *verticalLine = new TLine(2, graph->GetYaxis()->GetXmin(),
                                   2, graph->GetYaxis()->GetXmax());
   verticalLine->SetLineColor(kRed);
   verticalLine->SetLineWidth(2);

   verticalLine->Draw();
}