PHP是一種廣泛使用的服務(wù)器端腳本語言,目前被大量的網(wǎng)站使用。PHP本身并沒有提供繪圖功能,但是通過第三方庫可以方便地實(shí)現(xiàn)。
其中,JPGraph和pChart是兩個(gè)非常著名且廣泛使用的PHP繪圖庫。
JPGraph能夠繪制精美的線性圖、柱狀圖、散點(diǎn)圖等,也能夠按需定制繪圖特性。它的特點(diǎn)是能夠通過簡單易懂的代碼實(shí)現(xiàn)繪圖需求,同時(shí)支持多種數(shù)據(jù)源,包括MySQL、SQLServer和CSV等等。舉個(gè)例子,下面的代碼實(shí)現(xiàn)了一個(gè)使用JPGraph繪制柱狀圖的功能:
require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_bar.php'); $data = array(44,53,31,61,38,50); $graph = new Graph(550,400); $graph->SetScale("textlin"); $graph->SetShadow(); $graph->title->Set("Sales per month for 2010"); $graph->subtitle->Set("This is just a test"); $graph->xaxis->title->Set("Month"); $graph->yaxis->title->Set("Sales"); $graph->xaxis->SetTickLabels(array('Jan','Feb','Mar','Apr','May','Jun')); $barplot = new BarPlot($data); $barplot->SetColor("white"); $barplot->SetFillColor("#cc1111"); $graph->Add($barplot); $graph->Stroke();pChart則是PHP中最優(yōu)秀的開源圖表工具之一,支持各種各樣的圖表類型,如柱形圖、餅圖、折線圖等等。它的特點(diǎn)是使用方便、代碼簡單,同時(shí)支持SVG、Flash動畫等輸出格式。舉個(gè)例子,下面的代碼實(shí)現(xiàn)了一個(gè)使用pChart繪制餅圖的功能:
require_once('pChart2.0.0/class/pData.class.php'); require_once('pChart2.0.0/class/pChart.class.php'); $data = array(20,50,30); $myData = new pData(); $myData->addPoints($data,'Score'); $myData->setSerieWeight('Score',2); $myData->setAxisName(0,"Scores"); $myData->addPoints(array("A","B","C"),"Labels"); $myData->setSerieDescription("Labels","Score"); $myData->setAbscissa("Labels"); $myPicture = new pChart(450,250); $myPicture->Antialias = FALSE; $myPicture->background->Fill(255,255,255); $pieChart = new pPie($myPicture,$myData); $pieChart->setSliceColor(0,array("R"=>255,"G"=>255,"B"=>255)); $pieChart->setSliceColor(1,array("R"=>0,"G"=>100,"B"=>255)); $pieChart->setSliceColor(2,array("R"=>255,"G"=>0,"B"=>0)); $pieChart->draw3DPie(125,125,array("Radius"=>100,"DrawLabels"=>FALSE,"LabelStacked"=>TRUE,"WriteValues"=>TRUE,"DataGapAngle"=>0,"DataGapRadius"=>10,"Border"=>TRUE)); $myPicture->Render();總之,PHP中的繪圖庫可以很方便地滿足我們繪制各種圖表的需求。在實(shí)際應(yīng)用中,我們可以根據(jù)具體需求選擇JPGraph或pChart等開源繪圖庫進(jìn)行使用。