Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Matplotlib uses a backend to render the plot. Some backends are "GUI backends", meaning that they can render into a window that displays on your screen. Others are "non-GUI backends" which can only...
Answer
#1: Initial revision
Matplotlib uses a *backend* to render the plot. Some backends are "GUI backends", meaning that they can render into a window that displays on your screen. Others are "non-GUI backends" which can only save the plot into an image file. Matplotlib doesn't come with any GUI backends except for `TkAgg`, which uses Tkinter to display the window. But if [tkinter is missing](https://software.codidact.com/posts/291791) then this won't work. In these cases, Matplotlib will pre-configure itself to use a plain, non-GUI backend just called `agg`. You can tell Matplotlib which backend to use by calling `matplotlib.use` before importing `matplotlib.pyplot`: ``` import matplotlib matplotlib.use('TkAgg') # for the Tkinter backend, for example import matplotlib.pyplot as plt ``` However, this will fail with an `ImportError` or `ModuleNotFoundError` if the named backend isn't available. If you don't actually need to show the plot on screen, the `agg` backend works just fine: use `.savefig()` (providing a filename) instead of `.show()`. You [can also](https://matplotlib.org/stable/install/index.html) switch to the `pdf`, `ps` or `svg` backends to write files in those formats, instead of an image file. Support for many backends can be installed via Pip - for example, `pip install pyqt5` will enable the `Qt5Agg` backend. <section class="notice is-danger"> However, Tkinter [is special because it's supposed to be part of the standard library](https://software.codidact.com/posts/291791). **Do not try to use Pip to install Tkinter support; it will not work and you will install something that may be useless or even harmful.** </section> See also the [Matplotlib documentation for optional dependencies](https://matplotlib.org/stable/install/dependencies.html#optional).