September 18th, 2009 Script | comments_icon15 Comments

PHP class/WP plugin for Google Charts API

chartHonestly I simply have no better place where to dump this. :) I need PHP exercise and tired of wasting time and effort every time I need chart or graph of some kind.

So unless you are interested (together or separately) in:

  • PHP;
  • Google;
  • charts (or at least pretty pics).

Then it is safe to skip this one.

What it does

Google Chart API serves pretty (or ugly, your choice) graphs of various kinds, taking specially formed URLs as input. One of those things that started as internal tool to power Google’s own stuff and later expanded into freely available service.

Why bother

  • let Google do grunt work of image generation;
  • let Google take bandwidth hit, up to 250K requests daily allowed and you can ask for more;
  • hook some dynamic data into it and get image that is always up to date.

Goals

Naturally there are a lot of solutions to make use of Google charts already. Somehow most of PHP ones start with “I am not going to maintain this” or “Could be better” or whatever.

I decided I could as well work with mess of a code that is mine. Roughly I want my WordPress blog to:

  • easily produce charts (of any kind I might like) when needed;
  • style them in consistent way;
  • make whole thing easy to work with.

Demo

Most of my charts are traffic related anyway. So I took real (plus projected) traffic details for two years of blogging. In PHP this would be:

$first=array(1634,1960,3664,3089,2084,2975,5835,7395,8091,10524,13169,
15022);
$second=array(16089,16676,18456,19129,21171,22674,21935,26010,26959,
29836,30924,34225);

If I simply drop these in Charts URL I will get terrible result, there are four different encodings to choose from and none of them is any good with large numbers.

So, taking my class for a ride:

$traffic = new GoogleChart;
$traffic->type='lc';
$traffic->SetImageSize(540,200);
$traffic->SetEncode('simple');
$traffic->AddData($first);
$traffic->AddData($second);
  • create new object;
  • set type to simple lines;
  • image size to one that fits my blog’s content area;
  • choose simple encoding that gives shortest URL, notice that large values will be automagically recalculated for it;
  • feed two arrays into it.
echo $traffic->GetImg();

chart

Here they are, nicely scaled to occupy all of image. Bit bland thou. Let’s spice it.

$traffic->AddChartColor('FF9900');
$traffic->AddChartColor('0077CC');
$traffic->AddLineStyle(3);
$traffic->AddLineStyle(2,5,5);
$traffic->AddDataLineStyle('0077CC',1,'0:1',3);
$traffic->AddFillArea('B','FF99007F',0);
$traffic->AddFillArea('b','E6F2FA7F',0,1);
  • add two colors for lines, order applied will be the same I added arrays in;
  • add two line styles, solid for past line and dashed for second year that had only started recently;
  • additional line segment to cover time that passed in second year;
  • some colors, notice different syntax – first covers from line to bottom of graph and second covers between two lines.

chart Much better, right? If I am ripping Google Analytics style anyway let’s add those cute nodes.

$traffic->AddShapeMarker('o','FFFFFF',0,-1,9);
$traffic->AddShapeMarker('o','FF9900',0,-1,7);
$traffic->AddShapeMarker('o','FFFFFF',1,'0:1',9);
$traffic->AddShapeMarker('o','0077CC',1,'0:1',7);
  • first set of markers will create orange dot on top of larger white for first year;
  • second set will do same for second, but only on chosen segment.

chart

Now it looks really nice, but overall lacks info value. Could be graph or anything, let’s make it clear.

$traffic->AddAxis('y,x');
$traffic->AddAxisRange(0,35000,5000);
$traffic->AddAxisLabel(array('Aug','Sep','Oct','Nov','Dec',
'Jan','Feb','Mar','Apr','May','June','July'),1);
$traffic->SetGrid(round(100/11,2),round(100/7,2),1,3);
  • add two axes for left and bottom;
  • left gets traffic figures from 0 to 35k with 5k step;
  • bottom gets months;
  • while at it I add grid, split into 12 parts horizontally and 7 vertically to match.

chart

And for last touch, since I am lazy to type explanations for chart near it:

$traffic->SetTitle('Visits per month');
$traffic->AddLegend('2008-2009');
$traffic->AddLegend('2009-2010');
$traffic->SetLegendPosition('b');
$traffic->AddDataPointLabel('f',round(array_sum($first)+$second[0]+
$second[1],-3).' total','000000',1,1,12);
  • title;
  • names for graphs, notice they pick up colors as well;
  • show legend at the bottom;
  • small flag with calculated total visits so far.

&chtt=Visits+per+month Nice, isn’t it? :)

Todo

  • cleanup initial mess of a code;
  • implement maps, QR codes and labels;
  • implement method to call sets of hardcoded styles.

Overall

