How to change the entries on a TLegend

Hey there,

I’ve been trying to change TLegend entries for graphs read from a TFile without success. I’m using TCanvas::BuildLegend(), but neither changing the name of the graph before calling this method, nor before calling TGraph::Draw() changes the entries on the legend (the title of the canvas is modified by it though). I don’t seem to find any TLegend methods to modify an entry on it (is it possible?).

How can I achieve this functionality?

Cheers,
Adam Hunyadi

You can right click on the legend and use the editing tool provided by the popup menu.

I need to do it from a script. How do I access the functionality provided by the menu through code?

Also, I don’t seem to be able to change the other properties of the graph either. Even is I do a SetMarkerStyle before adding it to a multigraph, the marker style still won’t change…

Here is an example:

void multigraphleg()
{
   TCanvas *c = new TCanvas("c","c",600, 400);

   TMultiGraph * mg = new TMultiGraph("mg","mg");

   const Int_t size = 10;

   double x[size];
   double y1[size];
   double y2[size];
   double y3[size];

   for ( int i = 0; i <  size ; ++i ) {
      x[i] = i;
      y1[i] = size - i;
      y2[i] = size - 0.5 * i;
      y3[i] = size - 0.6 * i;
   }

   TGraph * gr1 = new TGraph( size, x, y1 );
   gr1->SetName("gr1");
   gr1->SetTitle("graph 1");
   gr1->SetMarkerStyle(21);
   gr1->SetDrawOption("AP");
   gr1->SetLineColor(2);
   gr1->SetLineWidth(4);
   gr1->SetFillStyle(0);

   TGraph * gr2 = new TGraph( size, x, y2 );
   gr2->SetName("gr2");
   gr2->SetTitle("graph 2");
   gr2->SetMarkerStyle(22);
   gr2->SetMarkerColor(2);
   gr2->SetDrawOption("P");
   gr2->SetLineColor(3);
   gr2->SetLineWidth(4);
   gr2->SetFillStyle(0);

   TGraph * gr3 = new TGraph( size, x, y3 );
   gr3->SetName("gr3");
   gr3->SetTitle("graph 3");
   gr3->SetMarkerStyle(23);
   gr3->SetLineColor(4);
   gr3->SetLineWidth(4);
   gr3->SetFillStyle(0);

   mg->Add( gr1 );
   mg->Add( gr2 );

   gr3->Draw("ALP");
   mg->Draw("LP");

   TLegend *l = c->BuildLegend();
   TList *p = l->GetListOfPrimitives();

   TIter next(p);
   TObject *obj;
   TLegendEntry *le;
   int i = 0;

   while ((obj = next())) {
      le = (TLegendEntry*)obj;
      i++;
      if (i==2) le->SetLabel("New Label");
   }
}
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.