Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 51a1ab6

Browse files
authored
Merge pull request #31061 from scottshambaugh/log_text_negative_coord
BUG: Fix text appearing far outside valid axis scale range
2 parents 00e29f2 + bb9daee commit 51a1ab6

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

lib/matplotlib/axes/_base.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2470,6 +2470,20 @@ def _add_text(self, txt):
24702470
self.stale = True
24712471
return txt
24722472

2473+
def _point_in_data_domain(self, x, y):
2474+
"""
2475+
Check if the data point (x, y) is within the valid domain of the axes
2476+
scales.
2477+
2478+
Returns False if the point is outside the data range
2479+
(e.g. negative coordinates with a log scale).
2480+
"""
2481+
for val, axis in zip([x, y], self._axis_map.values()):
2482+
vmin, vmax = axis.limit_range_for_scale(val, val)
2483+
if vmin != val or vmax != val:
2484+
return False
2485+
return True
2486+
24732487
def _update_line_limits(self, line):
24742488
"""
24752489
Figures out the data limit of the given line, updating `.Axes.dataLim`.

lib/matplotlib/tests/test_text.py

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

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

lib/matplotlib/text.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,6 +1060,15 @@ 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+
# Exclude text at data coordinates outside the valid domain of the axes
1065+
# scales (e.g., negative coordinates with a log scale).
1066+
if (self.axes
1067+
and self.get_transform() == self.axes.transData
1068+
and not self.axes._point_in_data_domain(*self.get_unitless_position())):
1069+
return Bbox.null()
1070+
return super().get_tightbbox(renderer)
1071+
10631072
def set_backgroundcolor(self, color):
10641073
"""
10651074
Set the background color of the text.

0 commit comments

Comments
 (0)