Charts with PHP and Google Charts API
Just yesterday I found out about the Google Charts API and I was impressed by this excellent service but noticed that creating multiple charts got pretty messy, especially if I wanted to edit the data later on.
I figured if I wanted to use this in the future, I’d like an easier way to create charts out of my data - thus the class GoogChart was born.
What I wanted to do was to simplify the process of calling the API, say I’ve got my data in an array called
<?php $data = array( 'IE7' => 22, 'IE6' => 30.7, 'IE5' => 1.7, 'Firefox' => 36.5, 'Mozilla' => 1.1, 'Safari' => 2, 'Opera' => 1.4, );
So I’ve got my data, I want it to be presented as a pie chart and be a specific size as well - Rather than to manually edit this into what the API would accept, as well as adding the labels for each of part of the data - It’s with GoogChart it’s as easy as:
<?php $chart = new googChart(); $chart->setChartAttrs( array( 'type' => 'pie', 'data' => $data, 'size' => array( 300, 200 ) )); echo $chart;
That tiny bit of code generates a Pie chart with all of my data neatly labeled and presented exactly as it should:
But that’s not all it can do, want to add a title to the chart? just add
'title' => 'Browser market 2008' to
GoogChart also supports multiple data types, just add each data to its own array within
<?php $data = array( 'February 2008' => array( 'IE7' => 22, 'IE6' => 30.7, 'IE5' => 1.7, 'Firefox' => 36.5, 'Mozilla' => 1.1, 'Safari' => 2, 'Opera' => 1.4, ), 'January 2008' => array( 'IE7' => 22, 'IE6' => 30.7, 'IE5' => 1.7, 'Firefox' => 36.5, 'Mozilla' => 1.1, 'Safari' => 2, 'Opera' => 1.4, ), );
The names of each data set are automatically added as Legends.
What kind of chart to create
The data to be used in the chart in an
The size of the chart
(Width x Height)
Colors to be used in the chart as
Fill colors to be used between timelines as
Background color of the chart, defaults to
Show or hide X and Y axis labels
(true/false)(false by default)
Show or hide a Legend
(true/false)(true by default)
Standard pie chart
Standard Line chart
Almost identical to Line, except defaults to no axis lines.
Horizontal bar chart
Vertical bar chart
Includes class as well as a short example file.
GoogChart covers by no means the whole Google Charts API - only the basics for now.
GoogChart is distributed under the MIT license, so feel free to change the class any way you want.
I’d like to thank my friend Fredrik Holmström for helping me enhance my code.