Calling gnuplot from python

前端 未结 8 636
清酒与你
清酒与你 2020-12-04 18:34

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 se

8条回答
  •  时光说笑
    2020-12-04 18:59

    I was trying to do something similar, but additionally I wanted to feed data from within python and output the graph file as a variable (so neither the data nor the graph are actual files). This is what I came up with:

    #! /usr/bin/env python
    
    import subprocess
    from sys import stdout, stderr
    from os import linesep as nl
    
    def gnuplot_ExecuteCommands(commands, data):
        args = ["gnuplot", "-e", (";".join([str(c) for c in commands]))]
        program = subprocess.Popen(\
            args, \
            stdin=subprocess.PIPE, \
            stdout=subprocess.PIPE, \
            stderr=subprocess.PIPE, \
            )
        for line in data:
            program.stdin.write(str(line)+nl)
        return program
    
    def gnuplot_GifTest():
        commands = [\
            "set datafile separator ','",\
            "set terminal gif",\
            "set output",\
            "plot '-' using 1:2 with linespoints, '' using 1:2 with linespoints",\
            ]
        data = [\
            "1,1",\
            "2,2",\
            "3,5",\
            "4,2",\
            "5,1",\
            "e",\
            "1,5",\
            "2,4",\
            "3,1",\
            "4,4",\
            "5,5",\
            "e",\
            ]
        return (commands, data)
    
    if __name__=="__main__":
        (commands, data) = gnuplot_GifTest()
        plotProg = gnuplot_ExecuteCommands(commands, data)
        (out, err) = (plotProg.stdout, plotProg.stderr)
        stdout.write(out.read())
    

    That script dumps the graph to stdout as the last step in main. The equivalent command line (where the graph is piped to 'out.gif') would be:

    gnuplot -e "set datafile separator ','; set terminal gif; set output; plot '-' using 1:2 with linespoints, '' using 1:2 with linespoints" > out.gif
    1,1
    2,2
    3,5
    4,2
    5,1
    e
    1,5
    2,4
    3,1
    4,4
    5,5
    e
    

提交回复
热议问题