I am using Ubuntu 16.04 with Python 3. Using APT to install python3-matplotlib and then printing the matplotlib backend gives TKAgg, which is expected because Ubuntu has 16.04 has python3-tk installed. This is done by running:

sudo apt install python3-matplotlib
python3 -c 'import matplotlib as mpl; print(mpl.get_backend())'

However, if I create a virtualenv for Python 3, activate the virtualenv, install matplotlib using pip and then print the matplotlib backend, I get agg instead. This is done by running:

virtualenv venv -p python3
source venv/bin/activate
pip install matplotlib
python -c 'import matplotlib as mpl; print(mpl.get_backend())'

It looks like matplotlib in the virtualenv is not aware of the presence of the TkAgg backend in the system, which is not surprising given the virtualenv does not see the system site packages when the --system-site-packages option is not used. Forcing matplotlib to use the TkAgg backend and then importing matplotlib.pyplot gives ImportError: cannot import name '_tkagg' as expected. This is done by running:

python -c "import matplotlib as mpl; mpl.use('TkAgg'); import matplotlib.pyplot as plt"

Therefore, how do I ensure that matplotlib in a Python 3 virtualenv uses the TkAgg backend?


You need to install the tk-dev package by running:

sudo apt install tk-dev

Then, reinstall matplotlib in the virtualenv by running:

pip --no-cache-dir install -U --force-reinstall matplotlib

Verify the TkAgg backend is used by checking if the following code returns TkAgg:

python -c 'import matplotlib as mpl; print(mpl.get_backend())'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.