D3js is the javascript library for manipulating documents based on data.
D3 stands for Data-Driven Documents. D3 will help us to create great visualization of graphs, charts, etc. with the help of SVG, CSS, and HTML DOM manipulations.
In this tutorial will see how we can use D3js in the AngularJS application. just by adding a script library to your HTML file, D3 is available globally. but here we are using AngularJS, so it is better to inject and use rather than globally.
Let’s start creating the first D3js chart. Before that will see how we can use d3 with dependency injection.
Using d3 with dependency injection
For version 4
So, by using dependency injection, we can keep our global namespace clean and inject dependencies like other services or factories.
First will create module d3 for our D3js library.
angular.module('d3', [])
and then will create a factory with the same name as d3, so that it is easily accessible with the same namespace after injection to any of the directives or controllers of our AngularJS app.
angular.module('d3', [])
.factory('d3', [function(){
var exports = {};
// insert d3 code here
return exports;
}];
Now, let’s add D3js library code to our factory. currently version 4 is on going. you can download latest version from here : https://d3js.org/d3.v4.js
After downloading, we need to add piece of lines code to our factory. If you can open downloaded file, we need to copy following piece of code,
from var version = "4.x.y";
to, one line before Object.defineProperty(exports, '__esModule', { value: true }); at the end.
and paste that code to above-specified factory where “insert d3 code here” is written.
For version 3
Also for version 3 has different code structure, so will inject same way as above factory code,
angular.module('d3', [])
.factory('d3', [function(){
// insert d3 code here
return d3;
}];
Same way we have to add d3 version 3 of code from here : https://d3js.org/d3.v3.js
After downloading, we need to add piece of lines code to our factory. If you can open downloaded file, we need to copy following piece of code,
from var d3;
to, one line before if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3; at the end.
and paste that code to above specified factory where “insert d3 code here” is written.
Note : D3js version 4 has different updated and more prescribed functions. Make sure you have injected proper version of D3js code before using in to your application.
You can have a look at final d3 version 4 factory here : angular-d3.v4.js and version 3 factory here : angular-d3.v3.js link for AngularJS app. according to version 4.2.2 & version 3.5.17. We can always update this file according to above strategy based on latest version of D3js.
Let’s create the first bar chart with updated new version 4 of D3js
Create Bar chart
First will create a module and controller for displaying the d3js chart. have a look at the below code,
<body ng-app="d3AngularApp">
<div ng-controller="chartCntrl">
<div id="bar-chart"></div>
</div>
<!-- Main app module js -->
<script src="app/app.module.js"></script>
<script src="app/angular-d3.js" type="text/javascript"></script>
</body>
In the above index file, we have added the app name along with the defined controller name, and div with the id bar chart which will display a bar chart.
var app = angular.module('d3AngularApp', ['d3']);
app.controller('chartCntrl', ['d3', '$scope', function(d3, $scope){
//Bar chart code
}]);
So, we have specified the app name with d3AngularApp and controller chartCntrl. Also injected d3 to module and controller for use of core functions to AngularJs application.
Now will create a function with functionality that will show a bar chart,
var app = angular.module('d3AngularApp', ['d3']);
app.controller('chartCntrl', ['d3', '$scope', function(d3, $scope){
$scope.drawBarChart = function(){ // Function for creating bar chart
var margin = {top: 20, right: 20, bottom: 30, left: 40},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scaleBand()
.rangeRound([0, width], .1)
.paddingInner(0.1);
var y = d3.scaleLinear()
.range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x);
var yAxis = d3.axisLeft()
.scale(y)
.ticks(10, "%");
var svg = d3.select("#bar-chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("assets/mockData/data.tsv", type, function(error, data) {
if (error) throw error;
x.domain(data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.bandwidth())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); });
});
function type(d) {
d.frequency = +d.frequency;
return d;
}
}
$scope.drawBarChart(); // Call to draw bar chart
}]);
So, in the above code, you can see one function with the name drawBarChart, which is to draw a bar chart. In which we have added all the functionality related to D3js.
To know more core functionality related to D3js visit : https://github.com/d3/d3/wiki
Conclusion
D3js is a very powerful library to show interactive graphs or charts etc. here this article mainly shows how to integrate or inject D3js into the AngularJS application. So that, it’s easily injected into any of the controllers of the application and makes use of the core functionality of D3js.

Meet Mukul, a passionate visionary and a dedicated 3D printing enthusiast. With an insatiable curiosity for technology and a flair for creativity, Mukul has discovered a world where innovation knows no bounds. Armed with a deep understanding of 3D printing and its endless possibilities, he has become a true pioneer in the field, constantly pushing the boundaries of what can be achieved with this remarkable technology.
Putting D3JS code in controller is not recommended way to do in AngularJS. D3js code has to be in angular directive.
Hi,
Yes, you are right. In this tutorial, our aim is just to explain how we can use d3 as a service injection in a controller/Directive and then use it instead globally. however, we can use that in any of the directives.
Thanks.