Wesley Pennington

  • About
  • Feed
  • Contact

Throw Your Hands in the Air(er): how to run matplotlib in a virtual environment

June 02, 2016 by Wesley Pennington

[Technical post, but good tunes. Something for everyone.]

So I came across an issue running matplotlib in a virtual environment. Given that there has been an open issue on this since 2011, it appears I am not the only one who came across this bug.

Depending on where you look, you might get a straightforward solution to this. More likely, however, you will come across documentation telling you that matplotlib has to run on a framework build of Python and that your only options are one of several pretty cumbersome solutions.

BUT I was able to work around it with another method that is not referenced in the FAQ documentation on this issue. It works well and is easy to implement, so I thought I'd document it here and channel some OutKast to celebrate pretty graphs and separate dependencies. 🙌

(Note: I've also documented in the issue tracker for the project.)

You can change the matplotlib backend to get matplotlib to work in a virtual environment:

There are (at least) three solutions I've used, with some additional methods included below. Each outlined here should to the same thing with a slightly different approach:

If you already installed matplotlib using pip on your virtual environment, you can...

1. Add a new matplotlibrc file for your virtual environment
For example, in your virtual environment run:

$ cd ~/.matplotlib
$ nano matplotlibrc #to create file using nano

Write backend: TkAgg in the file and save upon exit. You should be good to go.

*OR*

2. Edit the matplotlibrc file referenced by your virtual environment
In your virtual environment, open a python shell and run:

import matplotlib
matplotlib.matplotlib_fname()
'/home/foo/.config/matplotlib/matplotlibrc'

**NOTE: if you get a syntax error in your virtual environment, you might need to simply run:
import matplotlib
matplotlib.matplotlib_fname() 

This displays the matplotlibrc file referenced by the matplotlib package in your virtual environment. Follow the path and open the matplotlibrc file.

Edit the file's backend tag to read backend: TkAgg and save.

*OR*

3. You can define the backend upon import of matplotlib if you don't want to change the backend in the script itself:

import matplotlib
matplotlib.use('TkAgg')


(see sources below for further explanation and additional methods)

Sources:
[1] http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
[2] http://matplotlib.org/users/customizing.html#customizing-matplotlib
[3] http://stackoverflow.com/questions/4130355/python-matplotlib-framework-under-macosx
[4] http://stackoverflow.com/questions/29433824/unable-to-import-matplotlib-pyplot-as-plt-in-virtualenv

June 02, 2016 /Wesley Pennington
technical, dev
  • Newer
  • Older

©2017 Wesley Pennington