Enzo
Enzo

Reputation: 348

Elements cut off from saved image if `bbox_to_anchor` is specified

Consider a simple scenario:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0,1], [0,1], label = 'Line')

lgd = fig.legend(bbox_to_anchor=(0.2, -1, 1., 0), loc='lower left')
fig.savefig('figure.png', bbox_extra_artists=(lgd,), bbox_inches='tight') 

This saves the figure and bbox_extra_artists allows for more space at the bottom, but the legend is not printed. This only happens if I try to specify values outside [0,1] in bbox_to_anchor, for example if I want the legend on the upper right side.

Any tips on why this happens?

Upvotes: 1

Views: 746

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339230

Something strange is going on with the "tight" calculation. The underlying cause of this is not yet clear as seen from https://github.com/matplotlib/matplotlib/issues/10194.

For the moment you can create an axes legend, and position it in figure coordinates,

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([0,1], [0,1], label = 'Line')

lgd = ax.legend(loc='lower left', 
                bbox_to_anchor=(0.2, -1, 1., 0),  bbox_transform=fig.transFigure)
fig.savefig('figure.png', bbox_inches='tight')

enter image description here

Upvotes: 2

Related Questions