phpの折れ線グラフを作る
- 目標:office 2007 excelのグラフやGoogle Chartのような綺麗なものを作りたい
まずは、
単純なグラフを作成
<?php $data = array(180,5,160,134,134,210); $canvasWidth = 300; $canvasHeight = 300; $graphAreaMargin = 20; $graphAreaPadding = 20; $img = imagecreatetruecolor($canvasWidth, $canvasHeight); // カンバスの背景 imagefilledrectangle($img, 0, 0, $canvasWidth , $canvasHeight , imagecolorallocate($img, 225, 225, 225)); //imageantialias($img, true);//アンチエイリアスの有効 $axisLineColor = imagecolorallocate($img,86,86,86);//軸の線の色 $lineStyleColor = array('r' => 124,'g' => 96,'b' => 160);//red,green,blue $lineColor = imagecolorallocate($img,$lineStyleColor['r'],$lineStyleColor['g'],$lineStyleColor['b']); $lineWeight = 1;//折れ線の太さ @TODO //Y軸のデータの縮尺倍率 (上限 - 下限(x軸) / データの一番高いもの) $yAxisRate = (($canvasHeight - $graphAreaMargin ) - ($graphAreaMargin + $graphAreaPadding)) / max($data); $point = array(); $count = count($data); if($count == 0){return false;} //グラフの間隔 if($count > 1){ $gline = intval(($canvasWidth - $graphAreaMargin * 2 - $graphAreaPadding * 2) / ($count - 1)); } else { $gline = 0; } //データをプロットする座標を求める for($i=0; $i<$count;$i++){ $point[] = array($graphAreaMargin + $graphAreaPadding + $gline * $i, $canvasHeight - $graphAreaMargin - $data[$i] * $yAxisRate); } //折れ線グラフを描画する for($i=0; $i<$count - 1;$i++){ for($j = 0 ;$j<$lineWeight; $j++){//不完全 @TODO imageline ($img , $point[$i][0] + $j, $point[$i][1] , $point[$i + 1][0] + $j , $point[$i + 1][1] , $lineColor ); } } imageline ($img , 20, 280, 20, 20 , $axisLineColor);//Y軸を描画 imageline ($img , 20, 280, 280, 280 , $axisLineColor);//X軸を描画 header("Content-type: image/png"); header("Cache-control: no-cache"); imagepng($img);//PNGで出力 imagedestroy($img);//メモリ解放 ?>
次にやりたいこと
- アンチエイリアスの追加
- 目盛りの追加
- 凡例の追加
アンチエイリアスの追加
ググっていると、
・線形補間
・ブレゼンハムアルゴリズム
・オーバーサンプリング
というのがキーワードらしい。