00__00__00
00__00__00

Reputation: 5347

plotting without display: correct use of matplotlib.use()

I need to plot on a system that doesn't have a display. If I plot naively using matplotlib.pyplot.plt I get

    raise RuntimeError('Invalid DISPLAY variable')

I have found out that matplotlib.use() can be used in this context. Now I have a main file:

 **main.py:**

 import my_module
 ....
 # do stuff

 **my_module.py:**

 import matplotlib
 matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or     pylab!
 import matplotlib.pyplot as plt    
 # do stuff
 plt.plot(data)

When running main.py I get:

UserWarning: 
This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab,     matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

But to me it seems I am calling it before importing pyplot. Later I get this runtime error

File "[OMIT]/python2.7/site-packages/matplotlib    /backends/backend_qt5.py", line 144, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable

So what is the right way to change matplotlib backend?I do not need a display, but I need to be able to store the figures using plt.savefig

Upvotes: 3

Views: 2447

Answers (2)

00__00__00
00__00__00

Reputation: 5347

In the end, I have solved by:

**main.py***
import matplotlib
matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab!
import my_module

as the many subimports in my_module made impossible to identify where pyplot was first imported. Also I have done:

import my_module

instead of that I was doing ealier.

from my_module import my_func

Upvotes: 1

Reblochon Masque
Reblochon Masque

Reputation: 36702

You need to

import matplotlib
matplotlib.use('Agg')

on a fresh kernel, especially if you are using ipython, before importing matplotlib.pyplot

I'd be curious, and happy, to know if there are ways to clear/flush the ipython kernel, without having to restart it; so far, my quest has not been successful.

Upvotes: 1

Related Questions