Close all open figures and set the Matplotlib backend. The argument is case-insensitive. Switching to an interactive backend is possible only if no event loop for another interactive backend has started. Switching to and from non-interactive backends is always possible. Param
(newbackend)
| 175 | |
| 176 | |
| 177 | def switch_backend(newbackend): |
| 178 | """ |
| 179 | Close all open figures and set the Matplotlib backend. |
| 180 | |
| 181 | The argument is case-insensitive. Switching to an interactive backend is |
| 182 | possible only if no event loop for another interactive backend has started. |
| 183 | Switching to and from non-interactive backends is always possible. |
| 184 | |
| 185 | Parameters |
| 186 | ---------- |
| 187 | newbackend : str |
| 188 | The name of the backend to use. |
| 189 | """ |
| 190 | close("all") |
| 191 | |
| 192 | if newbackend is rcsetup._auto_backend_sentinel: |
| 193 | for candidate in ["macosx", "qt5agg", "qt4agg", "gtk3agg", "gtk3cairo", |
| 194 | "tkagg", "wxagg", "agg", "cairo"]: |
| 195 | try: |
| 196 | switch_backend(candidate) |
| 197 | except ImportError: |
| 198 | continue |
| 199 | else: |
| 200 | rcParamsOrig['backend'] = candidate |
| 201 | return |
| 202 | |
| 203 | backend_name = ( |
| 204 | newbackend[9:] if newbackend.startswith("module://") |
| 205 | else "matplotlib.backends.backend_{}".format(newbackend.lower())) |
| 206 | |
| 207 | backend_mod = importlib.import_module(backend_name) |
| 208 | Backend = type( |
| 209 | "Backend", (matplotlib.backends._Backend,), vars(backend_mod)) |
| 210 | _log.debug("Loaded backend %s version %s.", |
| 211 | newbackend, Backend.backend_version) |
| 212 | |
| 213 | required_framework = Backend.required_interactive_framework |
| 214 | if required_framework is not None: |
| 215 | current_framework = \ |
| 216 | matplotlib.backends._get_running_interactive_framework() |
| 217 | if (current_framework and required_framework |
| 218 | and current_framework != required_framework): |
| 219 | raise ImportError( |
| 220 | "Cannot load backend {!r} which requires the {!r} interactive " |
| 221 | "framework, as {!r} is currently running".format( |
| 222 | newbackend, required_framework, current_framework)) |
| 223 | |
| 224 | rcParams['backend'] = rcParamsDefault['backend'] = newbackend |
| 225 | |
| 226 | global _backend_mod, new_figure_manager, draw_if_interactive, _show |
| 227 | _backend_mod = backend_mod |
| 228 | new_figure_manager = Backend.new_figure_manager |
| 229 | draw_if_interactive = Backend.draw_if_interactive |
| 230 | _show = Backend.show |
| 231 | |
| 232 | # Need to keep a global reference to the backend for compatibility reasons. |
| 233 | # See https://github.com/matplotlib/matplotlib/issues/6092 |
| 234 | matplotlib.backends.backend = newbackend |