TLegend make a box on a TF1

Hello,

I am trying to make a box over a TF1 in the Legend.

I have something like this:

where fstat is a TF1

legendcell = new TLegend(0.67,0.53,0.98,0.7+0.015*(years.size()));
fstat->SetLineColor(429);
fstat->SetFillColor(5);
fstat->SetFillStyle(1001);

legendcell->AddEntry(fstat, “#bf{” + legend + “}” ,“fl”);

legendcell->Draw();

The problem is that this also creates a filling in the TGraph.
Is there any way to create a box on the TLegend without changing the drawing on the canvas?

PS: I also tried to do fstat->SetFillStyle(0); after the drawing of the legend but this also removes the box from the TLegend

My root version is 6.28/00

I really appreciate any help you can provide.

Hi Beatriz,

Could you provide a minimal reproducer for this plot for us to be able to help?

Cheers,
D

I can try:

graph = (TGraphErrors*) file->Get(graphname);

TMultiGraph *statgraph = new TMultiGraph();

statgraph = Add(graph)

TF1 *fstat = new TF1(“fit”,fitfunc_form.c_str());

fstat = (TF1*) graph->GetFunction(“fit”);

TLegend legendcell;
legendcell = new TLegend(0.67,0.53,0.98,0.7+0.015
(years.size()));

fstat->SetLineColor(429);
fstat->SetFillColor(5);
fstat->SetFillStyle(1001);

legendcell->AddEntry(fstat, “#bf{” + legend + “}” ,“fl”);

legendcell->Draw();

statgraph->Draw(“ap”);

Something like this helps?

Hi,

Thanks a lot! However, this is still extracted from a context where variables are defined… Can you make it a macro we can execute perhaps?

Cheers,
D

You could add an empty entry and then manually draw a TBox in the position you want (and you’ll have to find out the coordinates), see as a starting guide the second example in the TLegend documentation.
Another option, maybe simpler, is to make a fake function (or histogram) with the line and fill styles as the one you want, but at a position outside the limits of the frame you are plotting, and add this function, instead of the real one, to the legend (you have to Draw it, otherwise the fill doesn’t show on the legend; drawing it outside the frame means it is not visible, but the entry is correctly added to the legend); e.g.

{
   auto c1 = new TCanvas("c1","c1",600,500);
   gStyle->SetOptStat(0);
 
   auto h1 = new TH1F("h1","TLegend Example",200,-10,10);
   h1->FillRandom("gaus",30000);
   h1->SetFillColor(kGreen);
   h1->SetFillStyle(3003);
   h1->Draw();
 
   auto f1=new TF1("f1","x",-20,-20);  // outside the range of the histogram shown (-10 to 10)
   f1->SetLineColor(kBlue);
   f1->SetLineWidth(2);
   f1->SetFillColor(5);
   f1->SetFillStyle(1001);
   f1->Draw("same");
 
   auto legend = new TLegend(0.1,0.7,0.48,0.9);
   legend->AddEntry(h1,"Histogram filled with random numbers","f");
   legend->AddEntry("f1","Dummy function","fl");
   legend->Draw();
}

c1

Hello,

Yes, this works, thank you very much. I thought there was another way to do but maybe not.

Kind regards,