Monday, 13 July 2015

D3 Pie-Chart

    Hola!
    This tutorial will give the basics of creating a pie-chart using D3.js. New to D3? No worries. We will give you a brief understanding of D3 too.
    So, what is  D3?
    D3–Data-Driven Documents is a JavaScript library for producing dynamic and interactive data visualizations in web browsers using widely implemented SVG, HTML5, and CSS standards.
    JavaScript D3.js library is embedded within an HTML webpage and uses pre-built JavaScript functions to select elements, create SVG objects, style them, or add transitions, dynamic effects. Briefly, it allows you to dynamically manipulate the properties and attributes of your HTML document elements and it can create and manipulate SVG elements as well.
    We can easily bind large data set to SVG objects using simple D3.js functions.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.
    The data can be in various formats, most commonly JSON,CSV geoJSON, but if required, JavaScript functions can be written to read other data formats as well.
    For more information on this, you can visit this link D3-intro
    Until now, you must have understood what D3 is all about.Here we shall describe how to create a pie chart using D3

    pie-chart-1
    As you see in the above figure, a pie chart is composed of multiple arc-like paths, with different fill colours. D3.js provides a helper functions to draw arcs. Arcs are drawn using 4 main parameters: startAngle, endAngle, innerRadius and outerRadius.In case of pie-charts, the innerRadius is zero.
    To draw an arc, first add the following SVG element:
    var width = 550;
    var height = 350;
    var color = d3.scale.category20b();  //builtin range of colors
    var svg = d3.select('#pie_chart').append('svg').attr('width', width).attr('height', height).append('g').attr('transform', 'translate(' + (width / 2) +',' + (height / 2) + ')');
    Now draw an arc using:
    var arc = d3.svg.arc().outerRadius(radius);
    Next, we create a pie element of D3 using:
    var pie = d3.layout.pie().value(function(d,i) { return  pie_data[i]; }).sort(null);
    We now create the path and append it to our SVG element, using     .append(“path”); assign data of pie_data and then assign the “arc” to its “d”     attribute.To append arcs dynamically based on our data, we select path, bind our data to the selections and append new paths accordingly.
    var path = svg.selectAll('path')
    .data(pie(data))
    .enter()
    .append('path')
    .attr('d', arc)
    .attr('fill', function(d, i) {
    return data[i].color;
    });
    where data is:
    [
    { "count": 10,"color":"rgb(0,154,205)" },
    { "count": 20 ,"color":"rgb(139,119,101)"},
    { "count": 30,"color":"rgb(255,140,0)" },
    { "count": 40,"color":"rgb(127,255,0)" }
    ]
    Now that you have understood the basics, you can jump right in to the code:
    Step 1:
    To create a pie chart, we first need the libraries , which will be inside the script tag (script tag which is inside html <head></head> tag):
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script> //JQuery
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js" charset="utf-8"></script>//D3 
    Next, define a <div id=”pie_chart”> </div> tag.
    Step 2: 
    You must have a sample_data.json file in the directory where your is present.
    sample_data.json
    [
    { "count": 10,"color":"rgb(0,154,205)" },
    { "count": 20 ,"color":"rgb(139,119,101)"},
    { "count": 30,"color":"rgb(255,140,0)" },
    { "count": 40,"color":"rgb(127,255,0)" }
    ]
    Step 3:
    Lastly, we define a Script tag. We will write the actual code here to render the pie-chart.
    <script>
    var width = 550;          //width
    var height = 350;        //height
    var radius = 300/ 2;   //radius of the pie-chart
    var color = d3.scale.category20b();    //builtin range of colors
    var svg = d3.select('#pie_chart')        //create the SVG element inside the <body>
    .append('svg')
    .attr('width', width) //set the width and height of our visualization
    .attr('height', height) // attributes of the <svg> tag
    .append('g')              //create a group to hold our pie chart
    .attr('transform', 'translate(' + (width / 2) +
    ',' + (height / 2) + ')');//move the center of the pie chart from 0, 0 to specified value
    var total=0;
    d3.json("sample_data.json", function(error, data) {
    for(var a=0;a<data.length;a++){
    total=total+parseInt(data[a].count); // simple logic to calculate total of data count value
    console.log(total);
    }
    var pie_data=[];
    for( var a=0;a<data.length;a++){ // simple logic to calculate percentage data for the pie
    pie_data[a]=(data[a].count/total)*100;
    }
    var arc = d3.svg.arc().outerRadius(radius);
    // creating arc element.
    var pie = d3.layout.pie()
    .value(function(d,i) { return pie_data[i]; })
    .sort(null);
    //Given a list of values, it will create an arc data for us
    //we must explicitly specify it to access the value of each element in our data array
    var path = svg.selectAll('path')
    .data(pie(data))
    .enter()
    .append('path')
    .attr('d', arc)
    .attr('fill', function(d, i) {
    return data[i].color;
    });
    //set the color for each slice to be chosen, from the color defined in sample_data.json
    //this creates the actual SVG path using the associated data (pie) with the arc drawing function
    });
    </script>
    Here’s the output !

    pie-chart-2

2 comments:

  1. HI Poonam,
    I need a little help on these charts. I am using fusionchart library, i have to Show data on US MAP. data is on xml files.

    ReplyDelete
  2. Hey..what kind of data do you want to show ?? can you just give an example?

    ReplyDelete