How do I find the size of a legend in a figure?

Question:

The answer to
How to include the outside legend into the generated file?
is predicated on figuring out the size of a legend in inches.

How do I do that? legend inherits from artist and neither mentions size.

Asked By: sds

||

Answers:

The height of the legend is determined at draw time. To get the height, you have to first draw the figure with fig.canvas.draw() and then use legend.get_window_extent(). Specifically get height and width with .height and .width. The values are in pixels and the default DPI of Matplotlib is 100. So take the given values, divide by DPI (100), and that is your value in inches.

See:
Read height of legend in Python

Getting the width of a legend in matplotlib

Using your code from your previous question and just some random plot to show the difference:

nrows = 4
fig = plt.figure(figsize=(6, 2*nrows))
axes = fig.subplots(nrows=nrows, ncols=1)
names = [f"name-{n}" for n in range(10)]
for ax in axes:
    for n in names:
        ax.plot(np.arange(10),np.random.normal(size=10),label=n)
legend  = axes[0].legend(loc="upper left", bbox_to_anchor=(1,0,1,1))
plt.subplots_adjust(right=0.80)
fig.savefig("test.png")

fig.canvas.draw()
print(f'Height: {legend.get_window_extent().height/100} in')
print(f'Width: {legend.get_window_extent().width/100} in')

Output:

Height: 1.53 in
Width: 0.7425 in

enter image description here

x = [1,2,3,4,5]
y = [1,2,3,4,5]

fig = plt.figure()
axes = fig.subplots()
axes.plot(x,y, label="test")
legend = plt.legend()
fig.canvas.draw()
print(f'Height: {legend.get_window_extent().height/100} in')
print(f'Width: {legend.get_window_extent().width/100} in')

Output:

Height: 0.18 in
Width: 0.55125 in

enter image description here

Answered By: Michael S.
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.