Web Developer's Virtual Library: Encyclopedia of Web Design Tutorials, Articles and Discussions


Java/Open Source Daily

jobs.webdeveloper.com

e-commerce
Partner With Us















Developer Channel
FlashKit.com
JavaScript.com
JavaScriptSource
Developer Jobs
ScriptSearch
StreamingMediaWorld
Web Developer's Journal
Web Developer's Virtual Library
WebDeveloper.com
Webreference
Web Hosts
XMLfiles.com

internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Create Custom Web-based Graphs with the Google Chart API and PHP

Bookmark and Share

by W. Jason Gilmore

January 19, 2010

Presenting data visually can quickly reveal crucial trends. Learn how to use the Google Chart API in conjunction with PHP to create a variety of useful charts.

The rise of both the Web and increasingly powerful computing platforms has led to a society capable of gathering data pertinent to nearly every aspect of life. In fact, we've become obsessed with data collection, using solutions such as the Nike + iPod Sport Kit to monitor workout performance, Google Analytics to analyze corporate web site data, and The Energy Detective to track home electricity usage.

Yet for all of our fascination with amassing reams of data, most of us are actually pretty poor at actually analyzing this information in an effective manner. For instance, consider the following data set, which represents the number of calories I've burned during the past seven visits to the gym:

420,504,315,274,296,600,366

Although the information is right in front of my eyes, this bland representation makes it rather difficult to draw any definitive conclusions regarding my workout effectiveness. However, the potential trends buried within such data compilations tend to come alive when it's presented in a visually appealing way. Let's reconsider this data, but this time viewing it as a line chart (see Figure 1).


Figure 1. Charting the Calories Burned Over a Seven-Day Period: Potential trends tend to come alive when data is presented in a visually appealing way.

Put into the context of a seven-day period and charted, the data leads to immediate conclusions (such as my most effective workout day happens to be Friday, whereas my least effective days tend to fall during the midweek). Armed with this information, I might consider making changes to my workout in order to ensure a more uniform number of calories are burned throughout the week!

To help developers represent data as convenient charts such as this, Google (perhaps the reigning champion of data aggregation) released the Google Chart API in late 2007. In this tutorial, I'll show you how to use the Google Chart API in conjunction with PHP to create a variety of useful charts.

Introducing the Google Chart API

The Google Chart API is a Google service that allows you to dynamically create a variety of charts, given a data set and other relevant information such as the desired size, chart legends, and axis labels. Given this information, the service will respond with a link to the chart, which you can embed in an <img> tag's src attribute. The provided data is sent along as a series of GET parameters. For instance, you can create a chart simply by contacting the service via your browser address bar. Paste the following URL into your browser for an example:

http://chart.apis.google.com/chart?cht=p3&chd=t:30,70&chs=400x200&chl=Protein|Carbs

Navigating to this URL will produce the chart shown in Figure 2.


Figure 2. Creating a Pie Chart with the Google Chart API: You can create a chart simply by contacting the service via your browser address bar.

Pie charts are only one of many chart types supported by the API; you can also create line, bar, and radar charts, in addition to Venn diagrams, scatter plots, and even map-based charts. Further, the API offers quite a few options for tweaking the presentation, such as setting the chart color, creating three-dimensional charts, modifying the chart orientation, and much more. See this page of the Google Chart API documentation for more information.

While this example demonstrated just how easy it is to create charts using Google Chart API, you'll need to spend some time getting acquainted with the numerous parameters before you can begin effectively using the service. Google probably used such short parameter names to maintain an absolute minimum communication payload, yet this comes at the cost of readability. To better understand the available parameters, let's break down the ones I used to create the above chart. For convenience, I'll reprint the URL here:

http://chart.apis.google.com/chart?cht=p3&chd=t:30,70&chs=400x200&chl=Protein|Carbs

