Get Matplotlib legend location?

前端 未结 2 1752
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 13:09

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_win         


        
相关标签:
2条回答
  • 2020-12-18 13:11

    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

    0 讨论(0)
  • 2020-12-18 13:13

    on this line of code

    leg = ax.legend(['line 1'], loc=6, frameon=False)
    

    Make the loc=0 this makes your plot to stay on the best location where it will not overlap or have the least overlap with your plot diagram.

    0 讨论(0)
提交回复
热议问题