pythonmatplotlib

Get Matplotlib legend location?


I would like to the get the position (x, y of either the axes data or scale) of a matplotlib legend. I have tried the following:

l = ax.legend(...)
l.get_window_extent()
l.legendPatch.get_bbox().inverse_transformed(ax.transAxes) 

My goal would be use the position of the legend to add a text box with additional information next to it.


Solution

  • The way of getting position of the legend depends on the legend and when do you access it.

    It seems like it is best if you access the legend object after you draw the plot, i.e. after calling:

    plt.draw()
    

    Accessing legend object position after this will return figure pixels which you can use later.

    There are at least two ways to access legend position:

    1. A universal way through .get_window_extent() method
    2. If the legend has a frame through .get_frame().get_bbox().bounds methods

    Clearly if the legend has no frame then the 1st method is preferred :-)

    You can play with both to see how best to deal with each one.

    Here is an example of how you could do it:

    import matplotlib.pyplot as plt
    
    x = y = [1,2,3,4,5]
    
    fig, ax = plt.subplots()
    
    ax.plot(x,y)
    leg = ax.legend(['line 1'], loc=6, frameon=False)
    
    plt.draw()
    
    p = leg.get_window_extent()
    
    ax.annotate('Annotation Text', (p.p0[0], p.p1[1]), (p.p0[0], p.p1[1]), 
                xycoords='figure pixels', zorder=9)
    
    plt.show()
    

    This yields:

    legend annotated