Home > Archive > 2010 > December

Algorithmic Advent: 05 – Inserting gnuplot images

By Marc Ermshaus on Sunday, December 5, 2010 at 11:55 pm.

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 . '">';

Add new comment

Name*:

Please leave the following field empty:

E-Mail:

Website:

Message*:

Please use HTML for formatting. Allowed tags:
<a href="">, <blockquote cite="">, <em>, <ul>, <ol>, <li>, <pre>, <strong>, <![CDATA[ … ]]>

<p> tags will be added automatically.

All comments are published under the CC BY-SA license.