本节内容:
PHP折线图的生成代码。
例子:
<?php
/**
* php折线图示例代码
* by www.jb200.com
*/
$data = array(1,2,33,4,5,16,7,8,9,10,11,12);
$month= array("Jan","Feb","March","April","May","June","July","Aug","Sep","Oct","Nov","Dec");
$rdata = array(0.1,0.2,6,0.4,0.5,0.6,0.7,2,0.9,1,1.1,1.2);
$max=max($data); //获取销售额的最大值
$rmax=max($rdata); //获取利润的最大值
$im = imagecreate(600,300); //创建画布
$green = imagecolorallocate($im,214,235,214);//设置颜色值
$black = imagecolorallocate($im,0,0,0);
$red = imagecolorallocate($im,255,0,0);
$blue = imagecolorallocate($im,0,0,255);
imageline($im,20,230,530,230, $blue ); //设置X轴横坐标
imageline($im,20,20,20,230, $blue ); //设置Y轴纵坐标
imagestring($im,3,555,222,"X",$black); //输出字符X
imagestring($im,3,16,1,"Y",$black); //输出字符Y
$l=190;
$k1=20;
$k2=500;
for($j=0;$j<12;$j++){
imageline($im,$k1,$l,$k2,$l,$black); //设置X轴网格线横坐标
$l=$l-40;
}
$f=60;
$z1=30;
$z2=230;
for($j=0;$j<12;$j++){
imageline($im,$f,$z1,$f,$z2,$black); //设置Y轴网格线纵坐标
$f=$f+40;
}
//输出Y轴坐标值
$a=max($data);
$b=max($rdata);
$c=$a>$b?$a:$b;
$l=185;
for($j=0;$j<5;$j++){
imagestring($im,2,2,$l,floor($c/5*($j+1)),$red);
$l=$l-40;
}
$x = 20;
$y = 230;
for ($i=1;$i<12;$i++){
$y_lt = 230-(($data[$i-1]/$max)*200); //设置商品销售额所在的纵坐标值
$y_ht = 230-(($data[$i]/$max)* 200); //设置商品销售额所在的纵坐标值
imageline($im,$x*($i*2-1)+20,$y_lt,$x*(($i+1)*2-1)+20,$y_ht,$red); //绘制销售额折线图
}
for ($i=1;$i<13;$i++){
imagestring( $im,2,$x*($i-1)*2+30,$y+11,$month[$i-1],$black); //输出月份的值
imagestring( $im,2,$x*($i-1)*2+30,$y+25,$data[$i-1],$red); //输出商品销售额的值
imagestring( $im,2,$x*($i-1)*2+30,$y+40,$rdata[$i-1],$blue); //输出销售利润的值
}
$fontpath=$_SERVER["SystemRoot"]."fontssimhei.ttf"; //设置字库路径
$str=iconv("gb2312","UTF-8","中国人民123");
$str=str_repeat($str,2);
imagettftext($im,25,-45,80,20,$blue,$fontpath,$str);
imagettftext($im,15,30,180,190,$red,$fontpath,$str);
$x1 = 20;
$y1 = 230;
for ($r=1;$r<12;$r++){
$y_lt1 = 230-(($rdata[$r-1]/$max)* 200); //设置商品销售利润所在的纵坐标值
$y_ht1 = 230-(($rdata[$r]/$max)*200); //设置商品销售利润所在的纵坐标值
imageline($im,$x1*($r*2-1)+20,$y_lt1,$x*(($r+1)*2-1)+20,$y_ht1,$blue); //绘制销售利润折线图
}
list($usec, $sec) = explode(" ", microtime());
$ss=(string)((float)$usec + (float)$sec);
$ss2=((string)$sec).(substr((string)$usec,1,strlen((string)$usec)-1));
//echo $ss2;echo "<br>";
imagestring($im,8,200,10,$ss,$black);
imagestring($im,8,200,40,$ss2,$black);
$str=iconv("gb2312","UTF-8","9");
imagettftext($im,150,0,180,190,$red,$fontpath,$str);
echo(imagepng($im));
header("Content-type: image/png");
imagedestroy($im); //释放图像资源
header("Content-type: text/html");
//echo $ss2;echo "<br>";
?>
说明:若要同时输出多幅图,可以使用框架结构。