Home

Algorithmic Advent: 05 – Inserting gnuplot images

Published on 5 Dec 2010. Tagged with php, algorithmicadvent.

Here's an example on how to generate a gnuplot graph and integrate it as an image into an HTML document on the fly without using any additional output files.

$gnuplotCommands = <<<EOT
set term png
set output           # output to stdout

set   autoscale      # scale axes automatically
unset log            # remove any log-scaling
unset label          # remove any previous labels
set xtic auto        # set xtics automatically
set ytic auto        # set ytics automatically
set xr [0:7]
set yr [-1.5:1.5]
plot sin(x)
EOT;

$output    = array();
$errorCode = 0;

exec('echo "' . $gnuplotCommands . '" | gnuplot | base64', $output, $errorCode);

if ($errorCode !== 0) {
    echo 'Oops, something went wrong. Return code: ' . $errorCode;
    exit;
}

$imgData = implode("\n", $output);

echo '<img src="data:image/png;base64,' . $imgData . '">';