Passing Python functions to Gnuplot

前端 未结 1 1933
我在风中等你
我在风中等你 2021-01-13 20:46

Plotting a Python function in Gnuplot is not straightforward although there are some solutions. For example, one could either cast its values into an array or manually trans

1条回答
  •  Happy的楠姐
    2021-01-13 21:32

    I am not sure if I'm fully answering your question, but you could try executing your python script as a system call within gnuplot passing the argument(s).

    For instance, imagine the simple python script test.py:

    import sys
    
    x=float(sys.argv[1])
    
    print x**2
    

    which will return the square of the argument when called like this from a shell:

    :~$ python test.py 2
    4.0
    :~$ python test.py 3
    9.0
    :~$ python test.py 4
    16.0
    

    Now, within gnuplot, turn this into a function:

    gnuplot> f(x) = real(system(sprintf("python test.py %g", x)))
    gnuplot> print f(1)
    1.0
    gnuplot> print f(2)
    4.0
    gnuplot> print f(3)
    9.0
    gnuplot> print f(4)
    16.0
    

    I added the real() so that the string output from the system call is converted to float. This now allows you to use it as a regular gnuplot function. I don't need to mention this will take a lot longer to execute than just plot x**2:

    f(x) = real(system(sprintf("python test.py %g", x)))
    plot f(x)
    

    0 讨论(0)
提交回复
热议问题