#StandWithUkraine

PHP class/WP plugin for Google Charts API

Google had discontinued Chart API in April 2012 and it is expected to stop working after April 2015.

Honestly 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.

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
  • 0.2 code cleanup, inline documentation, implementing some recent changes

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

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

Related Posts

21 Comments

  • Noah #

    Do know you can set variables in a array? :) Example, $value_1 = $_SESSION['Numberone'] $first = array($value_1) and so on. :)
  • Rarst #

    @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. :)
  • Noah #

    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.
  • Rarst #

    @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.
  • Noah #

    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.
  • Rarst #

    @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.
  • Noah #

    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.
  • Rarst #

    @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.
  • Noah #

    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 :)
  • Rarst #

    @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? :)
  • Noah #

    Pretty much :) And now I want a share of the profits! Hehe.
  • Visual cues in interfaces | Rarst.net #

    [...] 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. [...]
  • PDFCreator – virtual printer to create documents | Rarst.net #

    [...] some time how should I organize jump from my report at work (beautiful mess of MySQL, PHP and my Google Charts class) to consolidated [...]
  • IPSURE | Uygulamalar (Weblog) | Google Analytics API ve Google Chart API Entegrasyonu İle Dinamik İstatistik Çizelgeleri Oluşturma « #

    [...] PHP class çalışmasından dolayı Eldee’ye ve Google Chart API class çalışmasından dolayı Andrey Savchenko (Rarst)’a teşekkür [...]
  • IPSURE | Hands-On (Weblog) | Creating Dynamic & Realtime Statistical Charts By Integration Of Google Analytics API And Google Chart API « #

    [...] 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 [...]
  • What is graphs in admin area best practice? - WordPress Tavern Forum #

    [...] on programming courses) that will require some graphs, mostly in admin area. For my own use I have Google Charts class that works reasonably well. But will have to either stick it into every plugin, or require it as [...]
  • erd #

    I am trying your script but i get this php error: PHP Warning: implode() [function.implode]: Invalid arguments passed in google_chart.php on line 733 line 733= $url .= '&chem=' . implode( '|', $this->chem ); any idea?
  • Rarst #

    @erd Hmm... It shouldn't be added if not set and if it's set then why error... chem is about icon markers, are you adding any? Can you add an example? Please email me at contact@rarst.net if that is more convenient for you than comments.
  • Vitaliy Kaplich #

    Good job! Thank you for this library! I've found a small issue: The 'chart title' should be URL encoded otherwise for instance if the title contains character - "#" all URL parameters following after this character will be treated as HTML anchor and will not be process correctly by Google Chart API. Method: SetTitle Line: 973 $this->title = '&chtt=' . urlencode($title);
  • Rarst #

    @Vitaliy Kaplich Noted, thank you. :) This code is kind of in a limbo at moment. I no longer work on project this was originally developed for. On other hand I am more interested into making more polished and full-featured WordPress plugin out of it... but no estimates on when will I get to that.
  • Tran Ngoc Nhat #

    @erd Your replace code : if (is_array($this->chem)) $url .= '&chem=' . implode( '|', $this->chem );