Import Matplotlib without display

I am trying to run a python script on my Linux server and create and save some graphics. I installed ipythonboth pylaband matplotlib, but then when I run my script, I get this error:

Traceback (most recent call last):
  File "/root/dining_hall_graph.py", line 14, in <module>
    from pylab import * 
  File "/usr/lib64/python2.7/site-packages/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/usr/lib64/python2.7/site-packages/matplotlib/pylab.py", line 265, in <module>
    from matplotlib.pyplot import *
  File "/usr/lib64/python2.7/site-packages/matplotlib/pyplot.py", line 97, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
    globals(),locals(),[backend_name])
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
    from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
  File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_gtk.py", line 13, in <module>
    import gtk; gdk = gtk.gdk
  File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
    _init()
  File "/usr/lib64/python2.7/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
    _gtk.init_check()
RuntimeError: could not open display

In this line from pylab import *

How can I build and save graphs in my python script that I run on my Linux server?

thanks

+4
source share
1 answer

You should almost never use from pylab import *.

Import what you need from numpy, scipyand matplotlib.

On machines without a display, you need to use the backend agg:

, MPLBACKEND

$ MPLBACKEND=Agg python plot.py

matplotlib matplotlib.pyplot:

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt

plt.plot([1, 2, 1])
plt.savefig('test.pdf')

, matplotlibrc $HOME/.config/matplotlib :

backend: Agg

X-Forwarding, -:

ssh -X user@server
+12

Source: https://habr.com/ru/post/1617315/


All Articles