# Legend

Hello!

I wish to add a legend to my plot, but i don’ manage to make it visible, can someone tell me what’s wrong?

/Karin
test.C (2.1 KB)

here is a simple example:

``````{
TH1F *h1=new TH1F("h1","h1",5,0,5);
h1->SetFillStyle(3004);
h1->SetFillColor(1);
h1->Fill(3);
h1->Draw();

TH1F *h2=new TH1F("h2","h2",5,0,5);
h2->SetFillStyle(3005);
h2->SetFillColor(1);
h2->SetLineColor(2);
h2->Fill(2);
h2->Draw("SAME");

TLegend *leg=new TLegend(0.2,0.2,0.4,0.4);
leg->SetEntrySeparation(0.1);
leg->Draw();
}``````

Thank you!

What I wish to do is however to have several histoes in one figure, lets say 2*2. I wish to have a title on the top and a legend to each histo. What i have done is to create a pad that I have divided into 4 parts. It now seems that this pad is covering my legend so it doesn’t show. If I don’t draw my pad I do indeed see it. So my question is, how can I achieve a divided figure with a visible legend.

/Karin

here is a divided figure with a visible legend:

``````{
c = new TCanvas("c","c",200,10,700,700);
c->Divide(1,2);
c->cd(1);
TH1F *h1=new TH1F("h1","h1",5,0,5);
h1->SetFillStyle(3004);
h1->SetFillColor(1);
h1->Fill(3);
h1->Draw();

c->cd(2);
TH1F *h2=new TH1F("h2","h2",5,0,5);
h2->SetFillStyle(3005);
h2->SetFillColor(1);
h2->SetLineColor(2);
h2->Fill(2);
h2->Draw();

TLegend *leg=new TLegend(0.2,0.2,0.4,0.4);
leg->SetEntrySeparation(0.1);
leg->Draw();
}``````

Thank you!

So what I did wrong was to draw the legend too early, I had to do it last! I noticed in your code that you divide the canvas starigt ahead instead of creating a pad ontop of it and divide that one. Could you explain the difference between these too approaches, is one to prefer before the other? (I have kept my pad so far…)

/Karin

I just looked at your macro (I must admit I hadn’t before). Why are you doing Divide(1,1) ? … this is equivalent of doing nothing. TLegend is drawn in the current pad. The current pad is defined with the "cd"command applied on the divided pad. In your macro you draw the TLegend before the “cd”. Take the example I sent you as starting point.

Olivier

Hello!

hehe, well I intend to do divide(n,n) later, but since it didn’t work I did divide(1,1) instead of taking it away, since I figured the problem was with the pad rather than with the division…
I have managed to get it right now thanks to your example, but I still don’t undestand the difference between dividing the canvas or dividing a pad…
/Karin

Well, you can also divide a pad. Example:

``````{
c = new TCanvas("c","c",200,10,700,700);
p->Draw();
p->Divide(1,2);
p->cd(1);
TH1F *h1=new TH1F("h1","h1",5,0,5);
h1->SetFillStyle(3004);
h1->SetFillColor(1);
h1->Fill(3);
h1->Draw();

p->cd(2);
TH1F *h2=new TH1F("h2","h2",5,0,5);
h2->SetFillStyle(3005);
h2->SetFillColor(1);
h2->SetLineColor(2);
h2->Fill(2);
h2->Draw();

TLegend *leg=new TLegend(0.2,0.2,0.4,0.4);