X Tutup
Skip to content

Commit 0d3ef72

Browse files
Fix text appearing outside axis scale range
1 parent 42e142d commit 0d3ef72

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

lib/matplotlib/artist.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,24 @@ def get_window_extent(self, renderer=None):
375375
"""
376376
return Bbox([[0, 0], [0, 0]])
377377

378+
def _in_axes_domain(self, x, y):
379+
"""
380+
Check if the data point (x, y) is within the valid domain of the axes
381+
scales.
382+
383+
Returns True if no axes or if the point is in the valid domain.
384+
"""
385+
ax = self.axes
386+
if ax is None:
387+
return True
388+
for val, axis in [(x, ax.xaxis), (y, ax.yaxis)]:
389+
if axis.get_scale() == 'linear':
390+
continue
391+
vmin, vmax = axis.limit_range_for_scale(val, val)
392+
if vmin != val or vmax != val:
393+
return False
394+
return True
395+
378396
def get_tightbbox(self, renderer=None):
379397
"""
380398
Get the artist's bounding box in display space, taking clipping into account.

lib/matplotlib/tests/test_text.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1226,3 +1226,15 @@ def test_ytick_rotation_mode():
12261226
tick.set_rotation(angle)
12271227

12281228
plt.subplots_adjust(left=0.4, right=0.6, top=.99, bottom=.01)
1229+
1230+
1231+
def test_text_tightbbox_outside_scale_domain():
1232+
# Test that text at positions outside the valid domain of axes scales
1233+
# (e.g., negative coordinates with log scale) returns a null bbox.
1234+
fig, ax = plt.subplots()
1235+
ax.set_yscale('log')
1236+
ax.set_ylim(1, 100)
1237+
1238+
invalid_text = ax.text(0, -5, 'invalid')
1239+
invalid_bbox = invalid_text.get_tightbbox(fig.canvas.get_renderer())
1240+
assert not np.isfinite(invalid_bbox.width)

lib/matplotlib/text.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,16 @@ def get_window_extent(self, renderer=None, dpi=None):
10601060
bbox = bbox.translated(x, y)
10611061
return bbox
10621062

1063+
def get_tightbbox(self, renderer=None):
1064+
if not self.get_visible() or self.get_text() == "":
1065+
return Bbox.null()
1066+
# Exclude text at positions outside the valid domain of the axes
1067+
# scales (e.g., negative coordinates with a log scale).
1068+
if (self.axes is not None and self.get_transform() == self.axes.transData
1069+
and not self._in_axes_domain(*self.get_unitless_position())):
1070+
return Bbox.null()
1071+
return super().get_tightbbox(renderer)
1072+
10631073
def set_backgroundcolor(self, color):
10641074
"""
10651075
Set the background color of the text.

0 commit comments

Comments
 (0)
X Tutup