Import Matplotlib without a display

2020-06-04 03:37发布

问题:

I am trying to run a python script on my linux server and make and save some plots. I have installed ipython and pylab and 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

On this line from pylab import *

How can I plot and save graphs in my python script that I am running on my linux server?

Thanks

回答1:

You should almost never use from pylab import *.

Import what you need from numpy, scipy and matplotlib.

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

You can achieve this by specifying the environmental variable MPLBACKEND

$ MPLBACKEND=Agg python plot.py

Or by importing matplotlib before importing matplotlib.pyplot:

import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt

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

To make this the default, you can create a file called matplotlibrc in the current directory or in $HOME/.config/matplotlib with the following content:

backend: Agg

Ot you could enable X-Forwarding, so the plots will pop up on your host machine:

ssh -X user@server