Request expansion of TPad::BuildLegend

Hi,

would it be possible to expand the ability of the function TPad::BuildLegend, which currently automagically generates a TLegend for any object in the pad which inherits from TAttLine, TAttMarker, TAttFill ?

I presume the inheritance checking is to prevent the builder from adding eg the TFrame etc which are also pad primitives.

But the problem is that THStack and TMultiGraph do not inherit from TAttLine, TAttMarker, TAttFill. So if you call BuildLegend on a TPad containing one of those types of objects then it doesn’t work. Of course, the irony is that is exactly the kind of object you would want an automatic legend builder for since it can contain many objects that is sometimes inconvenient to write legend code for !

cheers
Peter

ps - I wasn’t sure that this was the correct forum for feature requests

So you want that TPad::BuildLegend automatically scan objects like THStack and TMultigraph and make a the legend for all the graphs or histograms they contain ?
An other way would be to have a BuildLegend method in THStack and TMultigraph…
This 2nd way can be easily implement as a little macro:

void mgleg()
{
   float x1[] = {1,2,3}; float y1[] = {4,7,6};
   float x2[] = {3,5,6}; float y2[] = {0,9,4};
   float x3[] = {7,8,9}; float y3[] = {1,2,4};
   float x4[] = {0,6,5}; float y4[] = {5,2,7};

   TGraph *gr1 = new TGraph(3,x1,y1); gr1->SetLineColor(1);
   TGraph *gr2 = new TGraph(3,x2,y2); gr2->SetLineColor(2);
   TGraph *gr3 = new TGraph(3,x3,y3); gr3->SetLineColor(3);
   TGraph *gr4 = new TGraph(3,x4,y4); gr4->SetLineColor(4);

   TMultiGraph *mg1 = new TMultiGraph();
   mg1->Add(gr1); mg1->Add(gr2);
   TMultiGraph *mg2 = new TMultiGraph();
   mg2->Add(gr3); mg2->Add(gr4);
   mg2->Add(mg1); // mg2 now contains gr1 gr2 gr3 and gr4

   mg2->Draw("AL*");

   TLegend *leg = BuilLegend(mg2,0.8,0.8,1,1,"hello"); 
   leg->Draw();
}

TLegend *BuilLegend(TMultiGraph *mg,
                    Double_t x1, Double_t y1, Double_t x2, Double_t y2,
                    char* title)
{
   TLegend *leg = new TLegend(x1, y1, x2, y2, title);
   TList* grlist;
   grlist = mg->GetListOfGraphs();
   printf("%d\n",grlist->GetSize());
   TIter next(grlist);
   TObject *obj;
   TGraph *gr;
  
   while ((obj = next())) {
        gr=(TGraph*)obj;
        leg->AddEntry(obj,gr->GetName(),"lp");    
   }
  
   return leg;
}

Hi,

I think the cleanest way from a user perspective would be to have TPad::BuildLegend take care of it. Otherwise, for a pad that contains, say, a TGraph, and a THStack, and a TMultiGraph - then what happens? You would need to call BuildLegend three times - this starts to get messy. Anyway - that’s just my take on it !

cheers
Peter

TPad::BuildLegend has been modified in the following way:

If the pad contains some TMultiGraph or THStack the individual graphs or
histograms in them are added to the TLegend.