Is it possible to align the entries of a TLegend on the right?
As far as I see there is only the SetTextAlign method, which aligns the text but not the actual entries:
The only way I could think of doing this would be to create a TLegend with empty labels on the right, and add a right-aligned TPaveText at its left, but it would be rather cumbersome.
You are right it is not possible to have the legend on the right. The legend is alway on the left and the text on the right. At some point it was assumed to be the most general case. Which indeed seems to be the case as you are (to my knowledge ) the first one asking for it on the forum.
For anybody interested, here’s some pyroot code I just wrote to draw a legend with custom alignment (R or L).
def createLegend(align, position, dict_of_entries):
'''
A TLegend with a custom alignment (left or right.)
Inputs:
- align: "R" or "L"
- position: a tuple with x1, y1, x2, y2 (brndc)
- dict_of_entries: a dictionary with the names of the objects
to include as keys, and tuples with the corrisponding labels
and style attributes as values.
Returns:
- "L": a normal legend and an empty one
- "R": two legends, one with the labels and one with the markers.
Call TLegend.Draw on leg_dummy first, and then on leg.
'''
delta = 0.04
if 'l' in align.lower():
leg = r.TLegend(*position)
for key in dict_of_entries:
leg.AddEntry(key, *dict_of_entries[key])
leg_dummy = r.TLegend(*position)
else:
width = position[2] - position[0]
entries_position = (position[2] - delta, position[1], position[2] - delta + width, position[3])
leg = r.TLegend(*entries_position)
for key in dict_of_entries:
leg.AddEntry(key, ' ', dict_of_entries[key][1])
dummy_position = (position[0], position[1], position[2] - delta, position[3])
leg_dummy = r.TLegend(*dummy_position)
for key in dict_of_entries:
leg_dummy.AddEntry(None, dict_of_entries[key][0], '')
leg_dummy.SetTextAlign(32)
for l in [leg, leg_dummy]:
leg.SetFillColor(r.kWhite)
leg.SetFillStyle(0)
leg.SetLineColor(r.kWhite)
return leg, leg_dummy