Skip to content

Instantly share code, notes, and snippets.

@ethanpil
Created December 7, 2022 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanpil/18b88afd90a90718dcd444531b2ab061 to your computer and use it in GitHub Desktop.
Save ethanpil/18b88afd90a90718dcd444531b2ab061 to your computer and use it in GitHub Desktop.
gnuplot PNG from PHP
$gnuplotcommands = '
set terminal png size 640x480
set grid
set autoscale
unset log
unset label
set xtics 0,1,23
set ytic auto
set title "Sample Chart Data"
set xlabel "Date"
set ylabel "Rainfall (in)"
set key left top
set boxwidth 0.75
$PLOTDATA << EOD
#Day Rainfall
1 0
2 2
3 4
4 3
5 0
6 0
EOD
plot $PLOTDATA using 2:xtic(1) with histogram fillstyle solid fillcolor "green" title "Rainfall", \
$PLOTDATA using 0:($2 > 0 ? $2 : NaN):2 with labels notitle offset 0, char 1, \
';
$gnuplotcommandsArray = preg_split("/\r\n|\n|\r/", $gnuplotcommands);
//openPipe()
$descriptorspec = array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w'),
2 => array('pipe', 'r')
);
$process = proc_open('gnuplot', $descriptorspec, $pipes);
if (!is_resource($process)) {
throw new \Exception('Unable to run GnuPlot');
}
foreach ($gnuplotcommandsArray as $command) {
fwrite($pipes[0], $command . PHP_EOL);
}
// Read data, timeout=100ms
$result = '';
$timeout = 100;
do {
stream_set_blocking($pipes[1], false);
$data = fread($pipes[1], 128);
$result .= $data;
usleep(5000);
$timeout-=5;
} while ($timeout>0 || $data);
header('Content-type: image/png');
echo $result;
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment