Making SVG with D3.js

Now that we have a basic understanding of SVG and D3, we can make an example that uses both. From a basic boilerplate HTML document, we will use some data to create some circles!

To start, our basic HTML

<!DOCTYPE html>
<html>
  <head>
    <script src="https://d3js.org/d3.v4.min.js"></script>
  </head>
  <body>
    <svg></svg>
    <script></script>
  </body>
</html>

Next, lets work with our <script> tag.

      var dataList = [4,5,4];
      var svg = d3.select("svg");
      svg.attr("width" ,"500px")
         .attr("height","200px")
         .style("background-color","lightgrey");
      svg.selectAll("circle")
         .data(dataList)
         .enter()
             .append("circle")
             .attr("cy","100")
             .attr("cx",function(d,i){return (i+1)*120;})
             .attr("r",function(d){return d*10;})
             .style("fill","blue");

This will create the following SVG




Lets break down the javascript:

      // Create an array we will use for the circle radii 
      var dataList = [4,5,4];
      
      // Select the SVG element and store it in a var called svg
      var svg = d3.select("svg");

      // Using the svg var, set the width, height and bg color
      svg.attr("width" ,"500px")
         .attr("height","200px")
         .style("background-color","lightgrey");
         
      // Select all the circle elements in the svg (there are none)
      svg.selectAll("circle")
         // Join the data to this selection
         .data(dataList)

         // Work with the 'entering' nodes
         .enter()

             // Create a circle for each new node
             .append("circle")

             // Set its center Y to 100
             .attr("cy","100")

             // Using the 2 variable form of the inline function
             // gives us 'd' which is the data element we are
             // currently working with, and 'i' which will be the
             // numeric index of the element. Here I add 1 to the 
             // index and multiply it by 120 to get the center
             // positions of the circles (120, 240 and 260)
             .attr("cx",function(d,i){return (i+1)*120;})

             // Here we set the radius of the circles by multipling
             // the data element by 10. We don't need the 'i' index
             // on this particular attribute
             .attr("r",function(d){return d*10;})

             // Finally, set the fill color to blue
             .style("fill","blue");


This creates the following block of SVG code programmatically.

<svg width="500px" height="200px" style="background-color: lightgrey;">
    <circle cy="100" cx="120" r="40" style="fill: blue;"></circle>
    <circle cy="100" cx="240" r="50" style="fill: blue;"></circle>
    <circle cy="100" cx="360" r="40" style="fill: blue;"></circle>
</svg>

View this example on plunker

Comments