Libchart 是純 PHP 繪圖庫,支援長條圖、折線圖、圓餅圖、水平長條圖,需 GD 擴展支援。
<?php
require "./libchart/classes/libchart.php";
class drawPic {
var $chart;
var $style;
function drawPic($style = "1", $width = "500", $height = "250") {
$this->style = $style;
if ($style == 1) {
$this->chart = new VerticalBarChart($width, $height);
} elseif ($style == 2) {
$this->chart = new LineChart($width, $height);
} elseif ($style == 3) {
$this->chart = new PieChart($width, $height);
} else {
$this->chart = new HorizontalBarChart($width, $height);
}
}
function draw($obj) {
if ($this->style == 1 || $this->style == "1") {
$dataSet = new XYDataSet();
$this->chart->setTitle($obj->title);
foreach ($obj->dataArray as $key => $val) {
$dataSet->addPoint(new Point($key, $val));
}
$this->chart->setDataSet($dataSet);
$this->chart->render();
} elseif ($this->style == 2 || $this->style == "2") {
$this->chart->setTitle($obj->title);
$i = 0;
$dataSet = new XYSeriesDataSet();
foreach ($obj->dataArray as $key => $val) {
$serie[$i] = new XYDataSet();
foreach ($val as $k => $v) {
$serie[$i]->addPoint(new Point($k, $v));
}
$dataSet->addSerie($key, $serie[$i]);
$i++;
}
$this->chart->setDataSet($dataSet);
$this->chart->render();
} elseif ($this->style == 3) {
$dataSet = new XYDataSet();
$this->chart->setTitle($obj->title);
foreach ($obj->dataArray as $key => $val) {
$dataSet->addPoint(new Point($key . "($val)", $val));
}
$this->chart->setDataSet($dataSet);
$this->chart->render();
} else {
$dataSet = new XYDataSet();
$this->chart->setTitle($obj->title);
foreach ($obj->dataArray as $key => $val) {
$dataSet->addPoint(new Point($key, $val));
}
$this->chart->setDataSet($dataSet);
$this->chart->render();
}
}
}
// 使用範例
$n = new drawPic("4");
$k = new stdClass();
$k->dataArray = array("2000" => "30", "2001" => "40", "2002" => "50", "2003" => "60", "2004" => "70", "2005" => "80", "20020" => "90");
$k->title = "The Sheet title";
$n->draw($k);
?>
<?php
header("content-type:image/png");
require_once('libchart/classes/libchart.php');
$chart = new VerticalBarChart(500, 250);
$dataSet = new XYDataSet();
$str = '二月';
$str = mb_convert_encoding($str, "html-entities", "utf-8");
$dataSet->addPoint(new Point("Jan 2005", 273));
$dataSet->addPoint(new Point($str, 120));
$dataSet->addPoint(new Point("March 2005", 442));
$dataSet->addPoint(new Point("April 2005", 600));
$chart->setDataSet($dataSet);
$chart->setTitle("統計圖");
$chart->render();
?>
修改 libchart/classes/view/chart/Chart.php 的 setTitle 方法:
public function setTitle($title) {
$title = mb_convert_encoding($title, "html-entities", "utf-8");
$this->plot->setTitle($title);
}
修改 libchart/classes/view/text.php 第 47-48 行:
$this->fontCondensed = dirname(__FILE__) . "/../fonts/你的中文字體.ttf";
$this->fontCondensedBold = dirname(__FILE__) . "/../fonts/你的中文字體.ttf";
需將中文字體(如微軟正黑體、文泉驛等)放入 fonts 目錄,且 PHP 檔案儲存為 UTF-8 編碼。