Skip to content

[Bug]: Annotation clipping to rect works, but not when setting xlim #30276

Open
@bmcfee

Description

@bmcfee

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

Image

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

Image

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy