How to ensure matplotlib in a Python 3 virtualenv uses the TkAgg backend?

6,420

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())'
Share:
6,420

Related videos on Youtube

edwinksl
Author by

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, 2022

Comments

  • edwinksl
    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 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?