Let's review each parameter:

  • http://chart.apis.google.com/chart?: This is the service URL.
  • cht: This parameter defines the chart type. The above example is a three-dimensional pie chart, which is represented by the p3 value. Numerous other types exist, such as lc (line chart), ls (sparklines), and bhs (horizontal bar chart). (See the Google Chart API documentation for a complete list.)
  • chd: This parameter defines the data to be charted by the API. In the case of a pie chart, each value defines a percentage of the total pie size (100%), therefore 30,70 will define two slices: one consuming 30%, another 70%. Try experimenting with this value by modifying it to read t:10,50,40 and then reloading the browser.
  • chs: This parameter defines the chart size (width x height) in pixels.
  • chl: This parameter defines the chart labels. In the case of a pie chart, each label must be separated by the pipe symbol. Different syntactical variations apply according to chart type, so be sure to check the API documentation.

Of course, rather than tediously memorize the ambiguous list of parameters, why not create a PHP class that will offer a much more friendly API interface? In fact, several such classes already exist! Of the three best-known solutions, I recommend checking out GoogChart (as well as the project author's original blog post here). Although it's far from complete, GoogChart seems to offer the easiest solution for building basic charts.

Creating Google Charts with PHP and GoogChart

Like so many open source projects, GoogChart was created when author Ludwig Pettersson searched for an effective way to dynamically create charts based on stored data and found no acceptable solutions. Currently, GoogChart is capable of creating most of the graphs necessary for most typical applications, including pie, line, sparkline, horizontal bar, and vertical bar.

To begin using GoogChart, head over to the project's Google Code repository and download the class. Just include that class at the top of a PHP script, and you can begin creating your own charts! For instance, the following code creates the chart shown in Figure 1.

<?php

require 'GoogChart.class.php';

$chart = new GoogChart();

$color = array('#993300');

// Create the graph data array
$calories = array( 
  'Calories Burned' => array(
    'Sun'   => 420,
    'Mon'   => 504,
    'Tues'  => 315,
    'Weds'  => 274,
    'Thurs' => 296,
    'Fri'   => 600,
    'Sat'   => 366
  )
);

$chart->setChartAttrs( 
  array(
    'type'      => 'bar-vertical',
    'title'     => 'Getting Fit in 2010!',
    'data'      => $calories,
    'size'      => array( 550, 200 ),
    'color'     => $color,
    'labelsXY'  => true,
    'axisRange' => '0,100,800|1,0,800',
    'dataRange' => '0,800',
  )
);

echo $chart;

?>

This code doesn't work right out of the box; I did have to make a slight change to the GoogChart class in order to accommodate data values exceeding 100 (which is the default maximum allowable value). Read on to learn how I did it!

Adjusting the Axis and Data Ranges

One of the immediate drawbacks to GoogChart is it doesn't support adjusting the allowable range of data values, which by default is set to 0-100. Because all of the calorie values exceed this default range, I needed to make some changes to the class. For starters, I added the following two methods in order to adjust the allowable axis and data ranges:

// Set axis range
protected function setAxisRange( $range )
{
  $this->axisRange = $range;
}

// Set data range
protected function setDataRange ( $dataRange )
{
  $this->dataRange = $dataRange;    
}	

You'll also need to add the following two lines to the display() method's $this->query array (found in the GoogChart.class.php class), in addition to defining two appropriately named protected attributes at the top of the class:

'chxr' => $this->axisRange,
'chds' => $this->dataRange	

Where to From Here?

Creating dynamic charts using the Google Chart API is pretty easy when you learn what exactly is available in the supported parameters. With a class like GoogChart and some patience, you'll be able to bring PHP into the picture and create charts based on data stored in databases such as MySQL. Be sure to let me know if you do anything interesting with this great API!

About the Author

Jason Gilmore is founder of EasyPHPWebsites.com, and author of the popular book, "Easy PHP Websites with the Zend Framework". Formerly Apress' open source editor, Jason fostered the development of more than 60 books, along the way helping to transform their open source line into one of the industry's most respected publishing programs. Over the years he's authored several other books, including the best-selling Beginning PHP and MySQL: From Novice to Professional (currently in its third edition), Beginning PHP and PostgreSQL: From Novice to Professional, and Beginning PHP and Oracle: From Novice to Professional.

Jason is a cofounder and speaker chair of CodeMash, a nonprofit organization tasked with hosting an annual namesake developer's conference, and was a member of the 2008 MySQL Conference speaker selection board.

Jason has published more than 100 tutorials and articles within prominent publications such as Developer.com, Linux Magazine, and TechTarget.



Up to => Home / Authoring / Tutorials / PHP