Created
June 28, 2012 00:29
-
-
Save cam-gists/3007863 to your computer and use it in GitHub Desktop.
JavaScript: NVD3.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
anonymous function to init graph | |
*/ | |
function callAjax(controller, method, params) { | |
return $.ajax({ | |
url: '/th_ci/' + controller + '/' + method + '/' + params, | |
type: 'POST', | |
dataType: 'json', | |
success: function(data){} | |
}); | |
} | |
// Ajax Call | |
stuff = callAjax('news','get', ''); | |
/************************************** | |
* Data Parser | |
*/ | |
function value(obj, name, color) { | |
var val = []; | |
for (var i = 0; i < obj.length; i++) { | |
val.push({ | |
x: parseDate(obj[i].date), | |
y: parseInt(obj[i].impressions,10) | |
}); | |
} | |
return [{ | |
values: val, | |
key: name, | |
color: color | |
}]; | |
} | |
/************************************************************************ | |
Calculate Number of Days in Date Range | |
************************************************************************/ | |
function days_between(date1, date2) { | |
var d1 = parseDate(date1.replace(/\-/g,'.')); | |
var d2 = parseDate(date2.replace(/\-/g,'.')); | |
// The number of milliseconds in one day | |
var ONE_DAY = 1000 * 60 * 60 * 24; | |
// Calculate the difference in milliseconds | |
var difference_ms = Math.abs(d2 - d1); | |
// Convert back to days and return | |
return Math.round(difference_ms/ONE_DAY) + 1; | |
} | |
// Date Prser for Safari | |
function parseDate(input, format) { | |
format = format || 'yyyy-mm-dd'; // default format | |
var parts = input.match(/(\d+)/g), | |
i = 0, fmt = {}; | |
// extract date-part indexes from the format | |
format.replace(/(yyyy|dd|mm)/g, function(part) { fmt[part] = i++; }); | |
return new Date(parts[fmt['yyyy']], parts[fmt['mm']]-1, parts[fmt['dd']]); | |
} | |
/*** | |
Graph Function | |
*/ | |
nv.addGraph(function() { | |
var chart = nv.models.lineChart(); | |
chart.xAxis | |
.axisLabel('Date (time)') | |
.tickFormat(function(d) { | |
return d3.time.format('%x')(new Date(d)); // Make date | |
}); | |
chart.yAxis | |
.axisLabel('Impressions (i)') | |
.tickFormat(function(d) { return d3.format(',f')(d) ;}); // Make commas | |
//.tickFormat(d3.format(',f')); | |
//Once the ajax request is done then access the Global Value | |
window.stuff.done(function(data) { | |
d3.select('#chart svg') | |
.datum(value(data, 'impressions', '#000')) | |
.transition().duration(500) | |
.call(chart); | |
}); | |
nv.utils.windowResize(function() { d3.select('#chart svg').call(chart);}); | |
return chart; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment