Skip to content

Instantly share code, notes, and snippets.

@cagmz

cagmz/time_series.html

Last active Sep 21, 2017
Embed
What would you like to do?
Time Series graph using moment.js, D3, nvd3, anuglar-nvd3, and Angular.
<html>
<!-- See the pen at https://codepen.io/cagmz/pen/qqRGoY -->
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-nvd3/1.0.9/angular-nvd3.min.js"></script>
<script>
// 1) Declare app
var nvd3_timeseries = angular.module('nvd3_timeseries', ['nvd3']);
// 2) Declare controller
nvd3_timeseries.controller('demo', ['$scope', function($scope) {
// 3) Chart configuration
$scope.options = {
chart: {
type: 'lineChart',
height: 450,
margin: {
top: 20,
right: 20,
bottom: 40,
left: 55
},
x: function(d) {
/* Moment.js will attempt to parse the x coordinate
and return a value in milliseconds
*/
return moment.utc(d.x).valueOf();
},
y: function(d) {
return d.y;
},
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Date',
tickFormat: (function(d) {
// 3.1) Format the x ticks
return d3.time.format('%-m/%-d/%-Y')(new Date(d));
})
},
yAxis: {
axisLabel: 'Cats',
axisLabelDistance: -10
},
callback: function(chart) {}
},
title: {
enable: true,
text: 'Time Series graph'
}
};
$scope.dateRange = function dateRange(startDate, endDate) {
// http://stackoverflow.com/a/23796069
var dates = [];
var currDate = startDate.clone().startOf('day');
var lastDate = endDate.clone().startOf('day');
while (currDate.add(1, 'days').diff(lastDate) <= 0) {
dates.push(currDate.clone().toDate());
}
return dates;
};
// 4) Chart data
$scope.data = generateTimeSeries();
function generateTimeSeries() {
// Generate an array of dates for plotting
var dateRange = $scope.dateRange(moment().subtract(7, 'days'), moment());
// Plottable will be an array of (x, y) objects
var plottable = dateRange;
plottable.forEach(function to_utc(date, index) {
console.log('a[' + index + '] = ' + date);
// set x value to date and y to a random value
var rand = Math.round((Math.random() * (100 - 1) + 1));
var point = {
x: date,
y: rand
};
// Replace original element
plottable[index] = point;
});
// Return the plottable array for plotting
return [{
values: plottable,
key: 'Cats',
color: '#1b75ba'
}];
};
}]);
</script>
</head>
<body>
<div ng-app="nvd3_timeseries">
<div ng-controller="demo">
<nvd3 options="options" data="data"></nvd3>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.