@@ -125,3 +125,46 @@ def test_imshow_xarray(xr):
125125
126126 xr = pytest .importorskip ('xarray' )
127127 return xr
128+
129+
130+ @pytest .fixture
131+ def text_placeholders (monkeypatch ):
132+ from matplotlib .patches import Rectangle
133+
134+ def patched_get_text_metrics_with_cache (renderer , text , fontprop , ismath , dpi ):
135+ """
136+ Replace ``_get_text_metrics_with_cache`` with fixed results.
137+
138+ The usual ``renderer.get_text_width_height_descent`` would depend on font
139+ metrics; instead the fixed results are based on font size and the length of the
140+ string only.
141+ """
142+ # While get_window_extent returns pixels and font size is in points, font size
143+ # includes ascenders and descenders. Leaving out this factor and setting
144+ # descent=0 ends up with a box that is relatively close to DejaVu Sans.
145+ height = fontprop .get_size ()
146+ width = len (text ) * height / 1.618 # Golden ratio for character size.
147+ descent = 0
148+ return width , height , descent
149+
150+ def patched_text_draw (self , renderer ):
151+ """
152+ Replace ``Text.draw`` with a fixed bounding box Rectangle.
153+
154+ The bounding box corresponds to ``Text.get_window_extent``, which ultimately
155+ depends on the above patched ``_get_text_metrics_with_cache``.
156+ """
157+ if renderer is not None :
158+ self ._renderer = renderer
159+ if not self .get_visible ():
160+ return
161+ if self .get_text () == '' :
162+ return
163+ bbox = self .get_window_extent ()
164+ rect = Rectangle (bbox .p0 , bbox .width , bbox .height ,
165+ facecolor = self .get_color (), edgecolor = 'none' )
166+ rect .draw (renderer )
167+
168+ monkeypatch .setattr ('matplotlib.text._get_text_metrics_with_cache' ,
169+ patched_get_text_metrics_with_cache )
170+ monkeypatch .setattr ('matplotlib.text.Text.draw' , patched_text_draw )
0 commit comments