Drawing Pie Chart in D3

D3.js is a JavaScript library that is widely used in data visualization and animation. The power of d3.js and its flexibility comes at the expense of its steep learning curve. There are some libraries built on top of it that provide numerous off-the-shelf charts in order to make the users’ life easier.
Its power comes from two additional functionality. It can also create and manipulate SVG elements, and it can also bind the DOM or SVG elements to arrays of data, so that any changes in that data will be reflected on those elements they are bind to. There are numerous SVG shapes, such as circles, rectangles, paths and texts. Those shapes serve as the building blocks of your visualization’s.

How to draw pie charts?

In this article, we are going to create pie charts. Pie charts are built using SVG paths. The SVG path is a more advanced shape compared to circles and rectangles, since it uses path commands to create any arbitrary shape we want. D3.js provides a helper functions to draw arcs. Arcs are drawn using 4 main parameters: startAngle, endAngle, innerRadius and outerRadius.

How to draw an arc?

In pie charts drawing arc is easy because of d3. We just have to specify the inner radius to 0 and outer radius to 100. After that we have to give a startAngel and a endAngel. Just like the below shows.

var arc = d3.svg.arc()

Or, if you want to do it more easily than this. Then there is a short format for it. Which is shown in the below.

var arc = d3.svg.arc()              

In the above code we do not have startAngel or endAngel. Because the data we will provide to arc will make the angels automatically.
We learnt how to create an arc. Pie charts are composed of multiple arcs the angle of each of them represents the value of one item of our data to the overall data values. In other words if we have 3 mobile brands, A, B and C, where A has 20% of the market share, while B has 50% of the market share and C has 30% . To implement this using the d3.js way, you need to have an array of data and bind it to arcs. In the below example we have introduced an element called ‘label’ which will distinguish the sections of the chart.

data = [{"label":"A", "value":20}, 
            {"label":"B", "value":50}, 
            {"label":"C", "value":30}];

We can even write down the data percentage in the label for better understanding. Just like

data = [{"label":"A20", "value":20}, 
            {"label":"B50", "value":50}, 
            {"label":”C30", "value":30}];

This will help the viewer to understand, how much market share every company has, at a glance.
So, as we have observed many aspects of a pie chart. Now it is time for to create a pie chart for ourselves. First let’s take a look at the example. The example is basis on the three branded mobile companies, whom we were talking in the above. Let us look through coding first:

<!DOCTYPE html>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Testing Pie Chart</title>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js?2.1.3"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js?2.1.3"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js?2.1.3"></script>
     <style type="text/css">
        .slice text {
            font-size: 16pt;
            font-family: Arial;
    <script type="text/javascript">
     var w = 300,                        
    h = 300,                            
    r = 100,                            
    color = d3.scale.category20c();    
     data = [{"label":"A", "value":20}, 
            {"label":"B", "value":50}, 
            {"label":"C", "value":30}];
        var vis = d3.select("body")
            .attr("width", w)           
            .attr("height", h)
            .attr("transform", "translate(" + r + "," + r + ")")    
     var arc = d3.svg.arc()  
     var pie = d3.layout.pie()          
        .value(function(d) { return d.value; });    
     var arcs = vis.selectAll("g.slice")     
                .attr("class", "slice");    
                .attr("fill", function(d, i) { return color(i); } ) 
                .attr("d", arc);                                    
                .attr("transform", function(d) {                    
                d.innerRadius = 50;
                d.outerRadius = 100;
                return "translate(" + arc.centroid(d) + ")";        
            .attr("text-anchor", "middle")                          
            .text(function(d, i) { return data[i].label; });        

Now let us look at the output:

pie chart

In the above article we have talked about the pie charts in a long way. But you should know that you can use this same concept to create better charts than this. Like donut chart, Florence Nightingale’s Polar Chart, multilevel pie chart, etc.

If you find this article helpful, you can connect us in Google+ and Twitter.

Leave a Reply

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