Testing matplotlib-based plots in Travis CI

You can solve this without explicitly setting display by using the "agg" backend in matplotlib. This is necessary anyway, in my experience, in order to ensure consistency of the generated images. Just make sure you

 matplotlib.use('agg')

before you import pyplot or pylab. I've explained more here.


Update: as per @matt-pitkin comment, the method has been updated. In case an Ubuntu Xenial container is used, the preferred method to enable xvfb is through a Travis service:

services:
- xvfb

However, if an Ubuntu Trusty container is used, my original answer (below) remains relevant. I also recommend reading the answer by @david-ketcheson, which has a more specific solution to the original question.


In order to set the DISPLAY variable inside Travis, you need to emulate a display from inside their VM. They teach how to do it using xvfbby adding the following to the before_script of yout .travis.yml file:

before_script: # configure a headless display to test plot generation
- "export DISPLAY=:99.0"
- "sh -e /etc/init.d/xvfb start"
- sleep 3 # give xvfb some time to start

In order for Travis not to get hung up on the plots, simply don't call pyplot.show(). If you are testing too many plots, make sure to call pyplot.close() or it will complain about having too many open images.