Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Dynamically Create Charts Using jQuery Flot and Google Analytics

17 Responses »

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.

The PHP

/* 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('youraccount@gmail.com', 'password');
	$analytics->setProfileByName('yourdomain.com');
	$analytics->setMonth($month,$year);
	$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).']';
	}
endif;

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; ?>;
	$('#placeholder').css({
		height: '400px',
		width: '600px'
	});
	$.plot($('#placeholder'),[
			{ 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.

Comparison

  • 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?

Discussion

  1. October 22, 2009 @ 7:57 am

    Perfect! Thanks for doing it using jQuery.

  2. October 22, 2009 @ 8:09 am

    Sweet!

    Great Demo, small typo in the sample “passwrod”

    cheers

  3. October 22, 2009 @ 9:12 am

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

  4. October 22, 2009 @ 9:53 am

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

  5. October 22, 2009 @ 10:02 am

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

  6. October 22, 2009 @ 10:24 am

    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. October 22, 2009 @ 2:55 pm

    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
    October 24, 2009 @ 11:00 am

    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
    October 26, 2009 @ 2:27 pm

    Nice!
    did you try jqplot inspired by Flot?!

  10. October 27, 2009 @ 8:53 am

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

  11. mike
    November 7, 2009 @ 11:44 pm

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

  12. November 16, 2009 @ 2:53 pm

    Static charts like this ones, for example:

    http://chart.apis.google.com/chart?chs=450×200&chf=bg,s,FFFFFF00&cht=lc&chco=0077CC&chd=t:403,383,536,555,657,553,347,696,460,920,554,475,495,237,80,159,371,352,452,447,440,181,388,769,574,473,587,291,234,158,381&chds=60,940&chxt=x,y&chxl=0:|Mon+10%2F19|Mon+10%2F26|Mon+11%2F02|Mon+11%2F09|Mon+11%2F16&chxr=1,80,920&chxp=0,6.67,30,53.33,76.67,100&chm=V,707070,0,2:31:7,1|o,0077CC,0,-1.0,6

    kills all the negatives of your comparison :))

  13. vladica savic
    January 19, 2010 @ 5:31 am

    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
    March 3, 2010 @ 6:42 pm

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

    try
    {
    $analytics = new analytics(‘youraccount@gmail.com’, ‘password’);
    }
    catch(Exception $e)
    {
    print_r($e->getMessage());
    }

    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. March 22, 2010 @ 5:27 am

    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
    http://spanishgringo.blogspot.com/2010/03/google-analytics-evolution-time-series.html

    http://gaevoluation.appspot.com

  16. mark joseph
    May 16, 2010 @ 10:46 am

    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
    August 19, 2010 @ 3:52 pm

    Hi David,

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

    http://code.google.com/p/flot/source/browse/trunk/jquery.flot.pie.js

    Thanks for the awesome post!

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!