D3js visualization with AngularJS

D3js visualization with AngularJS

D3js is the javascript library for manipulating document 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 that how we can use D3js in AngularJS application. just by adding script library to your HTML file D3 is available globally. but here we are using AngularJS, so it 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 factory.
First will create module d3 for our D3js library.

    angular.module('d3', [])

and then will create factory with the same name as d3, so that it is easily accessible with same namespace after injection to any of the directive or controller 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

D3 Bar Chart
D3js Bar Chart

First will create module and controller for displaying the d3js chart. have a look at below code,

<body ng-app="d3AngularApp">
    <div ng-controller="chartCntrl">
        <div id="bar-chart"></div>
    <!-- Main app module js -->
    <script src="app/app.module.js"></script>
    <script src="app/angular-d3.js" type="text/javascript"></script>

In above index file, we have added app name along with defined controller name, and div with id bar-chart in which will displaying a bar chart.

var app = angular.module('d3AngularApp', ['d3']);
app.controller('chartCntrl', ['d3', '$scope', function(d3, $scope){
    //Bar chart code

So, we have specified 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 function with functionality that will show 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)
        var y = d3.scaleLinear()
            .range([height, 0]);
        var xAxis = d3.axisBottom()
        var yAxis = d3.axisLeft()
            .ticks(10, "%");
        var svg = d3.select("#bar-chart").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .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; })]);
                .attr("class", "x axis")
                .attr("transform", "translate(0," + height + ")")
                .attr("class", "y axis")
                .attr("transform", "rotate(-90)")
                .attr("y", 6)
                .attr("dy", ".71em")
                .style("text-anchor", "end")
                .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 above code you can see one function with name drawBarChart, 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


D3js is a very powerful library to show interactive graph or charts etc. here in this article is to mainly show that how to integrate or inject D3js to AngularJS application. So that, it’s easily injected to any of the controllers of the application and make use of core functionality of D3js.

Like our articles? Get them straight to your inbox!

* indicates required
D3js visualization with AngularJS
Tagged on:         

2 thoughts on “D3js visualization with AngularJS

  • October 14, 2016 at 4:19 pm

    Putting D3JS code in controller is not recommended way to do in AngularJS. D3js code has to be in angular directive.

    • October 15, 2016 at 7:32 am

      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.


Leave a Reply

Your email address will not be published. Required fields are marked *