It is first worth reading about backends in the matplotlib
Usage Guide.
Running
$ python with_gui.py
Interactive mode: False
matplotlib backend: TkAgg
will run load and show the GUI without stopping and then close it when the script finishes. Running
$ python -i with_gui.py
will keep the REPL running after the script executes and allow for further interaction and updating of the GUI.
GUIs can be avoided by not using the GUI compatible matplotlib.pyplot
APIs and using the matplotlib.figure.Figure
APIs instead.
$ python without_gui.py
Interactive mode: False
matplotlib backend: TkAgg
Traceback (most recent call last):
File "without_gui.py", line 17, in <module>
fig.show() # Errors as no GUI available
File "/home/feickert/.pyenv/versions/base/lib/python3.8/site-packages/matplotlib/figure.py", line 407, in show
raise AttributeError(
AttributeError: Figure.show works only for figures managed by pyplot, normally created by pyplot.figure()
Or, as recommended by Thomas Caswell, set a non-GUI backend so that the GUI frameworks aren't even imported.
$ python nongui_backend.py
Interactive mode: False
matplotlib backend: agg
nongui_backend.py:20: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
fig.show() # Errors as no GUI possible