D3.js – Drawing Charts


D3.js – Drawing Charts


”;


D3.js is used to create a static SVG chart. It helps to draw the following charts −

  • Bar Chart
  • Circle Chart
  • Pie Chart
  • Donut Chart
  • Line Chart
  • Bubble Chart, etc.

This chapter explains about drawing charts in D3. Let us understand each of these in detail.

Bar Chart

Bar charts are one of the most commonly used types of graph and are used to display and compare the number, frequency or other measure (e.g. mean) for different discrete categories or groups. This graph is constructed in such a way that the heights or lengths of the different bars are proportional to the size of the category they represent.

The x-axis (the horizontal axis) represents the different categories it has no scale. The y axis (the vertical axis) does have a scale and this indicates the units of measurement. The bars can be drawn either vertically or horizontally depending upon the number of categories and length or complexity of the category.

Draw a Bar Chart

Let us create a bar chart in SVG using D3. For this example, we can use the rect elements for the bars and text elements to display our data values corresponding to the bars.

To create a bar chart in SVG using D3, let us follow the steps given below.

Step 1Adding style in the rect element − Let us add the following style to the rect element.

svg rect {
   fill: gray;
}

Step 2Add styles in text element − Add the following CSS class to apply styles to text values. Add this style to SVG text element. It is defined below −

svg text {
   fill: yellow;
   font: 12px sans-serif;
   text-anchor: end;
}

Here, Fill is used to apply colors. Text-anchor is used to position the text towards the right end of the bars.

Step 3Define variables − Let us add the variables in the script. It is explained below.

<script>
   var data = [10, 5, 12, 15];
   var width = 300,
      scaleFactor = 20,
      barHeight = 30;
</script>

Here,

  • Width − Width of the SVG.

  • Scalefactor − Scaled to a pixel value that is visible on the screen.

  • Barheight − This is the static height of the horizontal bars.

Step 4Append SVG elements − Let us append SVG elements in D3 using the following code.

var graph = d3.select("body")
   .append("svg")
   .attr("width", width)
   .attr("height", barHeight * data.length);

Here, we will first select the document body, create a new SVG element and then append it. We will build our bar graph inside this SVG element. Then, set the width and height of SVG. Height is calculated as bar height * number of data values.

We have taken the bar height as 30 and data array length is 4. Then SVG height is calculated as barheight* datalength which is 120 px.

Step 5Apply transformation − Let us apply the transformation in bar using the following code.

var bar = graph.selectAll("g") 
   .data(data)
   .enter()
   .append("g")
   .attr("transform", function(d, i) {
      return "translate(0," + i * barHeight + ")";
   });

Here, each bar inside corresponds with an element. Therefore, we create group elements. Each of our group elements needs to be positioned one below the other to build a horizontal bar chart. Let us take a transformation formula index * bar height.

Step 6Append rect elements to the bar − In the previous step, we appended group elements. Now add the rect elements to the bar using the following code.

bar.append("rect")
   .attr("width", function(d) {
      return d * scaleFactor;
   })
   .attr("height", barHeight - 1);

Here, the width is (data value * scale factor) and height is (bar height – margin).

Step 7Display data − This is the last step. Let us display the data on each bar using the following code.

bar.append("text")
   .attr("x", function(d) { return (d*scaleFactor); })
   .attr("y", barHeight / 2)
   .attr("dy", ".35em")
   .text(function(d) { return d; });

Here, width is defined as (data value * scalefactor). Text elements do not support padding or margin. For this reason, we need to give it a “dy” offset. This is used to align the text vertically.

Step 8Working example − The complete code listing is shown in the following code block. Create a webpage barcharts.html and add the following changes.

barcharts.html

<html>
   <head>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
      <style>
         svg rect {
            fill: gray;
         }
         
         svg text {
            fill: yellow;
            font: 12px sans-serif;
            text-anchor: end;
         }
      </style>
   </head>

   <body>
      <script>
         var data = [10, 5, 12, 15];
         
         var width = 300 
            scaleFactor = 20, 
            barHeight = 30;
         
         var graph = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", barHeight * data.length);
         
         var bar = graph.selectAll("g")
            .data(data)
            .enter()
            .append("g")
            .attr("transform", function(d, i) {
               return "translate(0," + i * barHeight + ")";
            });
         bar.append("rect").attr("width", function(d) {
            return d * scaleFactor;
         })
         
         .attr("height", barHeight - 1);
         
         bar.append("text")
            .attr("x", function(d) { return (d*scaleFactor); })
            .attr("y", barHeight / 2)
            .attr("dy", ".35em")
            .text(function(d) { return d; });
      </script>
   </body>
</html>

Now request your browser, you will see the following response.

piechart

Donut Chart

Donut or Doughnut chart is just a simple pie chart with a hole inside. We can define the hole radius to any size you need, both in percent or pixels. We can create a donut chart instead of a pie chart. Change the inner radius of the arc to use a value greater than zero. It is defined as follows.

var arc = d3.arc()
   .outerRadius(radius)
   .innerRadius(100);

Same as the pie chart coding and with a slightly changed inner radius, we can generate a donut chart. Create a webpage dounutchart.html and add the following changes in it.

Donutchart.html

<!DOCTYPE html>
<html>
   <head>
      <style>
         .arc text {
            font: 12px arial;
            text-anchor: middle;
         }
        
         .arc path {
            stroke: #fff;
         }
        
         .title {
            fill: green;
            font-weight: italic;
         }
      </style>
      <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script>
   </head>

   <body>
      <svg width = "400" height = "400"></svg>
      <script>
         var svg = d3.select("svg"),
            width = svg.attr("width"),
            height = svg.attr("height"),
            radius = Math.min(width, height) / 2;
        
         var g = svg.append("g")
            .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
        
         var color = d3.scaleOrdinal([
            ''gray'', ''green'', ''brown'', ''orange'', ''yellow'', ''red'', ''purple''
         ]);
        
         var pie = d3.pie().value(function(d) { 
            return d.percent; 
         });
        
         var path = d3.arc()
            .outerRadius(radius)
            .innerRadius(100);
        
         var label = d3.arc()
            .outerRadius(radius)
            .innerRadius(radius - 80);
        
         d3.csv("populations.csv", function(error, data) {
            if (error) {
               throw error;
            }
            
            var arc = g.selectAll(".arc")
               .data(pie(data))
               .enter()
               .append("g")
               .attr("class", "arc");
               arc.append("path")
                  .attr("d", path)
                  .attr("fill", function(d) { return color(d.data.states); });
           
               console.log(arc)
           
               arc.append("text")
                  .attr("transform", function(d) { 
                     return "translate(" + label.centroid(d) + ")"; 
                   })
                  .text(function(d) { return d.data.states; });
         });
         
         svg.append("g")
            .attr("transform", "translate(" + (width / 2 - 120) + "," + 20 + ")")
            .append("text")
            .attr("class", "title")
      </script>
   </body>
</html>

Here, we have changed the path variable as −

var path = d3.arc()
   .outerRadius(radius)
   .innerRadius(100);

We set the innerRadius value>0 to generate a donut chart. Now, request the browser and we can see the following response.

Donut Chart
Advertisements

Leave a Reply

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