code,  data science

D3 Experiments

D3 is a Javascript library used for data visualization. You can use this tool to make your webpage data driven. Essentially, you bind your data to components on your website including SVG elements.

Here is code that will create a simple D3 bar chart based on an array of numbers.

  const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
    
    const w = 500;
    const h = 100;
    
    const svg = d3.select("#plot")
                  .append("svg")
                  .attr("width", w)
                  .attr("height", h);
    
    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => 3 * d)
       .attr("fill", "blue")

This will create a very simple bar graph using the numbers in the array to determine the height of the bar. In order for this visualization to be displayed on my webpage here, we need to have a div with an id of “plot” and we need to import the D3 library.

So this is a very simple example that I took from my work at freeCodeCamp. You can do much more with D3 and as I develop more examples I’ll start adding them to this post.

Matt has worked as a data analyst, writer, counselor, and business owner for a total of 20 years. Since the start of his career he's been fascinated by technology and passionate about helping people use modern technology to hack their work and their lives.

Leave a Reply

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