Constrained layout does not work well with AnnotationBbox

I’m trying to use a constrained layout in a visualization that contains an artist that is an instance of AnnotationBbox, and matplotlib raises a warning saying constrained layout is not applied. The visual effect is not evident in this simple example, but it becomes very clear once we have multiple panels.

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea
print(matplotlib.__version__)
# 3.6.2

The following works without any warning

fig, ax = plt.subplots(layout="constrained")
ax.text(0.5, 0.5, "Some text", size=42, ha="center")
fig.set_facecolor("w")
fig.savefig("ax_text.png", dpi=300)

But if I use AnnotationBbox and TextArea

fig, ax = plt.subplots(layout="constrained")

ab = AnnotationBbox(
    TextArea("Some text", textprops={"size": 42}),
    (0.5, 0.5),
    xycoords="axes fraction",
    box_alignment=(0.5, 0.5),
    pad=0
)

ax.add_artist(ab)
fig.set_facecolor("w")
fig.savefig("annotation_box.png", dpi=300)

I have the following warning

UserWarning: constrained_layout not applied because axes sizes collapsed to zero.  Try making figure larger or axes decorations smaller.

and this is the result

The problem with the constrained layout is more evident if I have two or more panels.
One way of fixing it (i.e. getting rid of the warning and bad functionality) is to do ab.set_in_layout(False) before doing ax.add_artist(ab).

But I would like to know if this is a known issue, or if it’s that I’m simply doing something wrong.

Thanks!

1 Like

Can you make a GH issue with this example please?

Done! Thanks for replying :slight_smile: [Bug]: Constrained layout does not work well with AnnotationBbox · Issue #24453 · matplotlib/matplotlib · GitHub