virtualenv: Matplotlib fails inside virtualenv

Matplotlib doesn’t show the figure window from within a virtualenv. I’ve tried many combinations (e.g. intalling using pip, using easy_install, compiling from source, using --system-site-packages, different versions, etc.) with no luck. The test that makes me think is a virtualenv issue is that if I try to use my working system-wide matplotlib from virtualenv, I don’t see a figure. In other words, if I run this:

[~]$ python plotTest.py

it works ok (shows the figure). Then, if I create a virtualenv with --system-site-packages and run the same script, it doesn’t work. That is:

[~]$ virtualenv --system-site-packages vEnv
[~]$ source vEnv/bin/activate
(vEnv)[~]$ python plotTest.py

fails (it hangs and doesn’t even return). I need to kill the process. Btw, the plotTest.py if the following:

import matplotlib
import matplotlib.pyplot as plt

print "Backend: ", matplotlib.rcParams['backend']

plt.plot([1,2,1])
plt.show()

FWIW, in both cases I do see the line printing MacOSX as the backend.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 2
  • Comments: 39

Most upvoted comments

I’m more inclined at this point to blame matplotlib to be honest. I’m not even using virtualenv right now and I’m seeing all the same issues after trying all their hacks to make it work with virtualenv.

Finally I solved this problem by this article, http://www.wirywolf.com/2016/01/pyplot-in-jupyter-inside-pyenv-on-el-capitan.html

It works!!

There is someone that use also virtualenvwrapper?

In that case I used a suggested workaround that matplotlib has in its FAQ that is create the environment with pyvenv (of course if you need Python 3). The interesting thing is that if you create the environment with pyvenv inside the WORKON_HOME folder virtualenvwrapper still works fine and I can use matplotlib without problem inside that environment.

Hope this thing can help and that I’m not off topic.

It works fine with pyenv virtualenv combined with pyenv provided that you remember to build the pyenv python version as a framework build as documented here It also works with venv instead of virtualenv for python3 which I think is what was meant by “pyvenv” above.

Because matplotlib sets the backend at import time of pyplot. If you want a different backend I suggest selecting it before importing it or configuring another default backend.

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

Just for sake of documentation, http://wiki.wxpython.org/wxPythonVirtualenvOnMac solves this issue by calling systemwide python with a PYTHONHOME environment variable.