Import Matplotlib without a display
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
Or you could enable X-Forwarding, so the plots will pop up on your host machine:
ssh -X user@server
Comments
-
spen123 almost 2 years
I am trying to run a python script on my linux server and make and save some plots. I have installed
ipython
andpylab
andmatplotlib
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
-
spen123 over 8 yearsgreat, is it also possible to see the plot in the terminal?
-
MaxNoe over 8 yearsWhat do you mean? Ascii-art?
-
MaxNoe over 8 yearsnot that I know of. What is wrong with x-forwarding?