Two things AS IS and NOT PRODUCTION CODE. I spent three days to get most of properties implemented and there is plenty of polishing ahead. Will be happy to hear what you want from such a class. And maybe some simple and stylish examples to hardcode.

Can be used as WP plugin (but does nothing except providing class) or simply included in PHP to play with.

Version history

  • 0.1 initial release

Google Chart API http://code.google.com/apis/chart/

Plugin download http://www.rarst.net/script/google_chart.zip

RSSGet updates via RSS

15 Responses to “PHP class/WP plugin for Google Charts API”

  1. Noah says:

    Do know you can set variables in a array? :) Example,

    $value_1 = $_SESSION['Numberone']

    $first = array($value_1)

    and so on. :)

  2. Rarst says:

    @Noah

    Ehm… I know what array is and how to pack stuff in it. Look, there are some arrays in example code above. :)

    What specific part of this stuff you are getting at?

    PS I’ve cut like hundred lines of excessive code from first version today btw… will update on weekend after ensuring I hadn’t broke anything. And of course there is probably hundred things not yet working in it. :)

  3. Noah says:

    Ah, I was just checking, cause you didn’t use variables in the arrays :) Trying to be helpful hehe :)
    So you’re going to put on the site ? Cool. How does WP work? I’ve never used it, blogger is free, and the other sites I have are all business related.

  4. Rarst says:

    @Noah

    Actually some of methods have to accept mixed input and distinguish between single value and array of values. Needed to get multicolored stacked bars for example.

    I’ve kept example basic (and cute :).

    WordPress is blog/CMS engine in pure PHP. It can be easily extended with plugins (which can be basically any PHP code plus some stuff to make WP recognize it).

    So this class is packed as simple WP plugin. While it is enabled in WP, I can use it in other plugins, theme code and (with some extra effort to bypass default security) inside posts.

  5. Noah says:

    Ah, I love PHP. Favourite language, I just like the syntax.

    Ah, I see. So a sort of website builder? Sounds good for quickly setting up a blog. I like the thing you have on the top of page, it might just be the best in-site advertising for posts.

  6. Rarst says:

    @Noah

    Yep, it is about perfect to get blog up and running fast. Like in few minutes – upload WP, launch quick install routine to hook with database, upload some theme for design (plenty of both free and paid around).

    Getting deeper however can be challenging, code base is… peculiar. :) And a moving target, stuff gets changed between versions.

    I have mixed feelings about that slideshow. :) Effect is nice but the only plugin that fits my needs took hours to get it working and validating properly. It also eats bandwidth by fetching local images through HTTP requests. And developments is quite dead.

    I’ll have to re-code it from scratch :( for new theme I am slowly working on.

  7. Noah says:

    Hehe, sounds fun. You should take a look at trying to set up your own custom cart while using paypal to pay for it. It’s a complete nightmare.

    Ah, I suppose. Still, as bandwidth becomes less and less of a problem, it’s probably worth it :)

    Do the google ads make your site pay for itself? My cousin swears by them, and what I’ve seen so far, it’s all good.

  8. Rarst says:

    @Noah

    Heh, anyway you can look through WordPress tag or hit me in email/IM if you need firsthand info on WP. :)

    As for Google ads they are making twice old hosting cost, and infinitely more than current hosting cost (free :). Another thing that needs serious attention and optimization in new theme. This one completely sucks for ads and it doesn’t help that I was barely interested in that aspect during all of first year.

  9. Noah says:

    Ah, nice :)
    I’ll have a go at setting one up sometime, when I’m not so busy.

    Oh, nice. My cousin tells me that the best plan is buy a empty server with a name that people search for a lot, and then you get something like £20 ( ~ $30) per click on a ad.

    I guess the trick is to trick your followers to click on the ads, as if they are a part of your site and links to other things on your site :)

  10. Rarst says:

    @Noah

    My cousin tells me that the best plan is buy a empty server with a name that people search for a lot, and then you get something like £20 ( ~ $30) per click on a ad.

    Has he actually tried this and millionaire by now? :)

  11. Noah says:

    Pretty much :)

    And now I want a share of the profits! Hehe.

  12. [...] Yesterday I started up all that mess of software, that is essential for my work/fun/whatever process. And suddenly I was unable to find Notepad++. I knew it was there, knew I had just killed few more lines of code from google charts class. [...]

  13. [...] some time how should I organize jump from my report at work (beautiful mess of MySQL, PHP and my Google Charts class) to consolidated [...]

  14. [...] PHP class çalışmasından dolayı Eldee’ye ve Google Chart API class çalışmasından dolayı Andrey Savchenko (Rarst)’a teşekkür [...]

  15. [...] various sample classes I tried, I would like to thank Eldee for his Google Analytics API PHP and Andrey Savchenko (Rarst) for his Google Chart API which I used inside my application being appreciative of their coding [...]

Leave a Reply