Home | News | Documentation | Download

Create legend for histogram created in for loop

ROOT Version: 6.18/04
Platform: Linux

I am trying to add a legend to a plot that consists of 3 histograms that were created in a for loop, they are called ratio[i], where i goes from 0 to 2, and refers to the elements in the following vector:

std::vector<std::string> Cut = {"L_J20", "L_J30", "L_J40"}

I have given each histogram a different colour by writing:

if (i == 0) ratio[i]->SetLineColor(kRed);
else if (i == 1) ratio[i]->SetLineColor(kBlue);
else ratio[i]->SetLineColor(kYellow);

This works, but I was wondering if there is a quicker way to do this (in the form of a loop perhaps). But then my main question is, how do I now create a legend for these histograms? I have tried:

auto legend = new TLegend (.1, .7, .3, .9);
legend->AddEntry(ratio[0], "J20")
legend->AddEntry(ratio[1], "J30")
legend->AddEntry(ratio[2], "J40")

This doesn’t work (it crashes, but I get no error). Anyone got any idea on how to solve this?

   TH1D *h[3];

   for (int i=0; i<3; i++) {
      h[i] = new TH1D(Form("h%d",i), Form("h%d",i), 100, -1, 1);


   auto legend = new TLegend(0.1,0.7,0.28,0.9);

   for (int i=0; i<3; i++) {
      legend->AddEntry(h[i], Form("J%d0",i+3), "l");



That works! Thanks! What would I do, if I don’t want the J’s to be consecutive though? So, what would I do if I want to call my histograms J20, J40 and J75 for example?

If there is no logic in the legend’s comments you want tu use, it will not be possible to use the logic I showed you. You need to make an array of comments instead.

1 Like