Search code examples
pythonmatplotliblegendtext-alignment

Python legend with GetDist tool : push a part of second line to the right while keepin the other part to the left


I use the Python GetDist tool available on : GetDist tool

My issue is simple. I would like to push to the right a part of the second line of the legend. For the moment, I have by default the following behavior :

2 lines of legend pushed to the left

I would like to modify the location of the partial text "a = 300" to the right, at the same horizontal level of first line, i.e at the same "level" than "a = 200" of first line, then creating a space between "Criterion taking into account" and "a = 300" : this is what I would like to get.

I have not found currently a function that could perform this or a simple option in the handling of this specification.

Update

I tried the updated version of @ted930511, i.e :

# g.settings
g = plots.get_subplot_plotter()

# Push Fom to the right into legend
renderer = g.fig.canvas.get_renderer()
shift = max([t.get_window_extent(renderer).width for t in g.legend.get_texts()])
for t in g.legend.get_texts():
    t.set_ha('right') # ha is alias for horizontalalignment
    t.set_position((shift,0))

But it is pushed to the right too much. Here the result :

Too much pushed to the right

I have printed the value of shift : shift = 898.1568

Maybe this value is too large. How can I push only the part "a = xxx" to the right of legend?


Solution

  • Is this what you want?

    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    
    fontP = FontProperties()
    fontP.set_size('xx-small')
    
    fig = plt.figure(figsize=(7.2, 7.2/2))
    ax = fig.add_axes([0.1, 0.1, 0.3, 0.8])
    p1, = ax.plot([1, 2, 3], label='Opt. Flat. No Gamma. - cross - standard situation - Criterion taken into account a=200')
    p2, = ax.plot([3, 2, 1], label='Pess. Flat. No Gamma. - Criterion taken into account                                            a=200')
    legend = ax.legend(handles=[p1, p2], bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)
    
    #renderer = fig.canvas.get_renderer()
    #shift = max([t.get_window_extent(renderer).width for t in legend.get_texts()])
    #for t in legend.get_texts():
    #    t.set_ha('right') # ha is alias for horizontalalignment
    #    t.set_position((shift,0))
    

    enter image description here