Skip to content

[Feature Request]: Support wrapping text relative to axes boundaries #31635

@codegnan-dm

Description

@codegnan-dm

Feature Request Summary

This feature request proposes an optional axes-aware text wrapping enhancement for Text objects attached to axes.

Currently, wrap=True wraps text relative to the figure boundary, which is consistent with the documented behavior of set_wrap:

“Wrapping makes sure the text is confined to the (sub)figure box. It does not take into account any other artists.”

However, in constrained multi-panel layouts, wrapping relative to the axes boundary can help prevent text from visually overlapping neighboring axes.

This feature request explores adding an optional axes-based wrapping mode while preserving the existing default behavior for backward compatibility.

Code for reproduction

import matplotlib.pyplot as plt

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6, 4))

ax1.set_title("Left Axes")
ax1.text(0.05, 0.5,
         "This is a very long string that should wrap within the axes boundary and not overflow outside it",
         wrap=True, transform=ax1.transAxes, va='center')

ax2.set_title("Right Axes")
ax2.text(0.05, 0.5,
         "This is a very long string that should wrap within the axes boundary and not overflow outside it",
         wrap=True, transform=ax2.transAxes, va='center')

plt.show()

Actual outcome

Text overflows outside the axes boundary into adjacent axes
or outside the figure. The text appears on a single line
ignoring the axes boundary completely.

Image

Expected outcome

Text should wrap within the axes boundary, staying inside
the axes it belongs to.

Image

Additional information

The root cause is in _get_wrap_line_width() in text.py.
It always uses the figure boundary:

figure_box = self.get_figure().get_window_extent()

It should check whether the text belongs to an axes first
and use the axes boundary instead:

if self.axes is not None:
    clip_box = self.axes.get_window_extent()
else:
    clip_box = self.get_figure().get_window_extent()

Operating system

Windows 11

Matplotlib Version

3.10.9

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions