Creating Stylish Graphs with PHP & Yahoo Charts

1 comment
Few days back I was searching for some chart or Graph API to insert graphs in my web application. Then I encountered Yahoo Charts, and I start loving them in first use. Yahoo charts are very simple and customizable. And you can easily integrate them with server side language like PHP. Here I will show you the basic usage of Yahoo charts and how to integrate them with PHP. Watch it working.



Live Demo Download Script

First of all you need to include some javascript libraries in your web app to enable Yahoo charts. Following is the list of files. You can just copy and paste them in head tag of your page.

JavaScript Dependencies:
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/swf/swf-min.js"></script>
<!-- Source files -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/charts/charts-min.js"></script>
<script type="text/javascript">
YAHOO.widget.Chart.SWFURL = "http://yui.yahooapis.com/2.8.2r1/build/charts/assets/charts.swf";
</script>

Remember that Yahoo charts use JSON encoded data. So we have to convert our data into JSON format before using them for chart formation. We will fetch data from a MySQL database and store it in an array, Further array will be json formatted using json_encode() function of PHP.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test';
mysql_connect($host, $user, $pass);
mysql_select_db($dbname);

$data = array(); /*Array for holding the data*/

$res = mysql_query("SELECT `name`,`score`, `age` FROM `test`");
while($row = mysql_fetch_array($res))
{
 $temp_arr = array( 'name'=>$row['name'], 'marks'=>$row['score'], 'age'=>$row['age'] );
 array_push($data, $temp_arr);
}

$j = json_encode($data); /*Convert data into json format*/

echo '<script type="text/javascript"> /*Store data in JavaScript variable*/
  var myData = '.$j.';
   </script>';
?>
<script language="javascript">
var myDataSource = new YAHOO.util.DataSource(myData); /*Initialize data source*/
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
    fields: [ "name","marks","age" ] /*Specify fields in data source*/
};
</script>

Now create placeholder on your page to hold the chart specially a div as follows:
<div id="myContainer" style="height:500px; width:500px;">
 </div>

After creating the placeholder we will initialize the charts. Remember that following lines must be added after the 'div' in the HTML markup i.e the 'div' must be loaded before initializing the chart.
<script language="javascript">
var myChart = new YAHOO.widget.ColumnChart( "myContainer", myDataSource, {
    xField: "name", /*Specify x axis*/
    yField: "marks" /*Specify y axis*/
});
</script>

Customizing the Tool tip:
We can also customize the default tooltip text in the charts. For this add following lines of code:
function getDataTipText( item, index, series ) {
    var toolTipText = item.name + " of age " + item.age + " scored " + item.marks + " marks.";
    toolTipText += "\n";
    return toolTipText;
}
myChart.set( "dataTipFunction", getDataTipText ); /*Customize tooltip*/

Adding Currency To the Chart Axes:
Yahoo Charts enable you to customize your charts' axes for Currency Format. Just look how it is done:
var currencyAxis = new YAHOO.widget.NumericAxis();
currencyAxis.labelFunction = "formatCurrencyAxisLabel";
function formatCurrencyAxisLabel(value) {
    return YAHOO.util.Number.format(value, {
        prefix: "$",
        thousandsSeparator: ",",
        decimalPlaces: 2
    });
}
myChart.set("yAxis", currencyAxis);

Complete Code:
<html>
<head>
<!-- Dependencies -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/element/element-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/datasource/datasource-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/json/json-min.js"></script>
<script src="http://yui.yahooapis.com/2.8.2r1/build/swf/swf-min.js"></script>
<!-- Source files -->
<script src="http://yui.yahooapis.com/2.8.2r1/build/charts/charts-min.js"></script>
<script type="text/javascript">
YAHOO.widget.Chart.SWFURL = "http://yui.yahooapis.com/2.8.2r1/build/charts/assets/charts.swf";
</script>
</head>

<body>

<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test';
mysql_connect($host, $user, $pass);
mysql_select_db($dbname);

$data = array(); /*Array for holding the data*/

$res = mysql_query("SELECT `name`,`score`, `age` FROM `test`");
while($row = mysql_fetch_array($res))
{
 $temp_arr = array( 'name'=>$row['name'], 'marks'=>$row['score'], 'age'=>$row['age'] );
 array_push($data, $temp_arr);
}

$j = json_encode($data); /*Convert data into json format*/

echo '<script type="text/javascript">
  var myData = '.$j.';
  </script>';
?>

<script language="javascript">
var myDataSource = new YAHOO.util.DataSource(myData); /*Initialize data source*/
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
    fields: [ "name","marks","age" ] /*Specify fields in data source*/
};
</script>

 <div id="myContainer" style="height:500px; width:500px;">
 </div>
</body>

<script language="javascript">
var myChart = new YAHOO.widget.ColumnChart( "myContainer", myDataSource, {
    xField: "name", /*Specify x axis*/
    yField: "marks" /*Specify y axis*/
});

function getDataTipText( item, index, series ) {
    var toolTipText = item.name + " of age " + item.age + " scored " + item.marks + " marks.";
    toolTipText += "\n";
    return toolTipText;
}
myChart.set( "dataTipFunction", getDataTipText ); /*Customize tooltip*/
</script>
</html>

1 comments:

We would love to hear from you...

back to top