Archives for: July 2009, 30
30/07/09
Create data graph on the fly
Generating graph from data collected on the internet and shows it on the web can be very useful.
I found 2 ways to create data graph/chart on the fly:
1. Use the google api
http://code.google.com/apis/chart/basics.html
To create a simple pie chart, all you need is one line of html
XML: | <img src="http://chart.apis.google.com/chart?chs=350x100&chd=t:60,40&cht=p3&chl=Web_designers|Programmers" alt="Sample chart" /> |
And you will have
2. Use php + GD Library
to create the same chart you need the following codes. Codes are based on
http://www.talkphp.com/advanced-php-programming/2508-3d-pie-charts-php-gd.html
with small changes
PHP: | $image = imagecreatetruecolor(300, 300); |
|
|
| $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); |
| $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); |
| $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); |
| $navy = imagecolorallocate($image, 0x00, 0x00, 0x80); |
| $darknavy = imagecolorallocate($image, 0x00, 0x00, 0x50); |
| $red = imagecolorallocate($image, 0xFF, 0x00, 0x00); |
| $darkred = imagecolorallocate($image, 0x90, 0x00, 0x00); |
| |
|
|
| imageFill($image, 0, 0, $white); |
| imageColorTransparent($image, $white); |
| |
| |
| for ($i = 160; $i > 150; $i--) { |
| imagefilledarc($image, 150, $i, 200, 100, 0, 45, $darknavy, IMG_ARC_PIE); |
| imagefilledarc($image, 150, $i, 200, 100, 45, 75 , $darkgray, IMG_ARC_PIE); |
| imagefilledarc($image, 150, $i, 200, 100, 75, 360 , $darkred, IMG_ARC_PIE); |
| } |
| |
| imagefilledarc($image, 150, 150, 200, 100, 0, 45, $navy, IMG_ARC_PIE); |
| imagefilledarc($image, 150, 150, 200, 100, 45, 75 , $gray, IMG_ARC_PIE); |
| imagefilledarc($image, 150, 150, 200, 100, 75, 360 , $red, IMG_ARC_PIE); |
| |
|
|
| header('Content-type: image/png'); |
| imagepng($image); |
| imagedestroy($image); |
If you need to know more about using GD Lib to create graph on the web, please visit a tutorial at
http://php.about.com/od/advancedphp/ss/gd_library_6.htm
You need to be careful when you are using server side script to generate graph as it is CPU intensive.

|
|