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.
Why won't Matplotlib show me a plot?
I installed Matplotlib and tried a simple demo, but I got a warning message and no plot showed up:
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3],[4,5,6])
[<matplotlib.lines.Line2D object at ...>]
>>> plt.show()
<stdin>:1: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
What does this mean, and how can I show the plot?
1 answer
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 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 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.
However, Tkinter is special because it's supposed to be part of the standard library. 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.
See also the Matplotlib documentation for optional dependencies.
0 comment threads