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

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.


A good answer was also given in gnuplot - How can I save a graphics file of a plot that is the same as I designed it in xterminal?. For x11 terminal one can use

system("xwd -id ".GPVAL_TERM_WINDOWID." | convert xwd:- screenshot.png")

It can be also wrapped into a short cut

bind "Ctrl-c" 'system("xwd -id ".GPVAL_TERM_WINDOWID." | convert xwd:- png:- | xclip -sel clip -t image/png")'

So you plot the image

set term x11
plot sin(x)/x

and then press Ctrl+c in the plot window. Just here, I pasted the image with Ctrl+v:

Unfortunately, it does not work for qt or wxt (GPVAL_TERM_WINDOWID is associated to x11). They have clipboard buttons, but snapshots are not scriptable.

Tags:

Gnuplot