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

$month = date('n');
$year = date('Y');


if($_GET['month'] || $_GET['year']):
	
	$month = (int) $_GET['month']; if(!$month) { $month = 1; }
	$year = (int) $_GET['year']; if(!$year) { $year = date('Y'); }
	
	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();
	
	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?