TLegend Disappears when I add a TRatioPlot (PyROOT)


Please read tips for efficient and successful posting and posting code

_ROOT Version:_6.27/01
_Platform:_Ubuntu
_Compiler:_Python


Hello,

i would like to make a histogram with a ratio plot and also have a legend. When I try to do it with the following code, I get this result:

c1 = ROOT.TCanvas()

df = df.Filter("ditau_m_mmc > 20")

hist = df.Histo1D(("Ditau_m", "ditau_m", 100, 0, 500),"ditau_m")

hist1 = df.Histo1D(("Ditau_m_mmc", "ditau_m_mmc", 100, 0, 500),"ditau_m_mmc")

hist.Scale(hist1.Integral() / hist.Integral())
hist.SetLineColor(ROOT.kRed)
hist1.SetLineColor(ROOT.kBlue)
hist.SetFillStyle(0)
hist1.Draw("SAME, h")
hist.Draw("SAME, h")
hist.SetStats(0)
hist1.SetStats(0)
rp = ROOT.TRatioPlot(hist1.GetPtr(), hist.GetPtr())
rp.GetLowYaxis().SetRange(0, 5)
rp.SetH1DrawOpt("AC.")
rp.Draw()


legend = ROOT.TLegend(0.7, 0.7, 0.9, 0.9)
legend.AddEntry(hist.GetPtr(), "Ditau M")
legend.AddEntry(hist1.GetPtr(), "Ditau M MCC")
legend.Draw("SAME")


(Bonus question: why are the red histogram points different than the blue ones?)
As soon as I get rid of the ratioplot, it magically works:

Whats the solution here?

Hi!

The solution is to change to the top pad before drawing the legend:

rp.GetUpperPad().cd();
legend.Draw()

As for the different histogram styles, that’s just because the TRatioPlot does that by default (usually people want error bars only for the second histogram). For the first histogram, the default drawing option is "hist", and for the second one it’s "E". But as you already noticed, you can change the style to what you like with SetH1DrawOpt() and SetH2DrawOpt().

PS: see also Creating Legend for Upper Plot in TRatioPlot, where the call to TPad::BuildLegend() implicitly does the cd().

1 Like

Thanks, it works!

Note that “SAME” is not a drawing option for TLegend. Basically TLegend::Draw() does not use the option parameter. so it is enough to do the following:

rp.GetUpperPad().cd();
legend.Draw()
1 Like

Sorry @couet, that was a copy-paste error! I have updated my post to not have the "SAME", just in case people or ChatGPT look at this in the future.

@Jonas, no problem, the option is ignored anyway. It is simply not needed :wink:

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