Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 253
00__00__00 Avatar asked May 27 '26 14:05

00__00__00


1 Answers

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.

like image 142
Reblochon Masque Avatar answered May 30 '26 04:05

Reblochon Masque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!