O'Reilly

Dynamically Create Charts Using MooTools MilkChart and Google Analytics

By on  
MilkChart

The prospect of creating graphics charts with JavaScript is exciting. It's also the perfect use of JavaScript -- creating non-essential features with unobtrusive scripting. I've created a mix of PHP (the Analytics class), HTML, and MooTools JavaScript that will connect to Google Analytics, create an HTML table with the statistics for a given month, and use MooTools MilkChart to colorfully chart them out.

The PHP

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

/* 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]', 'yourP@ss');
	$analytics->setProfileByName('yourdomain.com');
	$analytics->setMonth($month,$year);
	$visits = $analytics->getVisitors();
	$views = $analytics->getPageviews();
	/* build tables */
	if(count($visits)) {
		//visits - php
		$visits_table_data = '<table id="data-table-visits">';
		/* $visits_table_data.= '<thead><tr><th>Unique Visits</th><th>PageViews</th></tr></head><tbody>'; */
		$visits_table_data.= '<thead><tr><th>Unique Visits</th></tr></head><tbody>';
		foreach($visits as $day=>$visit) { 
			/*
			$visits_table_data.= '<tr><td>'.$visit.'</td><td>'.$views[$day].'</td></tr>'."\n"; 
			$visits_table_foot.= '<td>'.$day.'</td><td>'.$day.'</td>'."\n";
			*/
			$visits_table_data.= '<tr><td>'.$visit.'</td></tr>'."\n"; 
			$visits_table_foot.= '<td>'.$day.'</td>'."\n";
		}
		$visits_table_data.= '</tbody>';
		$visits_table_data.= '<tfoot><tr>'.$visits_table_foot.'</tr></tfoot>';
		$visits_table_data.= '</table>';
	}
endif;

It all kicks off with grabbing the information from Google Analytics. Simply provide the time frame you would like statistics for. I usually choose to retrieve statistics by the month.

The Generated HTML & MooTools JavaScript

<h2>Select Your Month/Year</h2>
<form method="get">
	<select name="month" id="month">
		<option value="">-- Select Month --</option>
		<?php
			for($x = 1; $x <= 12; $x++):
				echo '<option value="',$x,'"',($month == $x ? ' selected="selected"' : ''),'>',date('F',mktime(0,0,0,$x,1,2009)),'</option>';
			endfor;
		?>
	</select>
	<select name="year" id="year">
		<option value="">-- Select Year --</option>
		<?php
			for($x = 2008; $x <= date('Y'); $x++):
				echo '<option value="',$x,'"',($year == $x ? ' selected="selected"' : ''),'>',$x,'</option>';
			endfor;
		?>
	</select>
	<select name="type" id="type">
		<option value="">-- Select Chart Type --</option>
		<?php
			$chart_types = array('Column','Bar','Line','Scatter','Pie');
			foreach($chart_types as $chart_type):
				echo '<option value="',$chart_type,'"',($type == $chart_type ? ' selected="selected"' : ''),'>',$chart_type,'</option>';
			endforeach;
		?>
	</select>
	<input type="submit" name="submit" id="submit" value="Get Statistics!" />
</form>

<?php 
	//php time - echo tables
	if($visits_table_data) { echo '<h3>Visits</h3>', $visits_table_data,'<br />'; } 
?>
<?php if(count($visits)): ?>
	<script type="text/javascript">
		var visits = new MilkChart.<?php echo $_GET['type']; ?>('data-table-visits',{
			width: 960,
			height: 550,
			font: 'tahoma',
			showValues: false,
			useFooter: true
		});
	</script>
<?php endif; ?>

Using the THEAD, TBODY, and TFOOT elements is extremely important in the ensuring the correct labels are placed within the generated chart. The data table itself is very simple. MilkChart will take the above table and create a CANVAS element which will contain the chart.

There are five different chart types you may choose from: Column, Bar, Pie, Line, Scatter. MilkChart takes full advantage of MooTools' inheritance model as each type of chart's class extends the base MilkChart class.

