Use PHP and Pear Graph in your Web Page to show Statistics

Nowadays it has become a nice trend to add graphical representation of statistical data to enhance the quality of web pages. But the question is how to create dynamic graph or pie chart or bar chart in the web pages with PHP programs.

Trust me guys, its very easy if you do it with PEAR image package. Ok…let me write down all the steps, how you might do it.

  • If PEAR is not installed in your server please install PEAR. Good news…it comes absolutely free being an open source package. You will get PEAR installation guide from
  • Don’t forget to install “Image” package from the pear.
  • Well…you are almost done now :)
  • Now all you have to do is to use the code snippet mentioned bellow.

You would also like to use different colors for different bars or different sections of the pie chart. To do that we need to give each dataset a unique identifier, as well as use a fill array to match the colors with the element. Also one graph may have more than one plot areas.

Let’s have a look at the following example for a better understanding…

include ‘Image/Graph.php';
$Graph =& Image_Graph::factory(‘graph’, array(600, 300));

$PlotareaTopLeft = Image_Graph::factory(‘plotarea’),
$PlotareaBottomLeft = Image_Graph::factory(‘plotarea’),
$PlotareaRight = Image_Graph::factory(‘plotarea’),

$Dataset =& Image_Graph::factory(‘dataset’);
$Dataset->addPoint(‘Jan’, 5, ‘J’);
$Dataset->addPoint(‘Feb’, 13, ‘F’);
$Dataset->addPoint(‘March’, 10, ‘M’);
$Plot =& $PlotareaRight->addNew(‘bar’, &$Dataset);


$fill =&
$fill->addColor(‘red’, ‘J’);
$fill->addColor(‘blue’, ‘F’);
$fill->addColor(‘yellow’, ‘M’);

$Font =& $Graph->addNew(‘ttf_font’, ‘Bitstream-Vera-Sans-Mono’);

$YAxis =& $PlotareaRight->getAxis(IMAGE_GRAPH_AXIS_Y);
$YAxis->setTitle(‘Rainy Days’, ‘vertical’);
$XAxis =& $PlotareaRight->getAxis(IMAGE_GRAPH_AXIS_X);

//2nd Plotarea
$Plot2 =& $PlotareaTopLeft->addNew(‘pie’, &$Dataset);

$fill =&
$fill->addColor(‘red’, ‘J’);
$fill->addColor(‘blue’, ‘F’);
$fill->addColor(‘yellow’, ‘M’);

//3rd Plotarea
$Plot3 =& $PlotareaBottomLeft->addNew(‘line’, &$Dataset);


At first, the graph is divided horizontally into two areas:

The leftmost plotarea which is taking up 30% of the space

The right one which is taking up the remaining.

The left area is then further broken into two plotareas, the top one taking up 60% of the space. Using the same dataset, we create two new types: a pie graph and a line graph.

Hope you have a wonderful time doing it as I did. For more on the subject, all you have to do is to… Stay tuned!!!

You made it to the 19th day of the writing challenge.

The following two tabs change content below.


Latest posts by admin (see all)