Skip to content

Commit 7bcdaf3

Browse files
tacaswellmelissawm
authored andcommitted
FIX: don't close figures is switch_backend unless really switching
closes matplotlib#14426
1 parent 635ae60 commit 7bcdaf3

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

lib/matplotlib/pyplot.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,6 @@ def switch_backend(newbackend):
224224
global _backend_mod
225225
# make sure the init is pulled up so we can assign to it later
226226
import matplotlib.backends
227-
close("all")
228227

229228
if newbackend is rcsetup._auto_backend_sentinel:
230229
current_framework = cbook._get_running_interactive_framework()
@@ -261,6 +260,8 @@ def switch_backend(newbackend):
261260
switch_backend("agg")
262261
rcParamsOrig["backend"] = "agg"
263262
return
263+
# have to escape the switch on access logic
264+
old_backend = dict.__getitem__(rcParams, 'backend')
264265

265266
backend_mod = importlib.import_module(
266267
cbook._backend_module_name(newbackend))
@@ -325,6 +326,9 @@ def draw_if_interactive():
325326
# Need to keep a global reference to the backend for compatibility reasons.
326327
# See https://github.com/matplotlib/matplotlib/issues/6092
327328
matplotlib.backends.backend = newbackend
329+
if not (isinstance(old_backend, str) and
330+
old_backend.lower() == newbackend.lower()):
331+
close("all")
328332

329333
# make sure the repl display hook is installed in case we become
330334
# interactive

lib/matplotlib/tests/test_pyplot.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,3 +429,14 @@ def test_minor_ticks():
429429
tick_labels = ax.get_yticklabels(minor=True)
430430
assert np.all(tick_pos == np.array([3.5, 6.5]))
431431
assert [l.get_text() for l in tick_labels] == ['a', 'b']
432+
433+
434+
def test_switch_backend_no_close():
435+
plt.switch_backend('agg')
436+
fig = plt.figure()
437+
fig = plt.figure()
438+
assert len(plt.get_fignums()) == 2
439+
plt.switch_backend('agg')
440+
assert len(plt.get_fignums()) == 2
441+
plt.switch_backend('svg')
442+
assert len(plt.get_fignums()) == 0

0 commit comments

Comments
 (0)