【PHP】jpGraphを使ったグラフの出力
PHPを使ってグラフをリアルタイムに出力する。
①ライブラリをダウンロードし、展開しておく
※サンプルは消しても構わないが、内部でインクルードしているのでそれ以外のファイルもすべて展開しておく
http://jpgraph.net/jpgraph.net
②フォントを展開しておく
フォントはお任せ。IPAフォントでも構わない。
osdn.jp
デフォルトは
/usr/share/fonts/truetype/または
C:\Windows\fonts\
変更するのであれば、展開したライブラリの中の
jpg-config.inc.phpファイル
if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { define('TTF_DIR','/usr/home/xxxxxxx/fonts/'); define('MBTTF_DIR','/usr/home/xxxxxxx/fonts/'); }
※上記の例では、Xampp等のWin環境とレンタルサーバ等のLinux環境で読み込む場所を変えている
③呼び出し元ファイルの制作
グラフ作成のPHPファイルそのものが画像のような扱いになる
呼び出し元では
<img src="graph.php">
④グラフの作成
タイトル等で日本語を扱うときは注意が必要
渡す文字の文字コードはUTF-8以外でないといけない
レンタルサーバによっては文字化けしたりしなかったり。
//サーバでは、タイトル等で渡す文字はUTF-8以外にしないといけないのでエンコード function con($arg1){ if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { return(mb_convert_encoding($arg1, 'SJIS')); } else { return($arg1); } }
グラフの実体は
// Some data $databary=array($cnt1, $cnt2); // New graph with a drop shadow $graph = new Graph(400,200); $graph->SetShadow(); // Use a "text" X-scale $graph->SetScale("textint"); // Set title and subtitle $graph->title->Set(con("アンケート結果")); $graph->title->SetFont(FF_GOTHIC,FS_NORMAL,20); $graph->yaxis->title->Set(con("票数")); $graph->yaxis->title->SetFont(FF_GOTHIC,FS_NORMAL,10); // Create the bar plot $b1 = new BarPlot($databary); // Setup values $b1->value->Show(); $b1->value->SetFormat('%d'); $b1->value->SetFont(FF_FONT1,FS_BOLD); // Center the values in the bar $b1->SetValuePos('center'); $graph->xaxis->SetFont(FF_GOTHIC,FS_NORMAL,10); $graph->xaxis->SetTickLabels(array(con("B案"),con("B案"))); // The order the plots are added determines who's ontop $graph->Add($b1); // Finally output the image $graph->Stroke();
詳細な解説は↓が詳しい
www.phpbook.jp