Search code examples
gnuplot

How to plot all data files in the directory with gnuplot?


How to plot all data files in the directory with gnuplot? I mean that from each data file a figure will be created. Data files have different names. I tried:

j=0;do for [i in system("ls")] { j=j+1; set term png; set output ''.i.'.png' ; p i u 1:2 w lines lc rgb "navy" t ''.i }

which lead to the error: x range is invalid

plot for [fn in system("ls")] fn with lines title ''.i

which lead to the error: internal error : STRING operator applied to undefined or non-STRING variable

This plot all data in one figure

a=system('a=`tempfile`;cat *.dat > $a;echo "$a"')
plot a u 1:2

Solution

  • I expected this to be a frequently asked question with well documented answers, however, I can't find a suitable example right away...

    Edit: you can do it in a "platform-independent" way using gnuplot's variable GPVAL_SYSNAME, which holds the name of the operating system. Furthermore, the user variables DIR for the directory and EXT for file extension are used. If the output files should be in a different directory, e.g. DIR_IN and DIR_OUT could be defined instead of DIR.

    Script:

    ### plot all datafiles in a directory
    reset session
    set term pngcairo
    
    DIR   = 'Test/'     # directory; use '' for current directory
    EXT   = '.dat'      # file extension
    FILES = GPVAL_SYSNAME[1:7] eq 'Windows' ? system(sprintf('dir /B %s*%s',DIR,EXT)) : \
                                              system(sprintf('ls     %s*%s',DIR,EXT))     # Linux/MacOS
    
    myInput(s)  = sprintf('%s%s',DIR,s)
    myOutput(s) = sprintf('%s%s.png',DIR,s[1:strlen(s)-strlen(EXT)])    # replace file extension with .png
    
    do for [FILE in FILES] {
        set output myOutput(FILE)
        plot myInput(FILE) u 1:2 w lines lc "red" title FILE
    }
    set output
    ### end of script