How to save a figure remotely with pylab?

I'm trying to generate a figure at a remote computer with the command pylab.savefig. But I got such error:

Unable to access the X Display, is $DISPLAY set properly?

How can I save the figure properly?

38442 次浏览

Try setting the DISPLAY variable to the appropriate value.

Graphics over the network using X11 work by the client (remote) computer having a DISPLAY environment variable that says where to draw the graphics. Typically it would be something like mydesktop.example.com:0.0 - then when an X11 program tries to draw something, it gets whizzed over the network to mydesktop.example.com, which is the machine you are sitting in front of (the X server) and up it pops.

Now, if the machine in front of you is Windows, then you'll need to get an X server from somewhere - cygwin/X11 or commercial eXceed will do nicely.

You also need to make sure security is handled - you cant just have anyone writing to your screen over the network.

How are you connecting to the remote machine? Because if you are going from a Linux box to another Linux box with ssh then the simple solution is probably 'Use ssh -X foo.example.com' to connect - this pipes the X11 connection over a local socket.

So, if ssh -X isnt the answer, can we have some more info on the operating systems involved please?

By default, matplotlib will use something like the TkAgg backend. This requires an X-server to be running.

While you can just use X-forwarding, there will be a noticeable lag as matplotlib tries to connect with the remote X-server. If you don't need to interact with the plot, it's often nicer to speed things up by avoiding an X-connection entirely.

If you want to make a plot without needing an X-server at all, use the Agg backend instead.

E.g. do something like this:

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


fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png')

If you want this to be the default behavior, you can modify your matplotlibrc file to use the Agg backend by default.

See this article for more information.