I love the way the MilkChart developer(s) utilized MooTools' OOP/inheritance model to perfection. I also love that MilkChart requires the bare minimum of data for the HTML table. MilkChart isn't without its flaws though. A few of the table types had a fit about including multiple dimensions (using both page views and visits within the same chart, for example) and value label placement has yet to be perfected.

Track.js Error Reporting

Recent Features

  • Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • 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

Discussion

  1. Wow, great idea! This inspired me to make an alternative that works with a self hosted solution (so users can see related statistics in their profiles). Thanks^^

  2. MilkChart is pretty sick. BTW, if you’re comparing this to jQuery Flot you should know that Flot does not have pie charts IIRC.

  3. Matthew

    David, it doesn’t seem to be working. Neither in Opera or IE8.
    IE says “Object doesn’t support this property or method”. Any idea?

  4. @Matthew: IE does not support the CANVAS element which this plugin is based off of. I’ll look further into the Opera issues.

  5. Seeker

    Very nice, sadly the IE incompatibility limit the possibilites of usage a lot :(

  6. What about showing data in a table for unsupported browsers?

    Another thing: It does not seem to be working on Linux (i’m using FireFox [3.0.8] – shared computer at the faculty)..

  7. You should check http://g.raphaeljs.com/ for charts. Works cross browser.

  8. The tool milkchart and the post is very good. I was using jpgraph but I guess with this I can create the graphs which we need mostly for various MIS fastly.

    Thanks
    Hrushikesh Wakadkar

  9. Abba Bryant

    The labels for the wedges in the pie chart align differently than they should. They are very close to the pie chart on one side, and further from the chart ( to the point of being outside the containing element ) on the other side.

    This makes the pie chart style basically worthless since I can’t see what some of the values line up to, and other values I plain can’t see since they get cut off.

  10. Abba Bryant

    FF 3.5.4 OS X 10.5.8 <- broken as above, also the key is spaced to where I only can see the 11th through the 20th using your default september 2009 data.

    Safari 4.0.3 OS X 10.5.8 <- broken as above, but not 'quite' as badly.

  11. Brett

    Thanks for the plug here David :) and all the feedback. I got some time so I will be fixing some bugs and implementing some more features. The biggest bug right now is IE and it should be fixed soon. I also added a color generator in trunk, thats why the pie graph above is half black :)

    Thanks again and glad to see it’s being used!

  12. Derek

    David, the dropdowns are empty for me. Chrome 4.0.237.0 on Karmic64 bit.

  13. Derek

    @Derek:

    Doh! it’s the latest chrome, doing it on several sites.

  14. some bugs and implementing some more features. The biggest bug

  15. For those of you not as tech savvy yet still want to display your Google Analytics in Graphical/Chart form, check out EmbeddedAnalytics ( http://www.embeddedanalytics.com ). This is a site I have developed. You simply define your report (profile, metrics, dimensions, and time-frame). You can then embed the report directly into a webpage simply by embedding a snippet of iframe code.

  16. thanks for you. cool analytics

  17. Is there any way to pull just the stats for one url? like only get the stats for http://davidwalsh.name/milkchart ?

  18. Phan Manh Linh

    i see not ga/analytics.class.php
    please help!
    sorry for english bad.

  19. Its awesome that charts can be visible from the Google Analytics which really helps a lot in evaluating traffic.
    Website ( http://www.techliance.com )also has some useful tools which may help in measuring traffic.

    Only question in my mind is will it be compatible with different internet explorers? Need guidance.

  20. tomonto

    If i want to make the chart real time Updated in every 10 seconds,How to do it??please help me

  21. tomonto

    If i want to make the chart real time Updated in every 10 seconds,How to do it??please help me

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

  • Serve a Directory via Python

    Sometimes I'm working with a test HTML file and some JavaScript but need to work off of a served space.  In that case, I sometimes need to swap out folders within MAMP Stack which leads to a maintenance nightmare.  Bleh. I recently found out that you can...

  • OSCON Portland:  Conference  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...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...