How to ensure 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())'
Related videos on Youtube
edwinksl
Research scientist at Institute for Infocomm Research. PhD and MS from MIT and BS from Stanford, all in chemical engineering. Interested in emerging technologies, batteries, ML and AI. Email: [email protected]
Updated on September 18, 2022Comments
-
edwinksl over 1 year
I am using Ubuntu 16.04 with Python 3. Using APT to install
python3-matplotlib
and then printing the matplotlib backend givesTKAgg
, which is expected because Ubuntu has 16.04 haspython3-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
usingpip
and then print the matplotlib backend, I getagg
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 theTkAgg
backend and then importingmatplotlib.pyplot
givesImportError: 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?