@@ -210,21 +210,24 @@ def _get_backend_mod():
210210
211211def switch_backend (newbackend ):
212212 """
213- Close all open figures and set the Matplotlib backend.
213+ Set the pyplot backend.
214214
215- The argument is case-insensitive. Switching to an interactive backend is
216- possible only if no event loop for another interactive backend has started.
217- Switching to and from non-interactive backends is always possible.
215+ Switching to an interactive backend is possible only if no event loop for
216+ another interactive backend has started. Switching to and from
217+ non-interactive backends is always possible.
218+
219+ If the new backend is different than the current backend then all open
220+ Figures will be closed via ``plt.close('all')``.
218221
219222 Parameters
220223 ----------
221224 newbackend : str
222- The name of the backend to use.
225+ The case-insensitive name of the backend to use.
226+
223227 """
224228 global _backend_mod
225229 # make sure the init is pulled up so we can assign to it later
226230 import matplotlib .backends
227- close ("all" )
228231
229232 if newbackend is rcsetup ._auto_backend_sentinel :
230233 current_framework = cbook ._get_running_interactive_framework ()
@@ -261,6 +264,8 @@ def switch_backend(newbackend):
261264 switch_backend ("agg" )
262265 rcParamsOrig ["backend" ] = "agg"
263266 return
267+ # have to escape the switch on access logic
268+ old_backend = dict .__getitem__ (rcParams , 'backend' )
264269
265270 backend_mod = importlib .import_module (
266271 cbook ._backend_module_name (newbackend ))
@@ -325,6 +330,8 @@ def draw_if_interactive():
325330 # Need to keep a global reference to the backend for compatibility reasons.
326331 # See https://github.com/matplotlib/matplotlib/issues/6092
327332 matplotlib .backends .backend = newbackend
333+ if not cbook ._str_equal (old_backend , newbackend ):
334+ close ("all" )
328335
329336 # make sure the repl display hook is installed in case we become
330337 # interactive
0 commit comments