Run matplotlib in a virtualenv on Ubuntu 16.04 with different backends

When trying to use matplotlib in a virtualenv under Ubuntu 16.04, I came across an issue that matplotlib does not automatically install or connect to any backend, therefore figures do not show up when plt.plot() is called. To fix it, I had to install Tk with Tkinter and build matplotlib from sources. You can get it working with different backends as well. See Working with Matplotlib in Virtual environments and What is a backend? to learn how backends work, and feel free to consult Matplotlib figures not showing up or displaying that provides the solution I reproduce here in a shorter form.

Solution for TkAgg

Install Tk (C++ library) and Tkinter (python wrapper around it)

sudo apt-get install tk-dev python-tk python3-tk

Create a project and a virtual environment, e.g. like this

mkdir ~/test_project
cd ~/test_project
virtualenv venv

Activate your venv and install numpy and scipy

source venv/bin/activate
pip install numpy scipy

Clone matplotlib repo and configure the installer

git clone https://github.com/matplotlib/matplotlib.git
cd matplotlib
python setup.py config

Read the output of the previous command and make sure that TkAgg was found. After that, install matplotlib

python setup.py install

Now, check that the backend works by executing the following commands in the python interpreter

>>> import matplotlib.pyplot as plt
>>> plt.get_backend()

which should output u'TkAgg'. If that is the case, you may plot a test figure

plt.plot([1, 4, 9])
plt.show()

It should open a figure in a new window.

Solution for Qt5

If you want to use another backend—Qt5, for example,—you will first need to install the required packages

sudo apt-get install qt5-default pyqt5-dev python-pyqt5 python3-pyqt5

and then create symlinks for PyQt and Sip from your global python library to the virtual environment. To do that, navigate to your local site-packages

cd ~/test_project/venv/lib/python2.7/site-packages

create a symlink to Qt5

ln -s /usr/lib/python2.7/dist-packages/PyQt5

and symlinks to Sip files

find /usr/lib/python2.7/dist-packages/ -name sip* -exec ln -s {} . \;

Now you can configure and install matplotlib as described in the section about TkAgg, and it should work.