How to call gnuplot from CLI and save the output graph to the image file?
You don't have to redirect the output from gnuplot into an image file; you can set that inside the gnuplot script itself:
set terminal png
set output 'image.png'
If you want to have a variable output name, one simple way to do that in bash is to wrap the gnuplot commands thus:
#!/bin/bash
echo "set terminal png
set output '$1'
plot 'data.dat'" | gnuplot
This way you can run the bash script with an argument for the output file name:
./plotscript.sh image.png
Simply putting the following line will make gnuplot to return png-format bytecode. Thus, you can redirect the output to a png-file.
set terminal png
When your batch file runs gnuplot only (with the script) and does nothing else, then you can combine the batch file with the gnuplot script:
@echo off & call gnuplot -e "echo='#';set macros" "%~f0" & goto :eof
set terminal png
set output 'image.png'
...
Save this with .cmd extension.
The advantages of this is that:
- you have only 1 file instead of two
- that file is runnable from Explorer/TaskScheduler/etc. in a portable way
(no need to associate a new extension with gnuplot.exe)
In other words, this is the Windows "equivalent"(?) of the #!/usr/bin/env gnuplot
solution of Unix
(this is why I find it so comfortable when working with gnuplot scripts under Windows).
(Note: 'call gnuplot' is used to allow for a gnuplot.cmd file somewhere in the PATH -- as opposed to polluting the PATH with the folder of gnuplot.exe (and many other programs).)