Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gnuplot scripts: use a path relative to file rather than execution directory?

Tags:

gnuplot

I'm generating a Gnuplot script in the same folder as a .dat file that I need to plot, and I'd like it to work even if it's called from a different directory. Unfortunately it seems like relative paths work from the directory within which Gnuplot is called, not the one in which the script file is. So for example:

gnuplot folder/script.gp

will fail if the file is folder/data.dat and the script says plot "data.dat". Is there any way to get around this? Like a variable in Gnuplot holding the location of the currently executed script?

like image 517
Okarin Avatar asked May 31 '26 02:05

Okarin


1 Answers

Your separator between directory and filename is /, so I assume you are on Linux. Here the following works:

  • If gnuplot is started with a script for execution, then there is a variable ARG0 which contains the complete script name as it was specified on the command line.
  • Via a system call we can send this script name back to the shell which has a dirname command for extracting the directory part of the script name.
  • Now we can use the gnuplot internal string functions for building file paths, especially the . which concatenates two strings.

You said you have a gnuplot script folder/script.gp and a data file folder/data.txt, then the script should contain something like that:

print ARG0       # just for debugging
working_directory = system("dirname ".ARG0)."/"
datafile = working_directory."data.dat"
outputfile = working_directory."graph.png"

print datafile   # just for debugging
print outputfile # just for debugging

set terminal pngcairo
set output outputfile
plot datafile w l

It also works if you are within "folder", then dirname returns . and the resulting datafile will be ./data.dat. I have not checked 'special' directory names containing spaces, ... I would not expect it to work.

Tested with gnuplot 5.0.5 on Debian 9.6, gnuplot uses the sh shell for system. I have not searched for a Windows solution.

like image 97
maij Avatar answered Jun 02 '26 21:06

maij