Back to Top

How to create charts using D3 JS .

Updated 27 December 2016

In this blog , we will learn how to create the charts using d3(Data Driven Documents JS ) . First of all we have to download its library from https://d3js.org/  or we can use the cdn  <script src=”https://d3js.org/d3.v4.min.js”></script> .

After including the library or using cdn , we can create the charts very easily . For creating the pie chart we can use the following code :

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package chart
 * @author Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

function pie_chart(donut){
    var w = 300,                        
    h = 400,                            
    r = 200,                            
    color = d3.scale.category10();     
    
    var vis = d3.select('#report_div')
        .append("svg:svg")              
        .data([data])                   
            .attr("width", '100%')      
            .attr("height", h)
            
        .append("svg:g")                
            .attr("transform", "translate(" + r + "," + r + ")")
            if (donut) {
              var arc = d3.svg.arc()              
              .innerRadius(r/2)
              .outerRadius(r);
            }else{
              var arc = d3.svg.arc()              
              .outerRadius(r);
            }
    
        
    var pie = d3.layout.pie()           
        .value(function(d) { 
          return d.value;   
        });
    var arcs = vis.selectAll("g.slice")     
        .data(pie)                          
        .enter()                            
            .append("svg:g")                
                .attr("class", "slice")
                .on("mouseover", mouseOverArc_pie)
           .on("mousemove", mouseMoveArc)
           .on("mouseout", mouseOutArc)
              
        arcs.append("svg:path")
                .attr("fill", function(d, i) { return color(i); } ) 
                .attr("d", arc);                                    
        arcs.append("svg:text")                                     
                .attr("transform", function(d) {                    
                d.outerRadius = r;
                d.innerRadius = r/2;
                return "translate(" + arc.centroid(d) + ")rotate(" + angle(d) + ")";   
              })
            .attr("text-anchor", "middle")
            .attr("font-size", "14px")                          
            .text(function(d, i) { 
              return data[i].label;                
            });   
        }

 

Function Description : 

d3.select(selector) : As the name implies , function is used to select the DOM element by using the selector like id , class or element .

Searching for an experienced
Opencart Company ?
Find out More

d3.scale.category10() : The function defines a built-in color scheme in the d3 library . We can also use d3.scale.category20() , d3.scale.category20b() ,d3.scale.category20c()

d3.layout.pie() : The function is used to calculate the inner and outer angle for drawing the pie chart .

d3.svg.axis() : The function is used to draw the horizontal and vertical axis .

d3.tip() : The function is used to specify the tool tip for specific slice / bar in the chart .

The output will be something like this :

We can also create other charts like bar chart , bi-level chart , bullet chart , bubble chart etc . Here’s the code for the bar chart :

/**
 * Webkul Software.
 *
 * @category Webkul
 * @package chart
 * @author Webkul
 * @copyright Copyright (c) 2010-2016 Webkul Software Private Limited (https://webkul.com)
 * @license https://store.webkul.com/license.html
 */

function bar_chart(){
  var margin = {top: 40, right: 20, bottom: 30, left: 65},
      
      height = 400 - margin.top - margin.bottom;
  var color = d3.scale.category10();         
  var formatPercent = d3.format(",d");

  var x = d3.scale.ordinal()
      .rangeRoundBands([0, width], .1);

  var y = d3.scale.linear()
      .range([height, 0]);

  var xAxis = d3.svg.axis()
      .scale(x)
      //.tickSize('20')
      .orient("bottom");

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left")
      
      .tickFormat(formatPercent);

  var tip = d3.tip()
    .attr('class', 'd3-tip')
    .offset([-10, 0])
    .html(function(d) {
      return "<strong>Value:</strong> <span style='color:red'>$" + d.value + "</span>";
    })

  var svg = d3.select("#report_div").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", "500px")
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.call(tip);          

  data.sort(function(a, b){
    return b.value-a.value;
  });
  var max = 0 ;
  max = data[0].value;
    // X Axis Label
    x.domain(data.map(function(d) { return d.label; }));
    y.domain([0,max]);
    if (total>20) {
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "0em")
        .attr("dy", "0.75em")
        .attr("font-size", "10px")
        .attr("transform", "rotate(-35)" );
    } else {
      svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "0em")
        .attr("dy", "0.75em")
        .attr("font-size", "14px")
        .attr("transform", "rotate(-35)" );  
    }    
    

    svg.append("g")
        .attr("class", "y axis")
        .attr("font-size", "14px")
        .call(yAxis)
      .append("text")
        
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .attr("font-size", "14px")
        

    svg.selectAll(".bar")
        .data(data)
      .enter().append("rect")
        //.attr("class", "bar")
        .attr("fill", function(d, i) { return color(i); } ) 
        .attr("x", function(d) { return x(d.label); })
        .attr("width", x.rangeBand())
        .attr("y", function(d) { 
          return y(d.value);
         })
        .attr("height", function(d) {
          return height - y(d.value);
         })
        .on('mouseover', tip.show)
        .on('mouseout', tip.hide)
}

The bar chart will look like as follows :

 

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home