Dynamically Create Charts Using jQuery Flot and Google Analytics

By on  

jQuery Flot

Earlier in the week I published a popular article titled Dynamically Create Charts Using MooTools MilkChart and Google Analytics. My post showed you how to use MooTools MilkChart and a splash of PHP to create beautiful charts of Google Analytics data. I was interested in seeing what jQuery had to offer in the charting department. jQuery Flot is what I found.


/* defaults */
$month = date('n');
$year = date('Y');

/* submission? */
if($_GET['month'] || $_GET['year']):
	/* cleanse lookups */
	$month = (int) $_GET['month']; if(!$month) { $month = 1; }
	$year = (int) $_GET['year']; if(!$year) { $year = date('Y'); }
	/* retrieve information from google analytics */
	require 'ga/analytics.class.php';
	$analytics = new analytics('[email protected]', 'password');
	$visits = $analytics->getVisitors();
	$views = $analytics->getPageviews();
	/* build tables */
	if(count($visits)) {
		foreach($visits as $day=>$visit) { 
			$flot_datas_visits[] = '['.$day.','.$visit.']';
			$flot_datas_views[] = '['.$day.','.$views[$day].']';
		$flot_data_visits = '['.implode(',',$flot_datas_visits).']';
		$flot_data_views = '['.implode(',',$flot_datas_views).']';

The above code is the same as my MooTools post with the exception of the statistics output format. jQuery flot prefers arrays instead of a HTML table.

The jQuery Flot JavaScript

$(document).ready(function() {
	var visits = <?php echo $flot_data_visits; ?>;
	var views = <?php echo $flot_data_views; ?>;
		height: '400px',
		width: '600px'
			{ label: 'Visits', data: visits },
			{ label: 'Pageviews', data: views }
	        lines: { show: true },
	        points: { show: true },
	        grid: { backgroundColor: '#fffaff' }

The above is a simple example of using jQuery Flot's plot method. Simply provide the placeholder and statistical data from the PHP above.


  • jQuery Flot provides IE support via ExCanvas, which is great.
  • MilkChart allows for pie charts while Flot doesn't. I prefer pie charts to other chart types.
  • MilkChart allows for easy creation of charts from HTML tables (good for accessibility) while jQuery Flot requires an array syntax.

What do you think? Which method do you prefer?

Track.js Error Reporting

Recent Features

  • Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() – this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • 9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • Animated AJAX Record Deletion Using Dojo

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with Dojo JavaScript. The PHP - Content & Header The following snippet goes at the...

  • Create Spinning, Fading Icons with CSS3 and MooTools

    A goal of my latest blog redesign was to practice what I preached a bit more;  add a bit more subtle flair.  One of the ways I accomplished that was by using CSS3 animations to change the display of my profile icons (RSS, GitHub, etc.)  I...


  1. Perfect! Thanks for doing it using jQuery.

  2. Sweet!

    Great Demo, small typo in the sample “passwrod”


  3. Wow… a great site…. and a great post… cheers !!!

  4. Yeee! I was just wondering how to do this with jQuery, thank you :)

  5. Doesn’t work in IE. Looks great otherwise :)

  6. Works for me in IE7 and on my IE6 Virtual Machine, and Firefox 3. Nice, was looking for something like this.

    If you like pie charts wondering why you did not use Sparklines?

  7. FWIW, I can say firsthand that Flot is very easily customizable. I can’t judge MilkChart. MilkChart looks a bit slicker IMHO.

  8. Bruce Robertson

    Pie charts are a very poor choice except in the simplest cases. So say I; but also visual data guru Tufte, strongly against them.

  9. JC

    did you try jqplot inspired by Flot?!

  10. David, It could be interesting to develop this chart using AJAX (with Mootools, of course).

  11. Mike

    I cant get this to work. Do you have like an example file i could take a look at?

  12. Static charts like this ones, for example:


    kills all the negatives of your comparison :))

  13. Vladica Savic

    Hi, can you post here your analytics.class.php becouse, I download the latest version from their website but when I try to run my code I receive error (of handling response from google).

  14. Zoran

    @Vladica, the class is using Exceptions to handle errors, so put the initialization in try, catch block and print out the error.

    $analytics = new analytics('[email protected]', 'password');
    catch(Exception $e)

    You will see the error you are getting… also it’s good idea to look through the code of the class, wherever a possible exception is thrown you need to catch it in case it occurs.

  15. I made a Google App Engine Project with Java taking a similar approach, but anybody can use it with their own data.

    Take a look


  16. Mark Joseph

    Hi david thanks for the tutorial and i’m a bit frustrated about the results on my end… though i already posted all those codes inside my page, but i still get stuck in the end resulting my page to none.

    do you have any samples aside for the given demo you had here… thanks and appreciate your effort to this.

  17. Jon Clark

    Hi David,

    Just wanted to mention that flot now has a pie chart plugin:


    Thanks for the awesome post!

  18. VaN

    no link to the php class ? how are we suppose to find the correct class file ? there are tons of GA php classes..

  19. @VaN, the class can be found here: http://www.swis.nl/ga/

    It’s linked to in the original MooTools post.

  20. Josh

    This is a great article. but i’m having trouble getting it work. Is there a demo file with all the PHP and scripts running that I could possible try working from?

    Also with this script and php, can it be modified to run multiple graphs from multiple profiles? (from the same google account tho), if so that would be awesome!

    Many Thanks

  21. Hi – nice, thanx
    getting some errors though:

    A PHP Error was encountered
    Severity: Notice
    Message: Undefined index: month
    Filename: views/admin_welcome_view.php
    Line Number: 6

    A PHP Error was encountered
    Severity: Notice
    Message: Undefined index: year
    Filename: views/admin_welcome_view.php
    Line Number: 6

    PHP is not a happy place for me – anyone shed any light? or have any guidance pls.

    • Undefined indexes are PHP Notices or Warnings. Check that the array key exists with a

      array_key_exists(‘month’, $array);

      Before trying to pull the array index. I haven’t seen your code so I can’t really give to much advice on it, but I normally use a method to check if the array key exists and is not empty before accessing it, something like

      function key_exists ( $key, $array )
      return (bool) ( array_key_exists ( $key, $array ) && !empty ( trim ( $array[$key] ) );

      That should work without throwing any notices.

  22. Alpha

    @Shawn Crigger : Way using all that when you can simply use an isset ?

    $year = isset($_GET[‘year’]) ? $_GET[‘year’] : date(‘y’);

  23. ramesh

    Hi David,
    I will be really very thank full you if you can gave me all the code How can i get analytical chart data from analytical account and show up on chart.

    I had found lot of links and way in google but really no one is help full.

    Actually i want to display all info of my google analytical account in my custom website admin panel.

    Thanks in advance,

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Convert Video to mp3

    Let's all be honest for a moment:  we've all ... not paid for ... music.  Whether it was via a file sharing app like Kazaa or Napster, or it was downloading and seeding on bittorrent, or maybe even downloading a music video and ripping its audio,...

  • Sort git Branches by Date

    I'll be first person to admit I don't do as much git repository maintenance as I should.  I rarely delete branches which have been merged, so a git branch execution shows me a mile-long list of branches that likely aren't relevant.  The best way to find branches I've recently...

  • Best Tools and Resources for Web Professionals in 2015

    Looking for the right resources to help you satisfy the needs of your clients? On the lookout for the best tools to help you increase your revenue? Searching for the right software to help you improve your business? Well, then you’ve come to the right place....

  • JavaScript Polling

    Polling with JavaScript is one of those ugly but important functions within advanced front-end user experience and testing practices.  Sometimes there isn't the event you can hook into to signify that a given task is complete, so you need to get your hands dirty and simply poll for...

  • OSCON Portland:  Conference Giveaway and Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...