#include #include #include #include #include #include void TLegend_example(){ TCanvas* canvas = new TCanvas("canvas","",100,100,600,600); // Just make some toy histograms TH1F* hBase = new TH1F("hBase","",100,0,1); TH1F* h1 = (TH1F*) hBase->Clone("h1"); TH1F* h2 = (TH1F*) hBase->Clone("h2"); TH1F* h3 = (TH1F*) hBase->Clone("h3"); h1->SetLineColor(kRed); h2->SetLineColor(kGreen); h3->SetLineColor(kBlue); h1->SetMarkerColor(kRed); h2->SetMarkerColor(kGreen); h3->SetMarkerColor(kBlue); // Fill them randomly TRandom3 random; for(Int_t i=0 ; i<1000 ; i++){ h1->Fill(random.Gaus(0.2,0.1)); h2->Fill(random.Gaus(0.5,0.3)); h3->Fill(random.Gaus(0.8,0.6)); } // Now make a TLegend and fill it // This legend will waste space TLegend legend_bad(0.45,0.8,0.85,0.5); legend_bad.AddEntry(h1,"h1","pe"); legend_bad.AddEntry(h2,"h2","pe"); legend_bad.AddEntry(h3,"h3","pe"); // Make some TLatex labels TLatex label_1_bad(0.5,0.90,"label 1"); TLatex label_2_bad(0.5,0.85,"label 2"); TLatex label_3_bad(0.5,0.80,"label 3"); label_1_bad.SetNDC(); label_2_bad.SetNDC(); label_3_bad.SetNDC(); // Draw it all canvas->cd(); h1->Draw("pe"); h2->Draw("pe:sames"); h3->Draw("pe:sames"); legend_bad.Draw(); label_1_bad.Draw(); label_2_bad.Draw(); label_3_bad.Draw(); canvas->Print("legend_bad.png"); // Now make another TLegend and fill it // This legend will take up only the space that it needs TLegend legend_good(0.45,0.8,0.6,0.5); legend_good.AddEntry(h1,"h1","pe"); legend_good.AddEntry(h2,"h2","pe"); legend_good.AddEntry(h3,"h3","pe"); // Make some TLatex labels // This time they can be nicely spaced next to the TLegend TLatex label_1_good(0.65,0.75,"label 1"); TLatex label_2_good(0.65,0.65,"label 2"); TLatex label_3_good(0.65,0.55,"label 3"); label_1_good.SetNDC(); label_2_good.SetNDC(); label_3_good.SetNDC(); // Draw it all canvas->cd(); h1->Draw("pe"); h2->Draw("pe:sames"); h3->Draw("pe:sames"); legend_good.Draw(); label_1_good.Draw(); label_2_good.Draw(); label_3_good.Draw(); canvas->Print("legend_good.png"); // Everything looks nice now! // Unfortunately I had to work this all out by hand because I cannot find out // how much space the text in the TLegend takes up. // I routinely make many plots, and so do colleagues, so it would be nice to be // able to automate the allocation of space. // // If I try to use TLegend.GetTextSize() it returns 0 (ie let the TLegend set // it when it gets drawn) so I cannot estimate the size of the text using a // TLatex object without first setting the size of the text in the TLegend. // But if I do that then I can't guarantee that the text will fit in the // TLegend at all! // Is there a way to esimate how much space the text in a TLegend will take up // so that I can choose the best size for the TLegend? }