Skip to content Skip to sidebar Skip to footer

Passing Python Functions To Gnuplot

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 translate it

Solution 1:

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 24.0:~$ python test.py 39.0:~$ python test.py 416.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)

enter image description here

Post a Comment for "Passing Python Functions To Gnuplot"