Question about the height of a text's bounding box

I’m trying to improve the bounding box capabilities of Flexitext and I’m facing one issue with the height of the bounding box of the text.

Let’s see the following example

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 3))

ax.text(0.5, 0.5, "abcde", size=60, ha="right", bbox={"fc": "green", "pad": 0})
ax.text(0.5, 0.5, "fghijk", size=60, ha="left", bbox={"fc": "green", "pad": 0})

fig.savefig("plot.png", dpi=300)

In both cases, Matplotlib created a bounding box of the same height. On the left, this results in extra space below abcde. On the right, this does not result in any extra space, because it is used by letters such as g and j.

My guess is that Matplotlib looks at the height of all the glyphs in the font being used, and makes sure anything you write fits in the bounding box.

I would like to know if it is possible to adjust the height of the bounding box to the actual text, without considering other glyphs in the font.

On the other hand, I have another example where the text escapes the bounding box.

fig, ax = plt.subplots(figsize=(8, 3))
ax.text(0.5, 0.5, "abcde", size=60, ha="center", fontname="Satisfy", bbox={"fc": "green", "pad": 0})
fig.savefig("plot.png", dpi=300)

Is this a bug in how Matplotlib determines the size of the bounding box?

I believe that’s dependent on the type and style of the font being used. In order to have the font “look right” when it’s used, a character can extend “above or below the line” (like your first example). So not every character is distributed within its boundary the same way. In other words, the a has the same size boundary as the g. I wouldn’t say that this is a bug within matplotlib (although the cursive example you cite is interesting).

For goal, I think you’d need to collect the size of the glyphs that you actually use and work from that (although I’ve never done this myself). Something in the neighborhood of this.

1 Like

I am speculating a bit here, but I believe the bounding box is based on the font metrics from the font and making use of the bonding boxes that are used to layout the text. If Satisify is a cursive font I would accept it is true if someone claimed that its glyphs extended outside of the box used for layout to be extra sure you never got gaps (this seems testable by using a low alpha on the text and seeing if you get weird artifacts).