D3js with Angular
Horizontal Stacked Bar Chart
by Rishabh Sharma
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<div ng-controller="MyCtrl">
<bar-chart data="data"></bar-chart>
</div>
CSS
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
#tooltip {
position: absolute;
text-align: center;
width: 40px;
height: auto;
padding: 2px 5px;
background-color: rgba(255, 255, 255, 0.8);
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
-webkit-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
-moz-box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.4);
pointer-events: none;
}
#tooltip.hidden {
display: none;
}
#tooltip p {
margin: 0;
font-family: sans-serif;
font-size: 12px;
line-height: 20px;
}
JavaScript
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
})
.directive('barChart', function($window) {
return {
restrict: 'E',
replace: true,
scope: {
data: '='
},
template: '<div></div>',
link: function(scope, element, attrs, fn) {
console.log('hello');
//var data = scope.data;
var d3 = $window.d3;
var rawSvg = element[0];
var margins = {
top: 12,
left: 64,
right: 24,
bottom: 24
},
legendPanel = {
width: 180
},
width = 500 - margins.left - margins.right - legendPanel.width,
height = 100 - margins.top - margins.bottom,
raw = [{
data: [{
period: 'Last Year',
volume: 123
}, {
period: 'This Year',
volume: 234
}],
name: 'Series #1'
}, {
data: [{
period: 'Last Year',
volume: 235
}, {
period: 'This Year',
volume: 267
}],
name: 'Series #2'
}
],
series = raw.map(function(d) {
return d.name;
}),
dataset = raw.map(function(d) {
return d.data.map(function(o, i) {
// Structure it so that your numeric
// axis (the stacked amount) is y
return {
y: o.volume,
x: o.period
};
});
}),
volumes = [0, 0],
stack = d3.layout.stack();
raw.forEach(function(a) {
a.data.forEach(function(b) {
if (b.period === 'Last Year') {
volumes[0] += b.volume;
} else {
volumes[1] += b.volume;
}
})
});
...