Open
Description
Bug summary
This is something of a follow-up to #28717 .
I have a display that involves setting a text annotation within a rectangular patch (axvspan) with clipping. Per #28717, this works fine, eg:
fig, ax = plt.subplots()
# 1) draw a vertical span from x=2 to x=3.05
rect = ax.axvspan(2, 3.05, ymin=0, ymax=1, color='red', alpha=0.5)
# 2) place an annotation inside that span and clip it to the patch
ann = ax.annotate(
"Hello",
xy=(3, 0.5), # in data coords (x) and axes-fraction (y)
xycoords=("data", "axes fraction"),
xytext=(0, 0),
textcoords="offset points",
va="center",
clip_on=True,
)
ann.set_clip_path(rect)
does the following

If, however, I follow the above code with an xlimit set:
ax.set_xlim(0, 3)
then the text is no longer clipped properly.
Code for reproduction
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# 1) draw a vertical span from x=2 to x=3.05
rect = ax.axvspan(2, 3.05, ymin=0, ymax=1, color='red', alpha=0.5)
# 2) place an annotation inside that span and clip it to the patch
ann = ax.annotate(
"Hello",
xy=(3, 0.5), # in data coords (x) and axes-fraction (y)
xycoords=("data", "axes fraction"),
xytext=(0, 0),
textcoords="offset points",
va="center",
clip_on=True,
)
ann.set_clip_path(rect)
# 3) now change the x-axis limits – the span will be clipped
# but the text remains visible beyond the new limits.
ax.set_xlim(0, 3)
Actual outcome

Note that the annotation is outside the axes.
Expected outcome
If the text is clipped by the rect, it should stay clipped even when the rect falls out of view.
Additional information
No response
Operating system
ubuntu, but probably irrelevant
Matplotlib Version
3.10.3
Matplotlib Backend
inline
Python version
3.13
Jupyter version
jupyterlab 4.4.4
Installation
conda
Metadata
Metadata
Assignees
Labels
No labels