How to get the location of a legend in matplotlib

I am trying to find the place of a legend in matplotlib. It looks like Legend.get_window_extent () should provide this, but it returns the same value no matter where the legend is. Here's an example:

from matplotlib import pyplot as plt

def get_legend_pos(loc):

    plt.figure()
    plt.plot([0,1],label='Plot')
    legend=plt.legend(loc=loc)

    plt.draw()

    return legend.get_window_extent()

if __name__=='__main__':

    # Returns a bbox that goes from (0,0) to (1,1)
    print get_legend_pos('upper left')

    # Returns the same bbox, even though legend is in a different location!
    print get_legend_pos('upper right')

      

What's the correct way to get the location of the legend?

+3


source to share


2 answers


You need to replace plt.draw()

with

plt.gcf().canvas.draw()

      



or, if you have a figure fig.canvas.draw()

. This is necessary because the position of the legend is only determined when drawing the canvas, before it just sits in one place.

Usage is plt.draw()

not sufficient because the legend requires a valid renderer from the backend being used to draw.

+1


source


TL DR; Try the following:

def get_legend_pos(loc):
    plt.figure()
    plt.plot([0,1],label='Plot')
    legend=plt.legend(loc=loc)
    plt.draw()
    plt.pause(0.0001)
    return legend.get_window_extent()

      

That's why

So I tried my code in Jupyter and I can reproduce the behavior with the option

%matplotlib notebook

      

However, for

%matplotlib inline

      

I am getting the correct answer



Bbox(x0=60.0, y0=230.6, x1=125.69999999999999, y1=253.2)
Bbox(x0=317.1, y0=230.6, x1=382.8, y1=253.2)

      

It looks like in the first case, the position of the legend is not evaluated until execution is complete. Here is an example that proves it, in the first cell I execute

fig = plt.figure()
plt.plot([0,1],label='Plot')
legend=plt.legend(loc='upper left')
plt.draw()
print(legend.get_window_extent()) 

      

Conclusion Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)

.

In the next cell, override the last expression

print(legend.get_window_extent()) 

      

Outputs Bbox(x0=88.0, y0=396.2, x1=175.725, y1=424.0)

You probably just need to add plt.pause()

to provide an estimate.

+2


source







All Articles