Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib not working for LInux. Cannot load backend 'TkAgg'

Trying to use Matplotlib on Linux, but I keep getting this error:

ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running

I am using a virtual environment on OS: Linux 18.04 LTS. Python version: 3.6

I have tried many solutions other posts have suggested:

sudo apt-get install tk-dev libpng-dev libffi-dev dvipng texlive-latex-base
pip uninstall matplotlib
pip --no-cache-dir install matplotlib

I have tried fiddling with the python script where matplotlib is used:

#TOP OF FILE
import matplotlib
matplotlib.use('Agg') # or 'TkAgg', or removing the line altogether
import matplotlib.pyplot as plt
...

Running python to see what backend is being used:

import matplotlib
matplotlib.get_backend()   # -> 'agg'

Any ideas? Thank you

like image 662
Edwarric Avatar asked Apr 17 '19 16:04

Edwarric


People also ask

What backend is matplotlib using?

Matplotlib is a plotting library. It relies on some backend to actually render the plots. The default backend is the agg backend.

What is TkAgg?

With the TkAgg backend, which uses the Tkinter user interface toolkit, you can use matplotlib from an arbitrary non-gui python shell. Just set your backend : TkAgg and interactive : True in your matplotlibrc file (see Customizing matplotlib) and fire up python.

How do I tell what version of matplotlib I have?

Once you've successfully installed matplotlib, you can use the following command to display the matplotlib version in your environment: pip show matplotlib Name: matplotlib Version: 3.1.


1 Answers

I had a similar issue using iPython on macOS getting the error message

matplotlib.use('TkAgg') 

ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'macosx' is currently running

I was able to show my plots using

matplotlib.use('WebAgg') # shows in the browser

or

matplotlib.use('MacOSX') # shows on the desktop

To get list of all available backends I typed:

matplotlib.use('?')
...

ValueError: Unrecognized backend string '?': valid strings are ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']

See also What is a backend?

like image 70
user2314737 Avatar answered Sep 20 '22 11:09

user2314737