Calling gnuplot from python

Viewed 47722

I've a python script that after some computing will generate two data files formatted as gnuplot input.

How do I 'call' gnuplot from python ?

I want to send the following python string as input to gnuplot:

"plot '%s' with lines, '%s' with points;" % (eout,nout)

where 'eout' and 'nout' are the two filenames.

PS: I prefer not to use additional python modules (eg. gnuplot-py), only the standard API.

Thank You

8 Answers

The subprocess module lets you call other programs:

import subprocess
plot = subprocess.Popen(['gnuplot'], stdin=subprocess.PIPE)
plot.communicate("plot '%s' with lines, '%s' with points;" % (eout,nout))

Subprocess is explained very clearly on Doug Hellemann's Python Module of the Week

This works well:

import subprocess
proc = subprocess.Popen(['gnuplot','-p'], 
                        shell=True,
                        stdin=subprocess.PIPE,
                        )
proc.stdin.write('set xrange [0:10]; set yrange [-2:2]\n')
proc.stdin.write('plot sin(x)\n')
proc.stdin.write('quit\n') #close the gnuplot window
proc.stdin.flush()

One could also use 'communicate' but the plot window closes immediately unless a gnuplot pause command is used

proc.communicate("""
set xrange [0:10]; set yrange [-2:2]
plot sin(x)
pause 4
""")

A simple approach might be to just write a third file containing your gnuplot commands and then tell Python to execute gnuplot with that file. Say you write

"plot '%s' with lines, '%s' with points;" % (eout,nout)

to a file called tmp.gp. Then you can use

from os import system, remove
system('gnuplot -persist tmp.gp')
remove('tmp.gp')
Related