Skip to content

Commit 4c0656d

Browse files
committed
FIX/API: fig.canvas.draw always updates internal state
Previously the non-interactive backends, other than Agg, did not define `draw` methods and fell back to the base no-op version. However, we have been documenting that the correct way to update the various internal state we keep (run tight/constrained layouts, auto limits, text size/position, ...), this is now a bug due to our suggested usage drifting. closes matplotlib#18407
1 parent dbe3622 commit 4c0656d

6 files changed

Lines changed: 62 additions & 6 deletions

File tree

‎lib/matplotlib/backend_bases.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1587,6 +1587,12 @@ def _draw(renderer): raise Done(renderer)
15871587
figure.canvas = orig_canvas
15881588

15891589

1590+
def _no_output_draw(figure):
1591+
renderer = _get_renderer(figure)
1592+
with renderer._draw_disabled():
1593+
figure.draw(renderer)
1594+
1595+
15901596
def _is_non_interactive_terminal_ipython(ip):
15911597
"""
15921598
Return whether we are in a a terminal IPython, but non interactive.
@@ -1624,7 +1630,9 @@ def _check_savefig_extra_args(func=None, extra_kwargs=()):
16241630
@functools.wraps(func)
16251631
def wrapper(*args, **kwargs):
16261632
name = 'savefig' # Reasonable default guess.
1627-
public_api = re.compile(r'^savefig|print_[A-Za-z0-9]+$')
1633+
public_api = re.compile(
1634+
r'^savefig|print_[A-Za-z0-9]+|_no_output_draw$'
1635+
)
16281636
seen_print_figure = False
16291637
for frame, line in traceback.walk_stack(None):
16301638
if frame is None:
@@ -1635,8 +1643,9 @@ def wrapper(*args, **kwargs):
16351643
frame.f_globals.get('__name__', '')):
16361644
if public_api.match(frame.f_code.co_name):
16371645
name = frame.f_code.co_name
1638-
if name == 'print_figure':
1646+
if name in ('print_figure', '_no_output_draw'):
16391647
seen_print_figure = True
1648+
16401649
else:
16411650
break
16421651

‎lib/matplotlib/backends/backend_pdf.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
from matplotlib._pylab_helpers import Gcf
2929
from matplotlib.backend_bases import (
3030
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
31-
GraphicsContextBase, RendererBase)
31+
GraphicsContextBase, RendererBase, _no_output_draw)
3232
from matplotlib.backends.backend_mixed import MixedModeRenderer
3333
from matplotlib.figure import Figure
3434
from matplotlib.font_manager import findfont, get_font
@@ -2727,6 +2727,9 @@ def print_pdf(self, filename, *,
27272727
else: # we opened the file above; now finish it off
27282728
file.close()
27292729

2730+
def draw(self, *args, **kwargs):
2731+
_no_output_draw(self.figure)
2732+
return super().draw(*args, **kwargs)
27302733

27312734
FigureManagerPdf = FigureManagerBase
27322735

‎lib/matplotlib/backends/backend_pgf.py‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
from matplotlib import _api, cbook, font_manager as fm
2020
from matplotlib.backend_bases import (
2121
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
22-
GraphicsContextBase, RendererBase)
22+
GraphicsContextBase, RendererBase, _no_output_draw
23+
)
2324
from matplotlib.backends.backend_mixed import MixedModeRenderer
2425
from matplotlib.backends.backend_pdf import (
2526
_create_pdf_info_dict, _datetime_to_pdf)
@@ -900,6 +901,10 @@ def print_png(self, fname_or_fh, *args, **kwargs):
900901
def get_renderer(self):
901902
return RendererPgf(self.figure, None)
902903

904+
def draw(self, *args, **kwargs):
905+
_no_output_draw(self.figure)
906+
return super().draw()
907+
903908

904909
FigureManagerPgf = FigureManagerBase
905910

‎lib/matplotlib/backends/backend_ps.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
from matplotlib.afm import AFM
2424
from matplotlib.backend_bases import (
2525
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
26-
GraphicsContextBase, RendererBase)
26+
GraphicsContextBase, RendererBase, _no_output_draw)
2727
from matplotlib.cbook import is_writable_file_like, file_requires_unicode
2828
from matplotlib.font_manager import get_font
2929
from matplotlib.ft2font import LOAD_NO_HINTING, LOAD_NO_SCALE
@@ -1126,6 +1126,9 @@ def _print_figure_tex(
11261126

11271127
_move_path_to_path_or_stream(tmpfile, outfile)
11281128

1129+
def draw(self, *args, **kwargs):
1130+
_no_output_draw(self.figure)
1131+
return super().draw()
11291132

11301133
def convert_psfrags(tmpfile, psfrags, font_preamble, custom_preamble,
11311134
paper_width, paper_height, orientation):

‎lib/matplotlib/backends/backend_svg.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from matplotlib import _api, cbook
1818
from matplotlib.backend_bases import (
1919
_Backend, _check_savefig_extra_args, FigureCanvasBase, FigureManagerBase,
20-
RendererBase)
20+
RendererBase, _no_output_draw)
2121
from matplotlib.backends.backend_mixed import MixedModeRenderer
2222
from matplotlib.colors import rgb2hex
2323
from matplotlib.dates import UTC
@@ -1360,6 +1360,9 @@ def _print_svg(self, filename, fh, *, dpi=72, bbox_inches_restore=None,
13601360
def get_default_filetype(self):
13611361
return 'svg'
13621362

1363+
def draw(self, *args, **kwargs):
1364+
_no_output_draw(self.figure)
1365+
return super().draw()
13631366

13641367
FigureManagerSVG = FigureManagerBase
13651368

‎lib/matplotlib/tests/test_backend_bases.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,3 +180,36 @@ def test_toolbar_zoompan():
180180
assert ax.get_navigate_mode() == "ZOOM"
181181
ax.figure.canvas.manager.toolmanager.trigger_tool('pan')
182182
assert ax.get_navigate_mode() == "PAN"
183+
184+
185+
@pytest.mark.parametrize("backend", ['svg', 'pgf', 'ps', 'pdf'])
186+
def test_draw(backend):
187+
from matplotlib.figure import Figure
188+
from matplotlib.backends.backend_agg import FigureCanvas
189+
test_backend = pytest.importorskip(
190+
f'matplotlib.backends.backend_{backend}'
191+
)
192+
TestCanvas = test_backend.FigureCanvas
193+
fig_test = Figure(constrained_layout=True)
194+
TestCanvas(fig_test)
195+
axes_test = fig_test.subplots(2, 2)
196+
197+
# defaults to FigureCanvasBase
198+
fig_agg = Figure(constrained_layout=True)
199+
# put a backends.backend_agg.FigureCanvas on it
200+
FigureCanvas(fig_agg)
201+
axes_agg = fig_agg.subplots(2, 2)
202+
203+
init_pos = [ax.get_position() for ax in axes_test.ravel()]
204+
205+
fig_test.canvas.draw()
206+
fig_agg.canvas.draw()
207+
208+
layed_out_pos_test = [ax.get_position() for ax in axes_test.ravel()]
209+
layed_out_pos_agg = [ax.get_position() for ax in axes_agg.ravel()]
210+
211+
for init, placed in zip(init_pos, layed_out_pos_test):
212+
assert not np.allclose(init, placed, atol=0.005)
213+
214+
for ref, test in zip(layed_out_pos_agg, layed_out_pos_test):
215+
np.testing.assert_allclose(ref, test, atol=0.005)

0 commit comments

Comments
 (0)