Matplotlib: display plot on a remote machine

I have a python code doing some calculation on a remote machine, named A. I connect on A via ssh from a machine named B. Is there a way to display the figure on machine B?


Sure, you can enable X11 forwarding. Usually this is done by passing the -X or -Y option to ssh when you connect to the remote computer

ssh -X computerA

Note that the SSH daemon on computer A will also have to be configured to enable X11 forwarding. This is done by putting

X11Forwarding yes

in computer A's sshd_config configuration file.

If computer A's SSH daemon does not have X11 forwarding enabled, you can always have Python write the result of the calculation to a text file, download it to computer B, and use Matplotlib locally.


If you use matplotlib on Mac OS X on the remote machine (B), you must first make sure that you use one of the X11-based display back-ends, since the native Mac OS X back-end cannot export its plots to another display. Selecting a back-end can be achieved with

import matplotlib
matplotlib.use('GTK')  # Or any other X11 back-end

The list of supported back-ends can be obtained by giving use() an incorrect back-end name: matplotlib then prints an error message listing the possible back-ends.

ssh X11 forwarding can then be used to display matplotlib plots.


The following worked for me using Mac OS X on the local machine (machine B) and ubuntu on the remote (machine A).

You need X11 server installed on your local machine to do this.

If you're running a recent version of Mac OSX (OS X Mountain Lion or newer), it would NOT have come with X11 pre-installed (see http://support.apple.com/kb/ht5293). Check if you have X11 by opening up Mac terminal, and run command xterm. If an X11 window opens up, you're all set. If it says command not found, then go to http://xquartz.macosforge.org/landing/ and install X11 server. Then logout and log back in to your mac.

After you log back in, try to run xterm command again. It should open up X11 window. At this point your $DISPLAY variable should also be set correctly. If it's not set, make sure you've logged in/out since installing X11 from XQuartz.

echo $DISPLAY
/tmp/launch-I9I3aI/org.macosforge.xquartz:0

Then from your local machine, use ssh -X to remote into remote machine A:

ssh -X user@machineA

Then on the remote machine:

python
>>> import matplotlib
>>> matplotlib.use('GTKAgg')  #I had to use GTKAgg for this to work, GTK threw errors
>>> import matplotlib.pyplot as plt  #...  and now do whatever you need...

Make sure you call matplotlib.use BEFORE importing anything else from matplotlib (e.g. matplotlib.pyplot)

Other useful troubleshooting tips on using ssh -X : http://oroborosx.sourceforge.net/remotex.html#usessh