Skip to content
Advertisement

Total figure width with external legend in matplotlib

I’m using

plt.legend(bbox_to_anchor = (1,1))

to put the legend outside my figure. The journal to which I’m submitting requires specific sizes for the figures. When I use this method, it increases the total width of my figure beyond the required size. I want to have the figure sized exactly to specification. Is there a way to calculate the total width of the figure including the external legend, so that I can reduce my figsize parameter accordingly?

Advertisement

Answer

The following works fine; I’ve just coloured the figure so you can see its size.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, ax = plt.subplots(figsize=(3, 3), constrained_layout=True)
fig.set_facecolor('0.5')
ax.plot(np.arange(10), label='Boo')
ax.legend(bbox_to_anchor=(1, 1))
fig.savefig('boo.png')

enter image description here

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement