Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e7bab33

Browse files
committed
Safely import pyplot if a GUI framework is already running.
`configure_subplots` now needs to import `pyplot` (because that's how we can spin up a new figure as needed), but when relying on embedding we could well reach that point with an already running interactive framework, pyplot never imported, and an incompatible rcParams["backend"] (which had not been read yet). For example, run `examples/user_interfaces/embedding_in_tk_sgskip.py` with a non-tk backend set in your matplotlibrc: clicking on the the configure_subplots button triggers a "cannot load backend 'foo' which requires the 'foo' interactive framework, as 'bar' is currently running". Instead, use a helper to safely import pyplot when another interactive framework may already be running. The list of frameworks that `_get_running_interactive_framework` returns is fixed, so we can just hardcode the mapping. (We are going to ignore the user-set `rcParams["backend"]` anyways.)
1 parent ce6ac2d commit e7bab33

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)