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 ="#plot")
                  .attr("width", w)
                  .attr("height", h);
       .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.

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.