Search code examples
gnuplot

Show graph on display and save it to file simultaneously in gnuplot


How can I save graph in to file and also print it to display? I've tried:

#!/usr/bin/gnuplot -p

date=system("date +%F_%T | sed 's/:/-/g'")

set term png
set output date.".png"

set term x11
set out

plot sin(x)

PS: Is there a possibility to save the graph which is displayed in gnuplot window? I've noticed that there is copy to clipboard button but no save.


Solution

  • If you want to send a plot both to a file and to an interactive terminal like x11 or wxt you have the replot after you changed the terminal

    set terminal png
    set output 'file.png'
    
    plot sin(x)
    
    set terminal x11
    set output
    replot
    

    If you don't want to set the x11 terminal explicitely, but rather use the default terminal, whatever it is, you can use the special terminals push and pop so save and restore a terminal:

    set terminal push
    set terminal pngcairo
    set output 'file.png'
    plot sin(x)
    set terminal pop
    set output
    replot
    

    To make this more transparent and save any image after you plotted it to an interactive terminal you could define a gnuplot script export.gp which you can then call and give the output file name as parameter.

    The export.gp script is

    set terminal push
    set terminal pngcairo
    set output '$0'
    
    replot
    set output
    set terminal pop
    

    which you can then use as

    plot sin(x)
    call 'export.gp' 'test.png'
    

    Note, however, that the exported file and the plot shown in the interactive window will be different, but if you use wxt as interactive and pngcairo or pdfcairo as output terminals, the chances are quite high, that displayed and exported images are very similar.

    With gnuplot 5.0 the qt and wxt terminals offer an "Export" button to save exactly the image shown in the window as svg, pdf or png files. Unfortunately, this functionality cannot yet be invoked from a script, i.e. there is no export command.