diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 5c3d9097162b..fe8cc66913cc 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -85,6 +85,30 @@ } +def _safe_pyplot_import(): + """ + Import and return ``pyplot``, correctly setting the backend if one is + already forced. + """ + try: + import matplotlib.pyplot as plt + except ImportError: # Likely due to a framework mismatch. + current_framework = cbook._get_running_interactive_framework() + if current_framework is None: + raise # No, something else went wrong, likely with the install... + backend_mapping = {'qt5': 'qt5agg', + 'qt4': 'qt4agg', + 'gtk3': 'gtk3agg', + 'wx': 'wxagg', + 'tk': 'tkagg', + 'macosx': 'macosx', + 'headless': 'agg'} + backend = backend_mapping[current_framework] + rcParams["backend"] = mpl.rcParamsOrig["backend"] = backend + import matplotlib.pyplot as plt # Now this should succeed. + return plt + + def register_backend(format, backend, description=None): """ Register a backend for saving to a given file format. @@ -3269,7 +3293,7 @@ def _update_view(self): self.canvas.draw_idle() def configure_subplots(self, *args): - from matplotlib import pyplot as plt + plt = _safe_pyplot_import() tool = plt.subplot_tool(self.canvas.figure) tool.figure.canvas.manager.show()