8000 Merge pull request #18316 from anntzer/safe_pyplot_import · matplotlib/matplotlib@3d725f6 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3d725f6

Browse files
authored
Merge pull request #18316 from anntzer/safe_pyplot_import
Safely import pyplot if a GUI framework is already running.
2 parents 5102676 + e7bab33 commit 3d725f6

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

lib/matplotlib/backend_bases.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,30 @@
8585
}
8686

8787

88+
def _safe_pyplot_import():
89+
"""
90+
Import and return ``pyplot``, correctly setting the backend if one is
91+
already forced.
92+
"""
93+
try:
94+
import matplotlib.pyplot as plt
95+
except ImportError: # Likely due to a framework mismatch.
96+
current_framework = cbook._get_running_interactive_framework()
97+
if current_framework is None:
98+
raise # No, something else went wrong, likely with the install...
99+
backend_mapping = {'qt5': 'qt5agg',
100+
'qt4': 'qt4agg',
101+
'gtk3': 'gtk3agg',
102+
'wx': 'wxagg',
103+
'tk': 'tkagg',
104+
'macosx': 'macosx',
105+
'headless': 'agg'}
106+
backend = backend_mapping[current_framework]
107+
rcParams["backend"] = mpl.rcParamsOrig["backend"] = backend
108+
import matplotlib.pyplot as plt # Now this should succeed.
109+
return plt
110+
111+
88112
def register_backend(format, backend, description=None):
89113
"""
90114
Register a backend for saving to a given file format.
@@ -3269,7 +3293,7 @@ def _update_view(self):
32693293
self.canvas.draw_idle()
32703294

32713295
def configure_subplots(self, *args):
3272-
from matplotlib import pyplot as plt
3296+
plt = _safe_pyplot_import()
32733297
tool = plt.subplot_tool(self.canvas.figure)
32743298
tool.figure.canvas.manager.show()
32753299

0 commit comments

Comments
 (0)
0