Developer Discussion

A blog about web programming.
Kh-sm

Easily show charts and graphs alongside statistics

Posted Thu May 29 at 04:56 PM by Kip

Most of us developers end up creating some kind of protected statistics pages for our clients. Say you've made a website that has a simple contact form on it, that captures some sort of demographics data along with the message the visitor has sent. Chances are that your client wants to see a report of those statistics that have been captured. Why limit ourselves to showing them some boring tables of totals and percentages? Let's spice those pages up a bit by taking advantage of Google's Chart API.

Our boring table

State Visitors Percentage
California 2,592 53.6%
Arizona 958 19.8%
Nevada 811 16.8%
Colorado 473 9.8%
Total: 4,834  

Here, client, take a look at these boring numbers and percentages. You probably expected us to go beyond this simplistic approach to showing you the data, huh?

Alright, so it's not that bad. Heck, if we add some nice color formatting and alignment in there, it might be pretty decent. But, why not add some awesome charts in there? It will only take us a line or two of code, and it'll look beautiful. Let's do this!

Let's improve this report

First, let's decide what type of chart we want. If you look through the API, you can see there are about seventy thousand chart types, each with customizable colors and styles. I think a pie chart is the best option for the simple data set that we have.

Google gives us this image URL format for the chart:

http://chart.apis.google.com/chart?<parameter 1>&<parameter 2>&<parameter n>

I'll go through the API and modify this URL until I'm satisfied with how it looks. Looks like to start I'll be setting the chart's size (chs=[width]x[height]), the data (chd=t:[data],[data],[data],...), the chart type (cht=p3), and the data labels, in the same order as the data provided (chl=[label]|[label]|[label]|... — that's CHL, not CH-One!). Remember that since we're using a pie chart, we'll want to express our data as percentages.

I come up with this image URL for my data above:

http://chart.apis.google.com/chart?chs=400x150&chd=t:53,19,16,9&cht=p3&chl=California|Arizona|Nevada|Colorado

Let's see it

Simply toss that URL as the src attribute of an img tag, and we'll get a chart. Let's see what it looks like!

Very cool! One thing I had to play around with a little bit was the chart size. You need to make sure you have enough extra width in your chart size to accommodate your labels, or they will not show up! Alright everyone, no more excuses for not having some awesome charts and graphs on those reporting pages for your clients. The API even provides chart types of scatter plots, Venn diagrams, and even maps.

Find related posts: google charts graphs tutorial

Post a comment

Name
Email — optional, shown to public
Comment